<template>
  <basic-container>
    <div class="search-content">
      <el-form :model="searchFrom" label-width="140px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="执行包年度">
              <el-date-picker clearable class="w100" v-model="searchFrom.year" type="year" placeholder="请选择执行包年度" format="yyyy" value-format="yyyy"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="执行包季度">
              <el-select v-model="searchFrom.quarter" placeholder="请选择服务季度" class="w100" clearable>
                <el-option label="第一季度" :value="1"></el-option>
                <el-option label="第二季度" :value="2"></el-option>
                <el-option label="第三季度" :value="3"></el-option>
                <el-option label="第四季度" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务提交时间">
              <el-date-picker class="w100" clearable v-model="searchFrom.createTime" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务类型">
              <el-select v-model="searchFrom.taskTypeId" placeholder="请选择服务类型" class="w100" clearable>
                <el-option :label="item.name" :value="item.id" v-for="item in taskTypeAvailArr" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="服务提供商">
              <el-select v-model="searchFrom.vendorId" placeholder="请选择服务提供商" class="w100" clearable filterable>
                <el-option v-for="item in deptListArr" :key="item.entId" :label="item.name" :value="item.entId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="代表姓名">
              <el-select v-model="searchFrom.salesId" placeholder="请选择代表姓名" class="w100" clearable filterable>
                <el-option v-for="item in userListArr" :key="item.userId" :label="item.realName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品所属生产企业">
              <el-select v-model="searchFrom.mahName" @change="mahNameChange" placeholder="请选择产品所属生产企业" class="w100" clearable>
                <el-option v-for="item in mahNameArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关联产品名称">
              <el-select v-model="searchFrom.skuId" placeholder="请选择关联产品名称" class="w100" :disabled="drugDisabled" clearable filterable>
                <el-option v-for="item in currDrugList" :key="item.id" :label="item.drugNameTy" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="执行包所属省份">
              <el-select v-model="searchFrom.provAbbr" placeholder="请选择省份" class="w100" clearable>
                <el-option v-for="province in abbreviationsProvincesList" :key="province" :label="province" :value="province" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上游服务包名称">
              <el-select v-model="searchFrom.pkgIds" placeholder="请选择上游服务包名称" class="w100" clearable filterable>
                <el-option v-for="(item, index) in relPkgNameArr" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态">
              <el-select v-model="searchFrom.taskStatus" placeholder="请选择审核状态" class="w100" clearable filterable>
                <el-option label="审核通过" value="3" />
                <el-option label="审核拒绝" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="search-btns">
              <el-button type="success" class="btn-style" @click="clickBtn">搜索</el-button>
              <el-button @click="clearSearch">清空</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="table-btns">
      <el-tooltip class="item" effect="dark" content="导出需要大量计算，请耐心等候，不要频繁点击" placement="top">
        <el-button type="primary" size="small" @click="exportBtnFn" :loading="exportLoading">导 出</el-button>
      </el-tooltip>

      <template v-if="userInfo.roles.includes(4) || userInfo.roles.includes(37)">
        <div class="right-btns">
          <div class="r-btn">
            <template v-if="pkgBtnErrorMsg">
              <el-tooltip effect="dark" :content="pkgBtnErrorMsg" placement="top-start">
                <el-button size="small" class="error-message" disabled>生成失败<i class="el-icon-warning-outline el-icon--right"></i></el-button>
              </el-tooltip>
            </template>
            <template v-else>
              <el-button class="down-btn" plain :type="exportPkgDisabled ? 'info' : 'primary'" :disabled="exportPkgDisabled" size="small" @click="downInfo(2)">{{
                pkgBtnText
              }}</el-button>
            </template>
            <el-button type="primary" size="small" @click="exportPersonalPackage">个人执行包数据导出</el-button>
          </div>
          <div class="r-btn">
            <template v-if="taskDetailErrorMsg">
              <el-tooltip effect="dark" :content="taskDetailErrorMsg" placement="top-start">
                <el-button size="small" class="error-message" disabled>生成失败<i class="el-icon-warning-outline el-icon--right"></i></el-button>
              </el-tooltip>
            </template>
            <template v-else>
              <el-button class="down-btn" plain :type="exportTaskDetailDisabled ? 'info' : 'primary'" :disabled="exportTaskDetailDisabled" size="small" @click="downInfo(1)">{{
                taskDetailBtnText
              }}</el-button>
            </template>
            <el-button type="primary" size="small" @click="exportPersonalTaskDetails">个人任务明细数据导出</el-button>
          </div>
        </div>
      </template>
    </div>

    <div class="table">
      <vxe-table
        ref="tableRef"
        border
        allAlign="center"
        show-overflow
        highlight-hover-row
        height="auto"
        empty-text="暂无匹配数据"
        v-loading="tableLoading"
        :data="tableData"
        :scroll-y="{ enabled: false }"
        :scroll-x="{ enabled: true }"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <vxe-table-column type="seq" title="序号" width="100"></vxe-table-column>
        <vxe-table-column field="taskNumber" title="服务编号" width="200"></vxe-table-column>
        <vxe-table-column field="cycle" title="服务包周期" width="200"> </vxe-table-column>
        <vxe-table-column field="relPkgName" title="上游服务包名称" width="250"> </vxe-table-column>
        <vxe-table-column field="pkgName" title="服务包名称" width="200"></vxe-table-column>
        <vxe-table-column field="taskTypeName" title="服务类型" width="200"></vxe-table-column>
        <vxe-table-column field="taskScore" title="服务分值" width="100"></vxe-table-column>
        <vxe-table-column field="salesName" title="代表姓名" width="150"></vxe-table-column>
        <vxe-table-column field="createTime" title="服务提交时间" width="200"></vxe-table-column>
        <vxe-table-column field="entName" title="服务提供商" width="200"></vxe-table-column>
        <vxe-table-column field="mahName" title="产品所属生产企业" width="200"></vxe-table-column>
        <vxe-table-column field="skuName" title="关联产品名称" width="200"></vxe-table-column>
        <vxe-table-column field="provAbbr" title="执行包所属省份" width="130"></vxe-table-column>
        <vxe-table-column field="taskStatus" title="审核状态" width="130">
          <template slot-scope="scope">
            <div v-if="scope.row.taskStatus === '2'">
              <div>待服务商审核</div>
            </div>
            <div v-else-if="scope.row.taskStatus === '3'">
              <div>审核通过</div>
            </div>
            <div v-else-if="scope.row.taskStatus === '4'">
              <div>审核拒绝</div>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column title="已审批节点" width="120">
          <template slot-scope="scope">
            <div class="btns">
              <el-popover
                placement="left"
                width="800"
                trigger="hover"
                @hide="hide"
                @show="
                  () => {
                    show(scope.row);
                  }
                "
              >
                <div v-loading="infoLoading" class="info-list">
                  <div v-html="infoContent" class="detail-content"></div>
                </div>
                <div slot="reference" class="check-detail">审核详情</div>
              </el-popover>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column title="操作" fixed="right" width="130">
          <template slot-scope="scope">
            <div class="btns"><el-button type="text" @click="serviceDetail(scope.row)">服务详情</el-button></div>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>

    <vxe-pager
      :current-page.sync="page.currentPage"
      :page-size.sync="page.pageSize"
      :total="page.total"
      :page-sizes="page.pageSizes"
      @page-change="pageChange"
      :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
    >
    </vxe-pager>

    <el-dialog title="提示" :visible.sync="exportDialogVisible" width="30%">
      <el-form ref="exportFormRef" :model="exportForm" label-width="80px">
        <el-form-item label="选择月份">
          <el-date-picker value-format="yyyy-MM-dd" v-model="exportForm.startDate" type="month" placeholder="选择月"> </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleExportDialogClose">取 消</el-button>
        <el-button type="primary" @click="exportDialogFn">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getTaskTypeAvailApi,
  getDeptv2Avail,
  getDrug2Avail,
  getUserV2Avail,
  getPkgV2Api,
  getTaskV2PageCheckedApi,
  getTaskV2CheckHisApi,
  pkgCheckExportApi
} from '@/api/serviceManagement/servicesToBeReviewed/index.js';

