<template>
  <basic-container class="supervision">
    <div class="supervision-info">
      <!-- <div class="supervision-item">
        <div class="txt">全部人员审核总数：{{ supervisionInfo.allOperatorSubtotal }}</div>
        <div class="progress">
          <el-progress type="dashboard" :percentage="supervisionInfo.allOperatorSupRate" />
          <span>全部人员审核百分比</span>
        </div>
      </div>
      <div class="supervision-item">
        <div class="txt">当前人员审核总数：{{ supervisionInfo.curOperatorSubtotal }}</div>
        <div class="progress">
          <el-progress type="dashboard" :percentage="supervisionInfo.curOperatorSupRate" />
          <span>当前人员审核百分比</span>
        </div>
      </div>
      <div class="supervision-item">
        <div class="txt">上季度积分包审核总数：{{ supervisionInfo.total }}</div>
      </div> -->
    </div>
    <avue-crud
      ref="crud"
      :page.sync="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      :search="searchForm"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @search-reset="searchReset"
      @size-change="sizeChange"
      @current-change="currentChange"
    >
      <template slot="taskPeriodSearch">
        <ElQuarterPicker placeholder="请选择" :value="monthrange" v-model="monthrange" @change="monthrangeChange" class="w100" />
      </template>

      <template slot="menuRight">
        <div class="right-content">
          <div class="r-btn" v-if="userInfo?.roles?.includes(53)">
            <template v-if="exportDetailErrorMsg">
              <el-tooltip effect="dark" :content="exportDetailErrorMsg" 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>
            <el-button
              class="down-btn"
              plain
              :type="exportDetailDisabled ? 'info' : 'primary'"
              v-if="exportDetailShow"
              :disabled="exportDetailDisabled"
              size="small"
              @click="downInfo"
              >{{ exportBtnText }}</el-button
            >

            <el-button type="primary" size="small" @click="exportTask">监督任务数据导出</el-button>
          </div>
          <el-checkbox v-model="supervision" @change="checkBoxChange">只看待监督</el-checkbox>
        </div>
      </template>

      <!-- 操作栏 -->
      <template slot="menu" slot-scope="scope">
        <el-button v-if="scope.row.toCheck" type="text" size="small" icon="el-icon-edit-outline" @click="taskMonitorFn(scope.row, 0)">任务监督 </el-button>
        <el-button v-if="scope.row.checked" type="text" size="small" icon="el-icon-tickets" @click="taskMonitorFn(scope.row, 1)">监督详情 </el-button>
        <el-button v-if="scope.row.checked && IS_JDY" type="text" size="small" icon="el-icon-download" @click="exportFn(scope.row, 1)">监督详情 </el-button>

        <!-- <el-button v-if="scope.row.taskSupStat && getPercentage(scope.row) > 10" type="text" size="small" icon="el-icon-edit-outline" @click="monitorFn(scope.row)"
          >监督
        </el-button> -->
      </template>

      <!-- 进度 -->
      <template slot="progress" slot-scope="scope">
        <div>
          <el-progress :percentage="getPercentage(scope.row, 0)"></el-progress>
        </div>
      </template>
      <!-- 角色 -->
      <template slot="roleNumber" slot-scope="scope">
        <div class="role-number">
          <div style="color: #67c23a"><span>生产企业财务监督：</span>{{ scope.row.taskSupStat.mahFinaSupTotal }}</div>
          <div style="color: #e6a23c"><span>生产企业销售监督：</span>{{ scope.row.taskSupStat.mahSalesSupTotal }}</div>
          <div style="color: #f56c6c"><span>营销中心财务监督：</span>{{ scope.row.taskSupStat.optFinaSupTotal }}</div>
          <div style="color: #409eff"><span>营销中心合规监督：</span>{{ scope.row.taskSupStat.optLawSupTotal }}</div>
        </div>
      </template>
      <!-- 进度 -->
      <template slot="roleProgress" slot-scope="scope">
        <div class="role-progress">
          <div><el-progress :percentage="getPercentage(scope.row, 1)" color="#67C23A" text-color="#67C23A"></el-progress></div>
          <div><el-progress :percentage="getPercentage(scope.row, 2)" color="#E6A23C" text-color="#E6A23C"></el-progress></div>
          <div><el-progress :percentage="getPercentage(scope.row, 3)" color="#F56C6C" text-color="#F56C6C"></el-progress></div>
          <div><el-progress :percentage="getPercentage(scope.row, 4)" color="#409EFF" text-color="#409EFF"></el-progress></div>
        </div>
      </template>
    </avue-crud>
    <monitorDialog ref="monitorRef" @success="success" />
    <!-- 导出弹窗 -->
    <el-dialog title="导出报告" :close-on-click-modal="false" :visible.sync="exportDialog" width="50%" center :before-close="exportDialogHandleClose">
      <el-form label-width="100px">
        <el-form-item label="导出周期">
          <ElQuarterPicker placeholder="请选择" v-model="exportMonthrange" @change="exportMonthrangeChange" class="w100" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportDialogHandleClose">取 消</el-button>
        <el-button type="primary" @click="exportBtn">确 定</el-button>
      </span>
    </el-dialog>

    <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 { fetchList, supervisionPkgStatApi, reportExportApi, checkHisExport } from '@/api/riskEventAudit.js';
