<template>
  <div class="container-summary">
    <!-- 内容el-card -->
    <el-card>
      <!-- 选择部分 -->
      <div class="screen-box">
        <div style="margin-bottom: 20px">
          <el-select placeholder="请选择报告类型" clearable v-model="industry" @change="conditionChange" style="margin-bottom: 20px">
            <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">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <el-input v-model="labelSearch" placeholder="请输入报告标签" clearable style="display: inline-block; width: 240px">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </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 slot-scope="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 slot-scope="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 slot-scope="scope">
            {{ scope.row.PublishStatus == 0 ? "未发布" : "已发布" }}
          </template>
        </el-table-column>
        <el-table-column key="pvUv" width="130" label="PV / UV" align="center" :render-header="renderHeader">
          <template slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="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 :shortcutIsDialog.sync="shortcutIsDialog" />
    <generation-ask :generaitondialogVisib.sync="generaitondialogVisib" :generaitonId="generaitonId" :generaitonType="generaitonType" />
    <focus-collection :collectionDlgShow="collectionDlgShow" :collectionId="collectionId" :collectionType="collectionType" />
  </div>
</template>

<script>
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";
export default {
  name: "",
  components: { mPage, ShortcutDialog, GenerationAsk, FocusCollection },
  props: {},
  watch: {
    titleValue(newval) {
      this.page_no = 1;
      this.getsummaryManageList();
    },
    labelSearch(newval) {
      this.page_no = 1;
      this.getsummaryManageList();
    },
    valueAuthor: {
      handler(newval) {
        if (newval === "") {
          this.authorOptions = [];
        }
      },
    },
  },
  data() {
    return {
      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: "",
    };
  },
  computed: {
    sta() {
      return this.status === 0 ? this.status : this.status === 1 ? this.status : 2;
    },
    exportPvUv() {
      return import.meta.env.VITE_APP_API_ROOT + "/cygx/summaryManage/articleHistoryExport?ArticleId=";
    },
  },

  created() {
    this.routerInit();
  },
  mounted() {
    this.chartPermission();
    this.sustainableDetailSummaryManage();
    this.remoteMethodAuthor();
    this.getsummaryManageList();
  },
  methods: {
    //页面缓存 路由
    routerInit() {
      if (sessionStorage.getItem("summaryManageBack")) {
        const { keyword, status, issueTime, tabs, industry, valueAuthor, labelSearch } = JSON.parse(sessionStorage.getItem("summaryManageBack"));
        this.titleValue = keyword;
        this.status = status; //状态
        this.issueTime = issueTime; //时间
        this.tabsIndex = tabs;
        this.industry = industry;
        this.valueAuthor = valueAuthor;
        this.labelSearch = labelSearch;
      }
    },
    //获取观点
    sustainableDetailSummaryManage() {
      raiInterface.sustainableDetailSummaryManage().then((res) => {
        if (res.Ret === 200) {
          this.isClientSwitch = !res.Data.OperationButton;
        }
      });
    },
    //table表头Pu/Uv自定义
    renderHeader(h, { column, $index }) {
      return h("div", { attrs: { style: "padding:0;" } }, [
        h("span", column.label),
        h("el-tooltip", { props: { placement: "top" } }, [
          h("p", { slot: "content", attrs: { style: "display:block;padding:5px 0;width:420px;" } }, "pv：报告被打开的次数，每次打开都计算一次（只统计有权限用户）"),
          h("p", { slot: "content", attrs: { style: "display:block;padding:5px 0;width:420px;" } }, "uv：访问报告的人数，每篇报告同一个人访问只计算一次（只统计有权限用户）"),
          h("el-button", { props: { icon: "el-icon-info" }, attrs: { style: "border:none;background:none;padding:5px" } }, ""),
        ]),
      ]);
    },
    //操作按键 发布 取消发布 删除
    operationBtn(id, value) {
      this.$confirm(`确定${value}该纪要吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (value == "删除") {
            const res = await raiInterface.getsummaryManagedelete({ ArticleId: id });
            if (res.Ret !== 200) return;
            this.$message.success("删除成功！");
            let page_num = Math.ceil((this.total - 1) / this.PageSize);
            if (this.page_no > page_num) {
              this.page_no = page_num;
            }
            this.getsummaryManageList();
          } else {
            const res = await raiInterface.publishAndCancel({ ArticleId: id });
            if (res.Ret !== 200) return;
            this.$message.success(`${value}成功！`);
            this.getsummaryManageList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消${value}`,
          });
        });
    },
    //编辑按钮
    editBtn(id) {
      console.log(id);
      this.$router.push({
        path: "/editSummary",
        query: { id: id },
      });
    },
    //分页
    handleCurrentChange(page) {
      this.page_no = page;
      this.getsummaryManageList();
    },
    //获取行业
    chartPermission() {
      raiInterface.summaryManageArticleType().then((res) => {
        if (res.Ret === 200) {
          this.chartPermissionList = res.Data.List;
        }
      });
    },
    //文章详情
    async lookDetail(item) {
      if (item.PublishStatus === 1) {
        let href = `${process.env.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 } = this.$router.resolve({ name: "预览研选报告" });
          window.open(href, "_blank");
        }
      }
    },
    //列表
    getsummaryManageList() {
      raiInterface
        .getsummaryManageList({
          CurrentIndex: this.page_no,
          PageSize: this.PageSize,
          PublishStatus: this.sta - 0,
          ArticleTypeId: this.industry,
          StartDate: this.issueTime[0],
          EndDate: this.issueTime[1],
          KeyWord: this.titleValue,
          Departmentİd: this.valueAuthor,
          Label: this.labelSearch,
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.dataList = res.Data.List;
          this.total = res.Data.Paging.Totals;
        });
    },
    //change 事件
    conditionChange() {
      this.page_no = 1;
      this.getsummaryManageList();
    },
    switchClickClient(value) {
      const str = value ? "开放" : "隐藏";
      this.$confirm(`【研选】系列纪要、报告、专家电话会将对永续客户${str}，是否继续？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          raiInterface.sustainableEditSummaryManage().then((res) => {
            if (res.Ret === 200) {
              this.sustainableDetailSummaryManage();
              this.$message.success("操作成功");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    //点击代问的弹框
    inquireBtn(id) {
      this.generaitondialogVisib = true;
      this.generaitonId = id;
    },
    tabsClick(item) {
      if (this.tabsIndex !== item.id) {
        this.tabsIndex = item.id;
      }
      this.page_no = 1;
      this.init();
      this.getsummaryManageList();
      this.remoteMethodAuthor();
    },
    init() {
      this.status = "";
      this.industry = "";
      this.issueTime = "";
      this.titleValue = "";
      this.valueAuthor = "";
      this.labelSearch = "";
      this.authorOptions = [];
    },
    //收藏 作者关注 点击事件
    collectionIsShow(id, type) {
      this.collectionId = id; //关注 收藏 id
      this.collectionType = type; //关注 收藏 类型区分
      this.collectionDlgShow = true;
    },
    //作者的搜索
    async remoteMethodAuthor(query) {
      const res = await raiInterface.departmentList({ KeyWord: query });
      if (res.Ret === 200) {
        this.authorOptions = res.Data.List || [];
      }
    },
    //清除作者的某一项后要有原有的数据
    clearAuthor() {
      this.remoteMethodAuthor();
    },
    // 置顶 取消置顶
    async toppingHandler(item) {
      const res = await raiInterface.summaryManageTopChange({ ArticleId: item.ArticleId });
      if (res.Ret === 200) {
        this.getsummaryManageList();
        this.$message.success("操作成功");
      }
    },
  },
  //路由离开
  beforeRouteLeave(to, from, next) {
    let backData = {};
    if (to.path == "/editSummary") {
      backData = {
        page_no: this.page_no,
        keyword: this.titleValue,
        status: this.status, //状态
        issueTime: this.issueTime, //时间
        tabs: this.tabsIndex,
        industry: this.industry,
        valueAuthor: this.valueAuthor,
        labelSearch: this.labelSearch,
      };
      sessionStorage.setItem("summaryManageBack", JSON.stringify(backData));
    }
    next();
  },
  //路由进入
  beforeRouteEnter(to, from, next) {
    if (from.path != "/editSummary") {
      sessionStorage.removeItem("summaryManageBack");
    }
    next();
  },
};
</script>
<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;
    }
  }
}
</style>
