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

export default defineComponent({
  beforeRouteEnter(to, from, next) {
    if (from.path != "/editSummary") {
      sessionStorage.removeItem("summaryManageBack");
    }
    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 ShortcutDialog from "../components/shortcutDialog.vue";
import GenerationAsk from "../components/generationAsk.vue";
import FocusCollection from "../components/focusCollection.vue";

import { Search } 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("summaryManageBack") ? JSON.parse(sessionStorage.getItem("summaryManageBack")).page_no : 1,
  dataList: [], //表格内容
  industry: "", //行业
  status: "", //状态
  issueTime: "", //时间
  valueAuthor: "", //作者昵称
  authorOptions: [], //作者数组
  options: [
    { id: 0, name: "未发布" },
    { id: 1, name: "已发布" },
  ],
  titleValue: "", //标题关键词
  total: 0, //条数
  PageSize: 10, //每页显示几条
  chartPermissionList: [], //行业的数组
  shortcutIsDialog: false, //
  isClientSwitch: false, //
  generaitondialogVisib: false, //代问的弹框
  generaitonId: "",
  generaitonType: "纪要",
  tabsList: [
    { id: 1, name: "纪要" },
    { id: 2, name: "观点" },
  ],
  tabsIndex: 1,
  collectionDlgShow: false, //关注 收藏 隐显
  collectionId: "", //关注 收藏 id
  collectionType: "", //关注 收藏 类型区分
  token: localStorage.getItem("auth") || "",
  labelSearch: "",
});

watch([() => pageState.titleValue, () => pageState.labelSearch], () => {
  pageState.page_no = 1;
  pageState.getsummaryManageList();
});
watch(
  () => pageState.valueAuthor,
  (newval) => {
    if (newval === "") {
      pageState.authorOptions = [];
    }
  }
);
const sta = computed(() => {
  return pageState.status === 0 ? pageState.status : pageState.status === 1 ? pageState.status : 2;
});
const exportPvUv = computed(() => {
  return import.meta.env.VITE_APP_API_ROOT + "/cygx/summaryManage/articleHistoryExport?ArticleId=";
});
onMounted(() => {
  routerInit();
  chartPermission();
  sustainableDetailSummaryManage();
  remoteMethodAuthor();
  getsummaryManageList();
});

//页面缓存 路由
function routerInit() {
  if (sessionStorage.getItem("summaryManageBack")) {
    const { keyword, status, issueTime, tabs, industry, valueAuthor, labelSearch } = JSON.parse(sessionStorage.getItem("summaryManageBack"));
    pageState.titleValue = keyword;
    pageState.status = status; //状态
    pageState.issueTime = issueTime; //时间
    pageState.tabsIndex = tabs;
    pageState.industry = industry;
    pageState.valueAuthor = valueAuthor;
    pageState.labelSearch = labelSearch;
  }
}
//获取观点
function sustainableDetailSummaryManage() {
  raiInterface.sustainableDetailSummaryManage().then((res) => {
    if (res.Ret === 200) {
      pageState.isClientSwitch = !res.Data.OperationButton;
    }
  });
}

//操作按键 发布 取消发布 删除
function operationBtn(id, value) {
  ElMessageBox.confirm(`确定${value}该纪要吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (value == "删除") {
        const res = await raiInterface.getsummaryManagedelete({ ArticleId: id });
        if (res.Ret !== 200) return;
        ElMessage.success("删除成功！");
        let page_num = Math.ceil((pageState.total - 1) / pageState.PageSize);
        if (pageState.page_no > page_num) {
          pageState.page_no = page_num;
        }
        getsummaryManageList();
      } else {
        const res = await raiInterface.publishAndCancel({ ArticleId: id });
        if (res.Ret !== 200) return;
        ElMessage.success(`${value}成功！`);
        getsummaryManageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `已取消${value}`,
      });
    });
}
//编辑按钮
function editBtn(id) {
  console.log(id);
  $router.push({
    path: "/editSummary",
    query: { id: id },
  });
}
//分页
function handleCurrentChange(page) {
  pageState.page_no = page;
  getsummaryManageList();
}
//获取行业
function chartPermission() {
  raiInterface.summaryManageArticleType().then((res) => {
    if (res.Ret === 200) {
      pageState.chartPermissionList = res.Data.List;
    }
  });
}
//文章详情
async function lookDetail(item) {
  if (item.PublishStatus === 1) {
    let href = `${import.meta.env.VITE_CYGX_WEB}/material/info/${item.ArticleId}`;
    window.open(href, "_blank");
  } else {
    const res = await raiInterface.getsummaryManagedetail({ ArticleId: item.ArticleId });
    if (res.Ret === 200) {
      sessionStorage.setItem("summaryPre", JSON.stringify(res.Data));
      let { href } = $router.resolve({ name: "预览研选报告" });
      window.open(href, "_blank");
    }
  }
}
//列表
function getsummaryManageList() {
  raiInterface
    .getsummaryManageList({
      CurrentIndex: pageState.page_no,
      PageSize: pageState.PageSize,
      PublishStatus: sta.value - 0,
      ArticleTypeId: pageState.industry,
      StartDate: pageState.issueTime[0],
      EndDate: pageState.issueTime[1],
      KeyWord: pageState.titleValue,
      Departmentİd: pageState.valueAuthor,
      Label: pageState.labelSearch,
    })
    .then((res) => {
      if (res.Ret !== 200) return;
      pageState.dataList = res.Data.List;
      pageState.total = res.Data.Paging.Totals;
    });
}
//change 事件
function conditionChange() {
  pageState.page_no = 1;
  getsummaryManageList();
}
function switchClickClient(value) {
  const str = value ? "开放" : "隐藏";
  this.$confirm(`【研选】系列纪要、报告、专家电话会将对永续客户${str}，是否继续？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      raiInterface.sustainableEditSummaryManage().then((res) => {
        if (res.Ret === 200) {
          sustainableDetailSummaryManage();
          ElMessage.success("操作成功");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消操作",
      });
    });
}
//点击代问的弹框
function inquireBtn(id) {
  pageState.generaitondialogVisib = true;
  pageState.generaitonId = id;
}
function tabsClick(item) {
  if (pageState.tabsIndex !== item.id) {
    pageState.tabsIndex = item.id;
  }
  pageState.page_no = 1;
  init();
  getsummaryManageList();
  remoteMethodAuthor();
}
function init() {
  pageState.status = "";
  pageState.industry = "";
  pageState.issueTime = "";
  pageState.titleValue = "";
  pageState.valueAuthor = "";
  pageState.labelSearch = "";
  pageState.authorOptions = [];
}
//收藏 作者关注 点击事件
function collectionIsShow(id, type) {
  pageState.collectionId = id; //关注 收藏 id
  pageState.collectionType = type; //关注 收藏 类型区分
  pageState.collectionDlgShow = true;
}
//作者的搜索
async function remoteMethodAuthor(query) {
  const res = await raiInterface.departmentList({ KeyWord: query });
  if (res.Ret === 200) {
    pageState.authorOptions = res.Data.List || [];
  }
}
//清除作者的某一项后要有原有的数据
function clearAuthor() {
  remoteMethodAuthor();
}
// 置顶 取消置顶
async function toppingHandler(item) {
  const res = await raiInterface.summaryManageTopChange({ ArticleId: item.ArticleId });
  if (res.Ret === 200) {
    getsummaryManageList();
    ElMessage.success("操作成功");
  }
}
onBeforeRouteLeave((to, from, next) => {
  let backData = {};
  if (to.path == "/editSummary") {
    backData = {
      page_no: pageState.page_no,
      keyword: pageState.titleValue,
      status: pageState.status, //状态
      issueTime: pageState.issueTime, //时间
      tabs: pageState.tabsIndex,
      industry: pageState.industry,
      valueAuthor: pageState.valueAuthor,
      labelSearch: pageState.labelSearch,
    };
    sessionStorage.setItem("summaryManageBack", JSON.stringify(backData));
  }
  next();
});

const {
  page_no,
  dataList,
  industry,
  status,
  issueTime,
  valueAuthor,
  authorOptions,
  options,
  titleValue,
  total,
  PageSize,
  chartPermissionList,
  shortcutIsDialog,
  isClientSwitch,
  generaitondialogVisib,
  generaitonId,
  generaitonType,
  tabsList,
  tabsIndex,
  collectionDlgShow,
  collectionId,
  collectionType,
  token,
  labelSearch,
} = toRefs(pageState);
</script>

<template>
  <div class="container-summary">
    <!-- 内容el-card -->
    <el-card>
      <!-- 选择部分 -->
      <div class="screen-box">
        <div>
          <el-select placeholder="请选择报告类型" clearable v-model="industry" @change="conditionChange" >
            <el-option v-for="item in chartPermissionList" :label="item.ArticleTypeName" :key="item.ArticleTypeId" :value="item.ArticleTypeId"></el-option>
          </el-select>
          <el-select placeholder="发布状态" clearable v-model="status" @change="conditionChange">
            <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>
          <el-input v-model="titleValue" placeholder="请输入报告标题" clearable style="display: inline-block; width: 240px" :prefix-icon="Search"> </el-input>
          <el-input v-model="labelSearch" placeholder="请输入报告标签" clearable style="display: inline-block; width: 240px" :prefix-icon="Search"> </el-input>
          <el-select v-model="valueAuthor" filterable clearable @change="conditionChange" :filter-method="remoteMethodAuthor" placeholder="作者昵称" @clear="clearAuthor">
            <el-option v-for="item in authorOptions" :key="item.DepartmentId" :label="item.Content" :value="item.DepartmentId"> </el-option>
          </el-select>
        </div>
        <div class="screen-right">
          <el-button type="primary" @click="$router.push('/addSummary')">添加报告</el-button>
        </div>
      </div>
      <!-- 表格部分 -->
      <el-table :data="dataList" style="width: 100%" border>
        <el-table-column key="title" align="center" label="报告标题" min-width="300">
          <template #default="scope">
            <span class="editsty" style="color: #409eff" @click="lookDetail(scope.row)">{{ scope.row.Title }}</span>
          </template>
        </el-table-column>
        <el-table-column key="category" prop="ArticleTypeName" align="center" label="报告类型" min-width="95"></el-table-column>
        <el-table-column key="label" prop="IndustryName" align="center" label="标签" min-width="160"></el-table-column>
        <el-table-column key="nickName" prop="NickName" align="center" label="作者昵称" min-width="90">
          <template #default="scope">
            <span class="editsty" @click="collectionIsShow(scope.row.DepartmentId, '关注')">{{ scope.row.NickName }}</span>
          </template>
        </el-table-column>
        <el-table-column key="PublishDate" min-width="160" prop="PublishDate" align="center" label="发布时间"></el-table-column>
        <el-table-column key="LastUpdatedTime" min-width="160" prop="LastUpdatedTime" align="center" label="更新时间"></el-table-column>
        <el-table-column key="status" align="center" label="发布状态" min-width="100">
          <template #default="scope">
            {{ scope.row.PublishStatus == 0 ? "未发布" : "已发布" }}
          </template>
        </el-table-column>
        <el-table-column key="pvUv" width="130" 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}&${token}`" download>
                <img src="~@/assets/img/rai_m/pvuv_download.png" alt="" />
              </a>
            </div>
          </template>
        </el-table-column>
        <el-table-column key="collection" align="center" label="收藏数" min-width="80">
          <template #default="scope">
            <span class="editsty" @click="collectionIsShow(scope.row.ArticleId, '收藏')">{{ scope.row.CollectionNum }}</span>
          </template>
        </el-table-column>
        <el-table-column key="ask" width="60" label="留言" align="center">
          <template #default="scope">
            <span @click="inquireBtn(scope.row.ArticleId)" class="editsty">{{ scope.row.CommentNum }}</span>
          </template>
        </el-table-column>
        <el-table-column key="operation" align="center" label="操作" width="150">
          <template #default="scope">
            <span class="editsty" @click="operationBtn(scope.row.ArticleId, '发布')">{{ scope.row.PublishStatus == 0 ? "发布" : "取消发布" }} &nbsp;&nbsp;</span>
            <span class="editsty" @click="editBtn(scope.row.ArticleId)">编辑 &nbsp;&nbsp;</span>
            <span class="deletesty" v-if="scope.row.PublishStatus == 0" @click="operationBtn(scope.row.ArticleId, '删除')">删除 &nbsp;&nbsp;</span>
            <span class="editsty" v-if="scope.row.PublishStatus != 0" @click="toppingHandler(scope.row)">{{ scope.row.TopTime > 0 ? "取消置顶" : "置顶" }} &nbsp;&nbsp;</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>
    <shortcut-dialog v-model:shortcutIsDialog="shortcutIsDialog" />
    <generation-ask v-model:generaitondialogVisib="generaitondialogVisib" :generaitonId="generaitonId" :generaitonType="generaitonType" />
    <focus-collection :collectionDlgShow="collectionDlgShow" :collectionId="collectionId" :collectionType="collectionType" />
  </div>
</template>

<style scoped lang="scss">
.container-summary {
  .el-card {
    min-height: calc(100vh - 118px);
  }
  .top-card-box {
    display: flex;
    justify-content: space-between;
  }
  .screen-box {
    display: flex;
    justify-content: space-between;
    .el-select,
    .el-input {
      margin-right: 25px;
    }
  }
  .mx-datepicker {
    width: 220px !important;
    margin-right: 25px;
  }
  .content-top-tabs {
    width: 100%;
    box-sizing: border-box;
    padding: 0 30px;
    height: 80px;
    background: #ffffff;
    border: 1px solid #ececec;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    .tabs-top {
      display: flex;
      span {
        box-sizing: border-box;
        padding: 0 24px;
        line-height: 38px;
        height: 40px;
        background: #ecf5ff;
        border: 1px solid #b3d8ff;
        opacity: 1;
        font-weight: 500;
        font-size: 16px;
        color: #409eff;
        border-radius: 4px;
        margin-right: 30px;
      }
      .active {
        background-color: #409eff;
        color: #fff;
      }
    }
  }
  .pv-uv-download {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 14px;
      height: 14px;
      margin-left: 10px;
    }
  }
  .screen-right {
    position: relative;
  }
  :deep(.el-input__wrapper) {
    margin-bottom: 20px !important;
  }
}
</style>