import ElQuarterPicker from '@/components/ElQuarterPicker/index';
import { tableOption } from '@/const/crud/riskEventAudit.js';
import { getAreaTreeApi } from '@/api/areaTree';
import monitorDialog from './components/monitorDialog.vue';
import { mapGetters } from 'vuex';
import dayjs from 'dayjs';
import { getExportResult } from '@/api/admin/user';
export default {
  components: { monitorDialog, ElQuarterPicker },
  data() {
    return {
      exportDialogVisible: false,
      exportUrl: '',
      exportForm: {
        startDate: ''
      },
      exportDetailShow: false,
      exportDetailDisabled: true,
      exportDetailErrorMsg: '',
      exportBtnText: '暂无数据',
      tableLoading: false,
      tableOption: tableOption,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      tableData: [],
      treeList: [],
      searchForm: {
        taskPeriod: []
      },
      supervision: false,
      searchFormAreaCodes: [],
      searchCascaderProps: {
        multiple: true,
        label: 'name',
        value: 'id'
      },
      supervisionInfo: {},
      IS_JDY: false,

      monthrange: '',
      exportDialog: false,
      exportMonthrange: '',
      exportPeriod: [],
      currRow: {}
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    const curr = this.getCurrentQuarterNumber();
    this.monthrange = curr;
    this.monthrangeChange(this.monthrange);
    this.getAreaTree();
    // 获取监督统计
    this.getSupervisionPkgStat();

    const roles = this.userInfo.roles;
    const rolesArr = [49, 52, 53, 56];
    this.IS_JDY = roles.some((item) => rolesArr.includes(item));
    this.getExportInfoStatus();
    //
  },

  activated() {
    this.getList(this.page);
  },
  methods: {
    getCurrentQuarterNumber() {
      const now = dayjs();
      const year = now.year();
      const month = now.month(); // 0-11
      const quarter = Math.floor(month / 3) + 1; // 1 到 4
      return `${year}-0${quarter}`;
    },
    exportDialogHandleClose() {
      this.exportMonthrange = '';
      this.exportPeriod = [];
      this.exportDialog = false;
    },
    monthrangeChange(e) {
      if (e) {
        let arr = this.getQuarterRange(e);
        this.searchForm.taskPeriod = arr;
      } else {
        this.monthrange = '';
        this.searchForm.taskPeriod = [];
      }
    },
    exportFn(row) {
      this.currRow = row;
      this.exportDialog = true;
    },
    exportMonthrangeChange(e) {
      if (e) {
        let arr = this.getQuarterRange(e);
        this.exportPeriod = arr;
      } else {
        this.exportMonthrange = '';
        this.exportPeriod = [];
      }
    },
    async exportBtn() {
      const obj = {
        entId: this.currRow.deptId,
        taskPeriod: this.exportPeriod
      };
      const res = await reportExportApi(obj);

      if (res.data.code === 0) {
        let url = res.data.data.url;
        const link = document.createElement('a');
        link.href = process.env.VUE_APP_URL + url;
        link.download = '详情.pdf';
        link.target = '_blank'; // 为了在某些浏览器中工作，可以设置为 "_blank"
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.exportDialogHandleClose();
      }
    },
    getQuarterRange(dateString) {
      const [year, quarterCode] = dateString.split('-').map(Number);
      let startMonth, endMonth, endDay;
      switch (quarterCode) {
        case 1: // Q1
          startMonth = 1;
          endMonth = 3;
          endDay = 31;
          break;
        case 2: // Q2
          startMonth = 4;
          endMonth = 6;
          endDay = 30;
          break;
        case 3: // Q3
          startMonth = 7;
          endMonth = 9;
          endDay = 30;
          break;
        case 4: // Q4
          startMonth = 10;
          endMonth = 12;
          endDay = 31;
          break;
        default:
          throw new Error('Invalid quarter code');
      }
      const startDate = `${year}-${String(startMonth).padStart(2, '0')}-01`;
      const endDate = `${year}-${String(endMonth).padStart(2, '0')}-${endDay}`;
      return [startDate, endDate];
    },
    getTaskMonitor() {},
    getShowtaskMonitorBtn(row) {
      const roles = this.userInfo.roles;
      const rolesArr = [49, 52, 53, 56];
      let flag = roles.some((item) => rolesArr.includes(item));
      const supervision = row.supervision;
      const scorePackageStatus = row.scorePackageStatus;
      const flag2 = scorePackageStatus === '4' && (!supervision || supervision === 'REJECTED');
      return flag && flag2;
    },
    async getSupervisionPkgStat() {
      const res = await supervisionPkgStatApi();
      if (res.data.code === 0) {
        this.supervisionInfo = res.data.data;
        this.supervisionInfo.allOperatorSupRate = this.supervisionInfo.allOperatorSupRate * 100;
        this.supervisionInfo.curOperatorSupRate = this.supervisionInfo.curOperatorSupRate * 100;
      }
    },
    // 获取区域树列表
    async getAreaTree() {
      const res = await getAreaTreeApi();
      this.treeList = res.data.data;
    },
    async getList(page, params) {
      this.tableLoading = true;
      const obj = Object.assign(
        {
          current: page.currentPage,
          size: page.pageSize,
          supervision: this.supervision
        },
        params,
        this.searchForm
      );
      const res = await fetchList(obj);
      if (res.data.code === 0) {
        this.tableData = res.data.data.records;
        this.page.total = res.data.data.total;
      }
      this.tableLoading = false;
    },
    refreshChange() {
      this.getList(this.page);
    },
    checkBoxChange() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    extractLastElements(array) {
      // 创建一个新的空数组来存储结果
      let result = [];
      // 遍历输入的二维数组
      for (let i = 0; i < array.length; i++) {
        // 检查内部数组是否非空
        if (array[i].length > 0) {
          // 将内部数组的最后一个元素添加到结果数组中
          result.push(array[i][array[i].length - 1]);
        }
      }
      // 返回结果数组
      return result;
    },
    searchChange(form, done) {
      this.searchForm = form;
      if (this.searchFormAreaCodes.length) {
        const codes = this.extractLastElements(this.searchFormAreaCodes);
        this.searchForm.areaCode = codes;
      }

      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    success() {
      this.getList(this.page);
      this.getSupervisionPkgStat();
    },
    searchReset() {
      this.searchForm = {};
      this.searchFormAreaCodes = [];
      this.monthrange = '';
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList(this.page);
    },
    currentChange(current) {
      this.page.currentPage = current;
      this.getList(this.page);
    },
    monitorFn(row) {
      this.$refs.monitorRef.showInfo(row);
    },
    taskMonitorFn(row, type) {
      console.log('this.monthrange', this.monthrange);
      this.$router.push({
        path: '/servicePackageMonitoring/riskEventAudit/taskMonitor?deptId=' + row.deptId + `&type=${type}&time=${this.monthrange}`,
        query: {
          name: '任务监督-' + row.deptName
        }
      });
    },
    getPercentage(row, type) {
      if (!row.taskSupStat) return 0;
      let num;
      switch (type) {
        case 0:
          num = row.taskSupStat.supTotal;
          break;
        case 1:
          num = row.taskSupStat.mahFinaSupTotal;
          break;
        case 2:
          num = row.taskSupStat.mahSalesSupTotal;
          break;
        case 3:
          num = row.taskSupStat.optFinaSupTotal;
          break;
        case 4:
          num = row.taskSupStat.optLawSupTotal;
          break;
      }
      if (Number(row.taskSupStat.total) && Number(num)) {
        let percentage = num / row.taskSupStat.total;
        percentage = percentage * 100;
        if (Number.isInteger(percentage)) {
          return percentage; // 如果是整数，直接转换为字符串
        } else {
          // 如果不是整数，保留两位小数并转换为字符串
          const num = percentage.toFixed(2);
          return Number(num);
        }
      }
      return 0;
    },
    exportTask() {
      this.exportDialogVisible = true;
    },

    getMonthRange(dateStr) {
      const start = dayjs(dateStr).startOf('month').format('YYYY-MM-DD');
      const end = dayjs(dateStr).endOf('month').format('YYYY-MM-DD');
      return [start, end];
    },
    async exportDialogFn() {
      if (!this.exportForm.startDate) {
        return this.$message.warning('请选择导出日期');
      }

      const taskPeriodResult = this.getMonthRange(this.exportForm.startDate);
      const res = await checkHisExport({
        taskPeriod: taskPeriodResult
      });

      if (res.data.code == 0) {
        this.getExportInfoStatus();
      }
      this.handleExportDialogClose();
    },
    // 获取导出状态 - 用户信息导出
    async getExportInfoStatus() {
      const checkStatus = async () => {
        const res = await getExportResult({ type: 'CHECK_SUP' });
        if (res.data.code === 0) {
          this.exportDetailShow = true;
          const status = res.data.data.status;
          this.exportDetailErrorMsg = '';
          if (status === 'NOT_GENERATE') {
            this.exportBtnText = '暂无数据';
            this.exportDetailDisabled = true;
            return false;
          } else if (status === 'GENERATING') {
            this.exportBtnText = '数据生成中';
            this.exportDetailDisabled = true;
            return false;
          } else if (status === 'GENERATED') {
            this.exportUrl = res.data.data.latestUrl;
            this.exportBtnText = '下载数据';
            this.exportDetailDisabled = false;
            return true;
          } else if (status === 'ERROR') {
            this.exportDetailErrorMsg = res.data.data.errorMsg || '导出失败';
            this.exportDetailDisabled = true;
            return true;
          } else {
            this.exportDetailShow = false;
            return true;
          }
        } else {
          this.exportBtnText = '获取状态失败';
          this.exportDetailDisabled = false;
          return true;
        }
      };

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

      // 如果还在生成中，启动轮询
      if (!stop) {
        const timer = setInterval(async () => {
          const stopLoop = await checkStatus();
          if (stopLoop) clearInterval(timer);
        }, 60000);
      }
    },

    async downInfo() {
      try {
        // 拼接日期，格式为 年/月
        const dateStr = dayjs().format('YYYY-MM');
        const fileName = `监督任务数据${dateStr}.xlsx`;

        // 这里根据开发/生产环境切换 baseURL
        const baseURL = process.env.NODE_ENV === 'development' ? '' : process.env.VUE_APP_URL;

        const res = await fetch(baseURL + this.exportUrl, {
          method: 'GET'
        });

        if (!res.ok) throw new Error('下载失败');

        const blob = await res.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);
      }
    },
    handleExportDialogClose() {
      this.exportForm.startDate = '';
      this.exportDialogVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.supervision {
  height: calc(100vh - 180px);
}
.supervision-info {
  margin-bottom: 30px;
  padding-left: 50px;
  display: flex;
  .supervision-item {
    margin-right: 50px;
    width: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .txt {
      margin-bottom: 20px;
      width: 200px;
      text-align: center;
    }
    .progress {
      width: 200px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
}
::v-deep .el-progress-bar {
  width: 160px;
}
::v-deep .el-progress__text {
  width: 60px;
}

.role-number {
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  div {
    height: 25px;
    span {
      display: inline-block;
      width: 180px;
      text-align: right;
    }
  }
}
.role-progress {
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  div {
    height: 25px;
  }
}
.right-content {
  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>
