<script>
import { defineComponent } from "vue";

export default defineComponent({
  beforeRouteEnter(to, from, next) {
    if (from.path != "/editRoadshow") {
      sessionStorage.removeItem("roadshowEssenceBack");
    }
    next();
  },
});
</script>

<script setup>
import { ref, computed, onMounted, reactive, toRefs, watch } from "vue";

import mPage from "@/components/mPage.vue";
import { raiInterface } from "@/api/api.js";
import { Calendar, Search, InfoFilled } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { onBeforeRouteLeave, useRouter, useRoute } from "vue-router";

const $route = useRoute();
const $router = useRouter();

const pageState = reactive({
  page_no: sessionStorage.getItem("roadshowEssenceBack") ? JSON.parse(sessionStorage.getItem("roadshowEssenceBack")).page_no : 1,
  total: 0, //条数
  PageSize: 10, //每页显示几条
  industry: "", //行业
  status: "", //发布状态
  issueTime: "", //时间
  chartPermissionList: [], //行业的数组
  options: [
    { id: 0, name: "未发布" },
    { id: 1, name: "已发布" },
  ], //发布的数组
  tableData: [], //表格
  keyWord: "",
});

const sta = computed(() => {
  return pageState.status === 0 ? pageState.status : pageState.status === 1 ? pageState.status : 2;
});

onMounted(() => {
  if (sessionStorage.getItem("roadshowEssenceBack")) {
    const initialize = JSON.parse(sessionStorage.getItem("roadshowEssenceBack"));
    pageState.status = initialize.status;
    pageState.issueTime = initialize.issueTime;
    pageState.industry = initialize.industry;
    pageState.keyWord = initialize.keyWord;
  }
  getList();
  getIndustryList();
});