import { exportTaskDetail, exportPkgSubInfo } from '@/api/taskManagement/missionCenter';
import { getExportResult } from '@/api/admin/user';
import { tableOptin } from './index.js';
import { getDictType } from '@/api/common';
import abbreviationsProvinces from '@/const/abbreviationsProvinces.js';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
import TaskDetail from './components/TaskDetail.vue';
import refuseReason from '@/components/refuseReason';
import Config from '@/settings';

export default {
  components: { refuseReason, TaskDetail },
  data() {
    return {
      taskDetailShow: false,
      taskDetailBtnText: '暂无数据',
      taskDetailErrorMsg: '',
      exportTaskDetailDisabled: true,
      exportType: '',
      taskDetailUrl: '',
      exportDialogVisible: false,
      exportPkgDisabled: true,
      pkgUrl: '',
      pkgBtnErrorMsg: '',
      pkgDetailShow: false,
      pkgBtnText: '暂无数据',
      exportForm: {
        startDate: ''
      },
      tableOptin,
      tableData: [],
      tableLoading: false,
      checkResultArr: [],
      taskTypeAvailArr: [],
      mahNameArr: [],
      deptListArr: [],
      drugListArr: [],
      userListArr: [],
      currDrugList: [],
      relPkgNameArr: {},
      searchLoading: false,
      drugDisabled: true,
      abbreviationsProvincesList: abbreviationsProvinces,
      searchFrom: {
        year: '',
        taskTypeId: '',
        quarter: '',
        createTime: '',
        provAbbr: '',
        mahName: '',
        vendorId: '',
        salesId: '',
        skuId: '',
        pkgIds: '',
        taskStatus: ''
      },

      page: {
        pageSizes: [10, 50, 100, 300, 500],
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 300 // 每页显示多少条
      },

      taskForm: {
        checkResult: '',
        checkMessage: ''
      },
      rules: {
        checkResult: [{ required: true, message: '请选择审批意见', trigger: 'change' }]
      },
      infoLoading: false,
      infoContent: '',
      exportLoading: false
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    this.getDict();
  },
  mounted() {
    const currYear = dayjs().format('YYYY');
    this.searchFrom.year = currYear;
    this.getList();

    this.gerTaskExprotResult();
    this.gerPkgExprotResult();
  },

  methods: {
    getDict() {
      getDictType({ type: 'task_status' }).then((res) => {
        this.checkResultArr = res.data.data;
      });
      getDictType({ type: 'mah_name' }).then((res) => {
        this.mahNameArr = res.data.data;
      });
      getTaskTypeAvailApi().then((res) => {
        this.taskTypeAvailArr = res.data.data;
      });
      getDeptv2Avail().then((res) => {
        this.deptListArr = res.data.data;
      });
      getUserV2Avail().then((res) => {
        this.userListArr = res.data.data;
      });
      getDrug2Avail().then((res) => {
        this.drugListArr = res.data.data;
      });
      getPkgV2Api().then((res) => {
        let arr = [];
        let data = res.data.data;
        for (let key in data) {
          let obj = {
            label: key,
            value: data[key]
          };
          arr.push(obj);
        }

        this.relPkgNameArr = arr;
      });
    },
    async getList() {
      this.tableLoading = true;
      const obj = Object.assign(
        {
          current: this.page.currentPage,
          size: this.page.pageSize
        },
        this.searchFrom
      );

      const res = await getTaskV2PageCheckedApi(obj);

      this.tableLoading = false;
      if (res.data.code === 0) {
        this.tableData = res.data.data.records;
        this.tableData.forEach((item) => {
          const currA = this.taskTypeAvailArr.find((itn) => itn.id === item.taskTypeId);
          const currB = this.checkResultArr.find((itn) => itn.value === item.taskStatus);
          item.taskTypeName = currA?.name ?? '';
          item.checkResultName = currB?.label ?? '';
          item.cycle = item.pkgStartTime + '~' + item.pkgEndTime;
        });
        this.page.total = res.data.data.total;
      }
    },
    clickBtn() {
      this.tableData = [];
      this.page.currentPage = 1;
      this.getList();
    },
    clearSearch() {
      this.searchFrom = {
        year: dayjs().subtract(1, 'year').format('YYYY'),
        taskTypeId: '',
        quarter: '',
        createTime: '',
        provAbbr: '',
        mahName: '',
        vendorId: '',
        salesId: '',
        skuId: '',
        pkgIds: '',
        taskStatus: 3
      };
    },
    pageChange(obj) {
      this.page.currentPage = obj.currentPage;
      this.page.pageSize = obj.pageSize;
      this.getList();
    },
    mahNameChange(e) {
      if (e) {
        console.log('e', e);

        const curr = this.drugListArr[e];
        this.currDrugList = curr;
        this.drugDisabled = false;
      } else {
        this.searchFrom.skuId = '';
        this.currDrugList = [];
        this.drugDisabled = true;
      }
    },

    serviceDetail(row) {
      window.open(
        Config.outsideUrl + '/h5/#/pages/task/task-detail/index?id=' + row.taskId,
        'newwindow',
        'height=500, width=400, top=200, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no'
      );
    },
    async show(item) {
      this.infoLoading = true;
      const res = await getTaskV2CheckHisApi({ taskId: item.taskId });
      if (res.data.code === 0 && res.data.data.length > 0) {
        let str = '';
        res.data.data.forEach((item) => {
          str += `<span style='font-weight:700'>审核人：</span>${item.checker}；<span style="font-weight:700">审核时间：</span>${
            item.checkTime
          }；<span style="font-weight:700">审核状态：</span>${item.checkResult}<span style="font-weight:700">；审核原因：</span>${item.checkMessage ?? ''}<br>`;
        });
        this.infoContent = str;
      }
      this.infoLoading = false;
    },
    hide() {
      this.infoContent = '';
      this.infoLoading = false;
    },
    async exportBtnFn() {
      if (!this.searchFrom.year || !this.searchFrom.quarter) {
        return this.$message.error('请选择年和季度');
      }

      try {
        this.exportLoading = true;
        const obj = {
          year: this.searchFrom.year,
          quarter: this.searchFrom.quarter
        };
        const res = await pkgCheckExportApi(obj);
        let url = window.URL.createObjectURL(new Blob([res.data]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '执行包审核明细信息.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.exportLoading = false;
      } catch (err) {
        this.exportLoading = false;
      }
    },

    handleExportDialogClose() {
      this.exportForm.startDate = '';
      this.exportDialogVisible = false;
    },
    exportPersonalTaskDetails() {
      this.exportType = '1';
      this.exportDialogVisible = true;
    },
    exportPersonalPackage() {
      this.exportType = '2';
      this.exportDialogVisible = true;
    },
    async exportDialogFn() {
      if (!this.exportForm.startDate) {
        return this.$message.warning('请选择导出日期');
      }
      let res;
      if (this.exportType == '1') {
        res = await exportTaskDetail(this.exportForm);
      } else {
        res = await exportPkgSubInfo(this.exportForm);
      }
      if (res.data.data) {
        this.exportType == '1' ? this.gerTaskExprotResult() : this.gerPkgExprotResult();
      }

      this.handleExportDialogClose();
    },
    // 获取导出状态 - TASK_DETAIL
    async gerTaskExprotResult() {
      const checkStatus = async () => {
        const res = await getExportResult({ type: 'TASK_DETAIL' });
        this.taskDetailErrorMsg = '';
        if (res.data.code === 0) {
          this.taskDetailShow = true;
          let status = res.data.data.status;
          if (status === 'NOT_GENERATE') {
            this.taskDetailBtnText = '暂无数据';
            this.exportTaskDetailDisabled = true;
            return false;
          } else if (status === 'GENERATING') {
            this.taskDetailBtnText = '数据生成中';
            this.exportTaskDetailDisabled = true;
            return false;
          } else if (status === 'GENERATED') {
            this.taskDetailUrl = res.data.data.latestUrl;
            this.taskDetailBtnText = '下载数据';
            this.exportTaskDetailDisabled = false;
            return true;
          } else if (status === 'ERROR') {
            this.taskDetailErrorMsg = res.data.data.errorMsg || '导出失败';
            this.exportTaskDetailDisabled = true;
            return true;
          } else {
            this.taskDetailShow = false;
            return true;
          }
        } else {
          this.taskDetailBtnText = '获取状态失败';
          this.exportTaskDetailDisabled = false;
          return true;
        }
      };

      // 初次执行
      const stop = await checkStatus();

      // 如果状态仍是生成中，开始轮询
      if (!stop) {
        const timer = setInterval(async () => {
          const stopLoop = await checkStatus();
          if (stopLoop) {
            clearInterval(timer);
          }
        }, 60000);
      }
    },

    // 获取导出状态 - SCORE_PACKAGE_SUB
    async gerPkgExprotResult() {
      const checkStatus = async () => {
        const res = await getExportResult({ type: 'SCORE_PACKAGE_SUB' });
        this.pkgBtnErrorMsg = '';
        if (res.data.code === 0) {
          this.pkgDetailShow = true;
          const status = res.data.data.status;
          if (status === 'NOT_GENERATE') {
            this.pkgBtnText = '暂无数据';
            this.exportPkgDisabled = true;
            return false;
          } else if (status === 'GENERATING') {
            this.pkgBtnText = '数据生成中';
            this.exportPkgDisabled = true;
            return false;
          } else if (status === 'GENERATED') {
            this.pkgUrl = res.data.data.latestUrl;
            this.pkgBtnText = '下载数据';
            this.exportPkgDisabled = false;
            return true;
          } else if (status === 'ERROR') {
            this.pkgBtnErrorMsg = res.data.data.errorMsg || '生成失败';
            this.exportPkgDisabled = true;
            return true;
          } else {
            this.pkgDetailShow = false;
            return true;
          }
        } else {
          this.pkgBtnText = '获取状态失败';
          this.exportPkgDisabled = false;
          return true;
        }
      };

      const stop = await checkStatus();

      if (!stop) {
        const timer = setInterval(async () => {
          const stopLoop = await checkStatus();
          if (stopLoop) {
            clearInterval(timer);
          }
        }, 60000);
      }
    },

    downInfo(type) {
      // 拼接日期
      const dateStr = dayjs().format('YYYY-MM-DD');
      // 根据类型拼接文件名
      const fileName = type == '1' ? `个人任务明细${dateStr}.xlsx` : `个人执行包数据${dateStr}.xlsx`;
      // 根据环境切换请求路径
      const baseURL =
        process.env.NODE_ENV === 'development'
          ? '' // 开发环境走 vue.config.js 代理
          : process.env.VUE_APP_URL;
      const url = type == '1' ? this.taskDetailUrl : this.pkgUrl;
      // 用 fetch 获取 blob，保证文件名可控
      fetch(baseURL + url)
        .then((res) => {
          if (!res.ok) throw new Error('下载失败');
          return res.blob();
        })
        .then((blob) => {
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
        })
        .catch((err) => {
          console.error('下载出错:', err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.search-btns {
  margin-left: 50px;
  display: flex;

  .btn-style {
    margin-right: 15px;
  }
}

.tips {
  display: inline-block;
  padding: 0 5px;
  color: #85ce61;
  border-radius: 3px;
  line-height: 14px;
  font-size: 14px;
}

.table {
  height: 1200px;
}
.teskDetailsty {
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  border-bottom: 1px solid #d7d6d5;
  margin: 0 0 10px 0;
}

.check-tips {
  margin-bottom: 5px;
  font-size: 16px;
  color: rgb(233 77 77);
  text-align: center;
  font-weight: 600;
}

.info-list {
  margin-bottom: 10px;
  li {
    list-style: none;
  }
}
.check-detail {
  font-size: 12px;
  color: #6e6e6e;
  cursor: pointer;
}
.table-btns {
  margin: 10px 0;
  display: flex;
  justify-content: space-between;
}

.right-btns {
  display: flex;
  align-items: center;
  .r-btn {
    margin-right: 10px;
  }
}
.error-message {
  color: red !important;
  font-weight: 600 !important;

  i {
    font-weight: 600;
    font-size: 12px;
  }

  &:hover {
    background-color: #fff !important;
    border-color: #ebeef5 !important;
    color: red !important;
  }
}

.down-btn {
  background-color: #fff !important;
  color: #6eb657 !important;
  &:hover {
    color: #6eb657 !important;
  }
}

.down-btn.is-disabled {
  color: #bcbec2 !important;
}

::v-deep .el-button--info {
  background-color: #fff !important;

  &:hover {
    color: #bcbec2 !important;
  }
}
</style>
