<template>
  <div>
    <div class="searchBox">
      <div class="searchItem">
        <span>时段：</span>
        <el-radio-group v-model="radio" size="mini" @change="resetDate">
          <el-radio label="sy" border>上月</el-radio>
          <el-radio label="by" border>本月</el-radio>
          <el-radio label="bjd" border>本季度</el-radio>
          <el-radio label="jn" border>今年</el-radio>
        </el-radio-group>
      </div>
      <div class="searchItem">
        <span>日期：</span>
        <el-date-picker
          v-model="date"
          size="mini"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="
            () => {
              this.radio = '';
              requestData();
            }
          "
        />
      </div>
      <div class="searchItem">
        <el-button size="mini" type="primary" @click="requestData"
          >搜索</el-button
        >
      </div>
    </div>
    <el-tabs v-model="tabActive" @tab-click="reLayoutTable">
      <el-tab-pane label="部门" name="bm">
        <div id="chartDom" style="width: 100%; height: 350px"></div>
        <div class="exportBox">
          <el-button size="small" @click="exportExcel">导出</el-button>
        </div>
        <el-table
          ref="archivesTableRef-bm"
          :data="bmTableData"
          border
          :height="tableHeight"
          style="width: 100%"
        >
          <el-table-column fixed="left" label="名称" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="viewWp(scope.row)">{{
                scope.row.deptName
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="ecTotalUser"
            label="应培训人数"
            sortable
            align="center"
          />
          <el-table-column
            prop="ecActualUser"
            label="实培训人数"
            sortable
            align="center"
          />
          <el-table-column prop="pxl" label="培训率" sortable align="center" >
            <template slot-scope="scope">{{scope.row.pxl}}%</template>
          </el-table-column>
          <el-table-column prop="rjxs" label="人均学时" sortable align="center" >
            <template slot-scope="scope">{{scope.row.rjxs}}</template>
          </el-table-column>
          <el-table-column prop="ecTotalMin" sortable label="累计学时" align="center" />
          <el-table-column
            prop="eeTotalUser"
            label="应考试人数"
            align="center"
            sortable
          />
          <el-table-column
            prop="eeActualUser"
            label="实考试人数"
            align="center"
            sortable
          />
          <el-table-column prop="ksl" label="考试率" sortable align="center">
            <template slot-scope="scope">{{scope.row.ksl}}%</template>
          </el-table-column>
          <el-table-column prop="kshgl" label="考试合格率" sortable align="center">
            <template slot-scope="scope">{{scope.row.kshgl}}%</template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="viewBmDetail(scope.row, date)"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane
        :label="`职工${selectDeptName ? '(仅查看' + selectDeptName + ')' : ''}`"
        name="zg"
      >
        <div class="exportBox" style="margin: 10px">
          <el-button size="small" @click="exportUserExcel">导出</el-button>
        </div>
        <el-table
          ref="archivesTableRef-zg"
          :data="zgTableData"
          border
          height="660"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />
          <el-table-column prop="realName" label="姓名" align="center" />
          <el-table-column prop="deptName" label="所属部门" align="center" />
          <el-table-column label="培训统计" align="center">
            <el-table-column
              prop="courseNum"
              label="参与课程数"
              align="center"
              sortable
            />
            <el-table-column prop="totalMin" label="总学时" sortable align="center" />
            <el-table-column prop="wcl" label="完成率" sortable align="center">
              <template slot-scope="scope">{{scope.row.wcl}}%</template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="考试记录" align="center">
            <el-table-column
              prop="tryCount"
              label="参与考试次数"
              align="center"
              sortable
            />
            <el-table-column prop="passed" label="及格次数" sortable align="center" />
            <el-table-column prop="jgl" label="及格率" sortable align="center">
              <template slot-scope="scope">{{scope.row.jgl}}%</template>
            </el-table-column>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="考培档案"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="viewZgDetail(scope.row, date)"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import * as echarts from "echarts";
import {
  getDepartTotal,
  getUserTotal,
  exportBmExcel,
} from "@/api/archives/index";
import { utils, writeFileXLSX } from 'xlsx';
import { Message } from "element-ui";
export default {
  data() {
    return {
      radio: "by",
      date: [],
      tabActive: "bm",
      bmTableData: [],
      zgTableData: [],
      selectDeptCode: "",
      selectDeptName: "",
      tableHeight: 280,
    };
  },

  mounted() {
    this.resetDate(this.radio);
    window.addEventListener('resize', () => {
      this.tableHeight = (window.innerHeight - 657) <= 280 ? 280 : window.innerHeight - 657
    })
  },

  methods: {
    // 获取部门数据
    getDepartTotal() {
      getDepartTotal({
        statDateL: this.date[0],
        statDateR: this.date[1],
      }).then((res) => {
        let xAxisData = [];
        let seriesData = [[], []];

        res.data.forEach((ele) => {
          ele.pxl = this.renderNumber(ele.ecActualUser, ele.ecTotalUser, true);
          ele.ksl = this.renderNumber(ele.eeActualUser, ele.eeTotalUser, true);
          ele.rjxs = this.renderNumber(ele.ecActualUser, ele.ecTotalMin, true);
          ele.kshgl = this.renderNumber(ele.eePassUser, ele.eeActualUser, true);

          xAxisData.push(ele.deptName);
          seriesData[0].push(
            this.renderNumber(ele.ecActualUser, ele.ecTotalUser, true)
          );
          seriesData[1].push(
            this.renderNumber(ele.eePassUser, ele.eeActualUser, true)
          );
        });
        this.bmTableData = res.data;

        this.initChart(xAxisData, seriesData);
      });
    },

    // 获取职工数据
    getUserTotal() {
      getUserTotal({
        statDateL: this.date[0],
        statDateR: this.date[1],
        deptCode: "",
        realName: "",
      }).then((res) => {
        if (!this.selectDeptCode) {
          res.data.forEach((ele) => {
            ele.wcl = this.renderNumber(ele.learnCourse, ele.courseNum, true);
            ele.jgl = this.renderNumber(ele.passed, ele.tryCount, true);
          });
          this.zgTableData = res.data;
        } else {
          let zgTableData = [];
          res.data.forEach((ele) => {
            if (ele.deptCode === this.selectDeptCode) {
              ele.wcl = this.renderNumber(ele.learnCourse, ele.courseNum, true);
              ele.jgl = this.renderNumber(ele.passed, ele.tryCount, true);
              zgTableData.push(ele);
            }
          });
          this.zgTableData = zgTableData;
        }
      });
    },

    // 过滤数字，规避 0/0 的情况
    renderNumber(num1, num2, renderChart) {
      if (!num1 && !num2) {
        return renderChart ? 0 : "0%";
      } else {
        if (!(num1 / num2)) {
          return renderChart ? 0 : "0%";
        } else {
          return renderChart ? parseInt((num1 / num2) * 100) : ((num1 / num2) * 100).toFixed(2) + "%";
        }
      }
    },

    // 初始化图表
    initChart(xAxisData, seriesData) {
      let myChart = echarts.init(document.getElementById("chartDom"));
      let option;

      option = {
        xAxis: {
          type: "category",
          data: xAxisData,
        },
        yAxis: {
          type: "value",
        },
        legend: {
          show: true,
          x: "center",
          y: "top",
          itemWidth: 10,
          itemHeight: 10,
          data: ["部门培训率", "部门考试合格率"],
          textStyle: {
            fontSize: 10, //字体大小
            color: "#000", //字体颜色
          },
        },
        tooltip: {
          show: true,
          trigger: "axis",
          formatter(data) {
            let str = `${data[0].name}: <br />`;
            data.forEach((ele) => {
              let circle = `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;left:5px;background-color:${ele.color}"></span>`;
              str += circle + `${ele.seriesName}: ${ele.value}% <br />`;
            });
            return str;
          },
        },
        grid: {
          show: true,
          left: "35",
          top: "23",
          right: "30",
          bottom: "23",
        },
        series: [
          {
            name: "部门培训率",
            data: seriesData[0],
            type: "bar",
            itemStyle: {
              color: "rgb(86,114,196)",
            },
            barMaxWidth: "25",
          },
          {
            name: "部门考试合格率",
            data: seriesData[1],
            type: "bar",
            itemStyle: {
              color: "rgb(149,204,122)",
            },
            barMaxWidth: "25",
          },
        ],
      };

      option && myChart.setOption(option);
    },

    // 点击时段
    resetDate(radio) {
      const date = new Date();
      const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

      if (radio === "sy") {
        const month = date.getMonth() - 1 < 0 ? 11 : date.getMonth() - 1;
        const day = days[month];

        this.date = [
          new Date(new Date() - 3600 * 1000 * 24 * 30).formatDate("yyyy-MM") +
            `-01`,
          new Date(new Date() - 3600 * 1000 * 24 * 30).formatDate("yyyy-MM") +
            `-${day}`,
        ];
      } else if (radio === "by") {
        const month = date.getMonth() - 1 < 0 ? 11 : date.getMonth() - 1;
        const day = days[month + 1];

        this.date = [
          new Date().formatDate("yyyy-MM") +
            "-01",
          new Date().formatDate("yyyy-MM") + `-${day}`,
        ];
      } else if (radio === "bjd") {
        const monthList = [1,4,7,10]
        const nowDate = new Date()
        let minMonth = 1;
        for(let i=0;i<monthList.length;i++){
          if(nowDate.getMonth()+1 >= monthList[i]){
            minMonth = monthList[i]
          }
        }
        const maxMonth = minMonth + 2
        nowDate.setMonth(maxMonth)
        nowDate.setDate(0)
        const day = nowDate.getDate()
        this.date = [
          nowDate.formatDate("yyyy")+ `-${(minMonth < 10 ? "0" + minMonth : maxMonth)}-01`,
            nowDate.formatDate("yyyy") +
            `-${(maxMonth < 10 ? "0" + maxMonth : maxMonth)}-${day}`,
        ];
      } else if (radio === "jn") {
        this.date = [
          new Date().formatDate("yyyy") + "-01-01",
          new Date().formatDate("yyyy") + "-12-31",
        ];
      }
      this.requestData();
    },

    // 请求数据
    requestData() {
      if (this.date && this.date.length) {
        this.getDepartTotal();
        this.getUserTotal();
      } else {
        Message.error("日期区间不可为空");
      }
    },

    // 点击场站
    viewWp(row) {
      if (this.date && this.date.length) {
        this.selectDeptCode = row.deptCode;
        this.selectDeptName = row.deptName;
        this.tabActive = "zg";
        this.getUserTotal();
      } else {
        Message.error("日期区间不可为空");
      }
    },

    // 查看部门详情
    viewBmDetail(params, date) {
      params._date = date;
      localStorage.setItem("examLocalStorage", JSON.stringify(params));
      this.$router.push({ name: "TrainDetailBm", params });
    },

    // 查看职工详情
    viewZgDetail(params, date) {
      params._date = date;
      localStorage.setItem("examLocalStorage", JSON.stringify(params));
      this.$router.push({ name: "TrainDetailZg", params });
    },

    // 导出 excel
    exportExcel() {
      if (this.date && this.date.length) {
        // exportBmExcel({
        //   statDateL: this.date[0],
        //   statDateR: this.date[1],
        // });
        getDepartTotal({
          statDateL: this.date[0],
          statDateR: this.date[1],
        }).then((res) => {
          res.data.forEach((ele) => {
            ele['部门编码'] = ele.deptCode
            ele['部门名称'] = ele.deptName
            ele['应培训人数'] = ele.ecTotalUser
            ele['实培训人数'] = ele.ecActualUser
            ele['培训率'] = this.renderNumber(ele.ecActualUser, ele.ecTotalUser)
            ele['人均学时'] = this.renderNumber(ele.ecActualUser, ele.ecTotalMin, true);
            ele['累积学时'] = ele.ecTotalMin
            ele['应考试人数'] = ele.eeTotalUser
            ele['实考试人数'] = ele.eeActualUser
            ele['考试率'] = this.renderNumber(ele.eeActualUser, ele.eeTotalUser);
            ele['考试合格率'] = this.renderNumber(ele.eePassUser, ele.eeActualUser);
            delete ele.deptName
            delete ele.deptCode
            delete ele.ecTotalUser
            delete ele.ecActualUser
            delete ele.ecTotalMin
            delete ele.ecPassUser
            delete ele.eeActualUser
            delete ele.eePassUser
            delete ele.eeTotalUser
          });
          const ws = utils.json_to_sheet(res.data);
          const wb = utils.book_new();
          utils.book_append_sheet(wb, ws, "sheet1");
          writeFileXLSX(wb, "部门统计-导出.xlsx");
        });
      } else {
        Message.error("搜索条件日期区间不可为空");
      }
    },
        // 导出 excel
        exportUserExcel() {
      if (this.date && this.date.length) {
        // exportBmExcel({
        //   statDateL: this.date[0],
        //   statDateR: this.date[1],
        // });
        getUserTotal({
          statDateL: this.date[0],
          statDateR: this.date[1],
          deptCode: "",
          realName: "",
        }).then((res) => {
          let zgTableData = [];
          if (!this.selectDeptCode) {
            res.data.forEach((ele) => {
              ele['姓名'] = ele.realName
              ele['所属部门'] = ele.deptName
              ele['参与课程数'] = ele.courseNum
              ele['总学时'] = ele.totalMin
              ele['完成率'] = this.renderNumber(ele.learnCourse, ele.courseNum);
              ele['参与考试次数'] = ele.tryCount
              ele['及格次数'] = ele.passed
              ele['及格率'] = this.renderNumber(ele.passed, ele.tryCount);
              delete ele.courseNum
              delete ele.deptCode
              delete ele.deptName
              delete ele.learnCourse
              delete ele.passed
              delete ele.realName
              delete ele.totalMin
              delete ele.tryCount
              delete ele.userName
            });
            zgTableData = res.data;
          } else {
            res.data.forEach((ele) => {
              if (ele.deptCode === this.selectDeptCode) {
                ele['姓名'] = ele.realName
                ele['所属部门'] = ele.deptName
                ele['参与课程数'] = ele.courseNum
                ele['总学时'] = ele.totalMin
                ele['完成率'] = this.renderNumber(ele.learnCourse, ele.courseNum);
                ele['参与考试次数'] = ele.tryCount
                ele['及格次数'] = ele.passed
                ele['及格率'] = this.renderNumber(ele.passed, ele.tryCount);
                delete ele.courseNum
                delete ele.deptCode
                delete ele.deptName
                delete ele.learnCourse
                delete ele.passed
                delete ele.realName
                delete ele.totalMin
                delete ele.tryCount
                delete ele.userName
                zgTableData.push(ele);
              }
            });
          }
          const ws = utils.json_to_sheet(zgTableData);
          const wb = utils.book_new();
          utils.book_append_sheet(wb, ws, "sheet1");
          writeFileXLSX(wb, "职工统计-导出.xlsx");

        });
      } else {
        Message.error("搜索条件日期区间不可为空");
      }
    },

    // 重置表格布局
    reLayoutTable() {
      if (this.selectDeptCode || this.selectDeptName) {
        if (this.date && this.date.length) {
          this.selectDeptCode = "";
          this.selectDeptName = "";
          this.getUserTotal();
        } else {
          Message.error("日期区间不可为空");
        }
      }
      this.$nextTick(() => {
        this.$refs[`archivesTableRef-${this.tabActive}`].doLayout();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.exportBox {
  width: calc(100% - 20px);
  margin: 20px 10px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.searchBox {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .searchItem {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-right: 20px;
    font-size: 14px;

    .el-radio-group {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      label.el-radio {
        margin: 2px 5px 2px 0;

        &:last-child {
          margin-right: 0;
        }
      }
    }

    &:first-child {
      margin-left: 0;
    }
  }
}
</style>