<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"
      @on-load="getList"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @search-reset="searchReset"
      @size-change="sizeChange"
      @current-change="currentChange"
    >
      <template slot="periodSearch">
        <ElQuarterPicker placeholder="请选择" v-model="monthrange" @change="monthrangeChange" class="w100" />
      </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>
  </basic-container>
</template>

<script>
import {fetchList, supervisionPkgStatApi, reportExportApi} 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';

export default {
  components: {monitorDialog, ElQuarterPicker},
  data() {
    return {
      tableLoading: false,
      tableOption: tableOption,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 50 // 每页显示多少条
      },
      tableData: [],
      treeList: [],
      searchForm: {
        period: []
      },
      searchFormAreaCodes: [],
      searchCascaderProps: {
        multiple: true,
        label: 'name',
        value: 'id'
      },
      supervisionInfo: {},
      IS_JDY: false,
      monthrange: '',
      exportDialog: false,
      exportMonthrange: '',
      exportPeriod: [],
      currRow: {}
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    this.getAreaTree();
    // 获取监督统计
    this.getSupervisionPkgStat();

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

  methods: {
    exportDialogHandleClose() {
      this.exportMonthrange = '';
      this.exportPeriod = [];
      this.exportDialog = false;
    },
    monthrangeChange(e) {
      if (e) {
        let arr = this.getQuarterRange(e);
        this.searchForm.period = arr;
      } else {
        this.monthrange = '';
        this.searchForm.period = [];
      }
    },
    exportFn(row) {
      console.log('riw', 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,
        period: 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
        },
        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);
    },
    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) {
      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;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    monitorFn(row) {
      this.$refs.monitorRef.showInfo(row);
    },
    taskMonitorFn(row, type) {
      this.$router.push({
        path: '/servicePackageMonitoring/riskEventAudit/taskMonitor?deptId=' + row.deptId + `&type=${type}`
      });
    },
    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;
    }
  }
};
</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;
  }
}
</style>