//获取list数组
async function getList() {
  const res = await raiInterface.roadshowEssenceList({
    CurrentIndex: pageState.page_no,
    PageSize: pageState.PageSize,
    PublishStatus: sta.value - 0,
    ChartPermissionId: pageState.industry,
    StartDate: pageState.issueTime[0],
    EndDate: pageState.issueTime[1],
    KeyWord: pageState.keyWord,
  });
  if (res.Ret === 200) {
    pageState.tableData = res.Data.List;
    pageState.total = res.Data.Paging.Totals;
  }
}
//获取行业
async function getIndustryList() {
  const res = await raiInterface.chartPermissionFirstHaveIco();
  if (res.Ret === 200) {
    pageState.chartPermissionList = res.Data.List;
  }
}
//选择后的事件
function conditionChange() {
  pageState.page_no = 1;
  getList();
}
//发布，取消发布，删除
function operationBtn(id, value) {
  ElMessageBox.confirm(`确定${value}该文章吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (value == "删除") {
        const res = await raiInterface.roadshowEssenceDelete({ ArticleId: id });
        if (res.Ret === 200) {
          ElMessage.success("删除成功！");
          let page_num = Math.ceil((pageState.total - 1) / pageState.PageSize);
          if (pageState.page_no > page_num) {
            pageState.page_no = page_num;
          }
          getList();
        }
      } else {
        const res = await raiInterface.roadshowEssencePublishAndCancel({ ArticleId: id });
        if (res.Ret === 200) {
          ElMessage.success(value + "成功！");
          getList();
        }
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `已取消${value}`,
      });
    });
}
//文章详情
function goDetail(row) {
  let { href } = $router.resolve({ name: "预览路演精华", query: { ArticleId: row.ArticleId } });
  window.open(href, "_blank");
}
//分页
function handleCurrentChange(page) {
  pageState.page_no = page;
  getList();
}
function editReport(id, status) {
  $router.push({
    path: "/editRoadshow",
    query: { id },
  });
}
function keyValueInpt() {
  pageState.page_no = 1;
  getList();
  init();
}
function init() {
  pageState.industry = ""; //行业
  pageState.status = ""; //发布状态
  pageState.issueTime = ""; //时间
}
//导出pv uv
function exportPvUv(id) {
  const url = import.meta.env.VITE_APP_API_ROOT + "/cygx/reportSelection/articleHistoryExport?ArticleId=" + id + "&Source=2&" + localStorage.getItem("auth") || "";
  return url;
}

onBeforeRouteLeave((to, from, next) => {
  let backData = {
    page_no: pageState.page_no,
    status: pageState.status, //状态
    issueTime: pageState.issueTime, //时间
    industry: pageState.industry,
    keyWord: pageState.keyWord,
  };
  sessionStorage.setItem("roadshowEssenceBack", JSON.stringify(backData));
  next();
});

const { page_no, total, PageSize, industry, status, issueTime, chartPermissionList, options, tableData, keyWord } = toRefs(pageState);
</script>

<template>
  <div class="container-essence">
    <el-card>
      <div class="top-box">
        <div class="top-container">
          <el-select placeholder="行业" clearable v-model="industry" @change="conditionChange" style="margin-bottom: 20px">
            <el-option v-for="item in chartPermissionList" :label="item.PermissionName" :key="item.ChartPermissionId" :value="item.ChartPermissionId"></el-option>
          </el-select>
          <el-select placeholder="发布状态" clearable v-model="status" @change="conditionChange" style="margin-bottom: 20px">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <date-picker v-model="issueTime" type="date" range placeholder="发布时间" value-type="format" @change="conditionChange"> </date-picker>
          <div class="top-input">
            <el-input :prefix-icon="Search" @input="keyValueInpt" v-model="keyWord" placeholder="请输入报告标题" clearable style="display: inline-block"> </el-input>
          </div>
        </div>
        <div>
          <el-button type="primary" @click="$router.push('/addRoadshow')">添加</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="" align="center" label="标题" min-width="260">
          <template #default="scope">
            <span class="editsty" @click="goDetail(scope.row)">{{ scope.row.Title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Periods" align="center" label="期数" width="108"></el-table-column>
        <el-table-column prop="PublishDate" align="center" label="发布时间" min-width="160"></el-table-column>
        <el-table-column prop="LastUpdatedTime" align="center" label="更新时间" min-width="160"></el-table-column>
        <el-table-column align="center" label="发布状态" min-width="108">
          <template #default="scope">
            {{ scope.row.PublishStatus == 1 ? "已发布" : "未发布" }}
          </template>
        </el-table-column>
        <el-table-column width="135" label="PV / UV" align="center">
          <template #header>
            <div style="display: flex; align-items: center; justify-content: center">
              <p style="margin-right: 5px">PV / UV</p>
              <el-tooltip placement="top-start">
                <template #content>
                  <p>pv：报告被打开的次数，每次打开都计算一次（只统计有权限用户）</p>
                  <p>uv：访问报告的人数，每篇报告同一个人访问只计算一次（只统计有权限用户）</p>
                </template>
                <el-icon><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <div class="pv-uv-download">
              <span>{{ scope.row.Pv }}/{{ scope.row.Uv }}</span>
              <a :href="exportPvUv(scope.row.ArticleId)" download>
                <img src="~@/assets/img/rai_m/pvuv_download.png" alt="" />
              </a>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="165">
          <template #default="scope">
            <span v-if="scope.row.PublishStatus !== 1" class="editsty" @click="operationBtn(scope.row.ArticleId, '发布')">发布&nbsp;&nbsp;</span>
            <span v-else class="editsty" @click="operationBtn(scope.row.ArticleId, '取消发布')">取消发布&nbsp;&nbsp;</span>
            <span class="editsty" @click="editReport(scope.row.ArticleId)">编辑&nbsp;&nbsp;</span>
            <span v-if="scope.row.PublishStatus !== 1 && !scope.row.Periods" class="deletesty" @click="operationBtn(scope.row.ArticleId, '删除')">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-col :span="24" class="toolbar">
        <m-page :total="total" :page_no="page_no" :pageSize="10" @handleCurrentChange="handleCurrentChange" />
      </el-col>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.container-essence {
  .top-box {
    display: flex;
    justify-content: space-between;
    .top-container {
      .el-select {
        width: 240px;
        margin-right: 20px;
      }
      .top-input {
        display: inline-block;
        width: 521px;
        margin-bottom: 20px;
      }
    }
  }
  .mx-datepicker {
    width: 230px !important;
    margin-right: 25px;
  }
  .pv-uv-download {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 14px;
      height: 14px;
      margin-left: 10px;
    }
  }
}
</style>
