<template>
  <div>
    <card-container>
      <vxe-toolbar print custom export>
        <template #buttons>
          <el-date-picker v-model="select.month" type="month" size="small" value-format="yyyy-MM" placeholder="月份"
            format="yyyy-MM" />
          <el-select  v-if="is_bgs" style="width:250px;margin-left:6px" size="small" @change="changeDepartment"
            v-model="select.department_id" placeholder="请选择">
            <el-option v-for="item in departments" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-button icon="el-icon-search" type="primary" plain size="small" style="margin-left: 6px;"
            @click="getList">搜索</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table ref="table" stripe :border='true' style="margin-top: 10px;border:1px solid #333" :loading="loading" :max-height="1400"
        :min-height="400" :export-config="{type: 'xlsx',filename:exportName,sheetName:exportName}" :print-config="{}"
        :column-config="{ resizable: true }" :expand-config="{
          visibleMethod: () => false,
          trigger: 'manual'
        }" :data="tableData" :merge-cells="mergeCells">
        <!-- :span-method="spanMethods"  -->
        <vxe-column width="180" header-align="center" align="center" field="department_name" title="科室"></vxe-column>
        <vxe-column width="180" header-align="center" align="center" field="name" title="姓名"></vxe-column>
        <vxe-column width="180" header-align="center" align="center" field="kaishiriqi" title="日期">
          <template #default="{ row }">
            {{row.kaishiriqi?row.kaishiriqi.substring(0,11):''}}
          </template>
        </vxe-column>
        <vxe-column minWidth="180" header-align="center" align="center" field="yuanyinshuoming" title="加班事由"></vxe-column>
        <vxe-column width="180" :export-method="exportjbMethod" header-align="center" align="center" field="jiabanshijian"
          title="加班时间">
          <template #default="{ row }">
            {{row.kaishiriqi?row.kaishiriqi.substring(11,row.kaishiriqi.length):''}}-{{row.kaishiriqi?row.jieshushijian.substring(11,row.jieshushijian.length):''}}
          </template>
        </vxe-column>
        <vxe-column width="180" header-align="center" align="center" field="jiabanshichang" title="加班时长(h)"></vxe-column>
        <!-- <vxe-column header-align="center" align="center" field="day" title="day"></vxe-column> -->
        <vxe-column  width="180" header-align="center" align="center" field="allDay" title="本月累计(h)"></vxe-column>



      </vxe-table>
    </card-container>
  </div>
</template>

<script>
  import {
    overtimeList
  } from "@/api/chart"
  import {
    departmentListNoAuth
  } from "@/api/common.js"
    import store from "@/store/modules/user.js"
  export default {
    data() {
      return {
        loading: false,
        tableData: [],
        select: {
          page: 1,
          page_size: 10,
          month: this.$moment().format('YYYY-MM'),
          department_id: ''
        },
        my_department_id:"",
        is_bgs:false, // 是否是办公室
        departments: [],
        mergeCells: [],
        exportName: '加班统计表',
        dName: '全部科室'
      }
    },
    methods: {
      async getList() {
        this.loading = true;
        try {
          const res = await overtimeList(this.select, false);
          console.log(res);
          let data = res?.users || [];
          this.tableData = this.overtimeData(data)
          let date = this.$moment(this.select.month).format("YYYY年MM月")
          this.exportName = `${date}${this.dName}加班统计表`
          this.loading = false;
        } catch (err) {
          console.error(err);
          this.loading = false;
        }
      },
      async getDepartmentList() {
        try {
          const res = await departmentListNoAuth();
          console.log(res);
          let arr = res
          this.departments = arr
          this.departments.unshift({
            id: '',
            name: '全部'
          })
        } catch (err) {
          console.error(err);
        }
      },
      overtimeData(arr) {
        let _arr = []
        const result = [];
        _arr = arr.filter(item => item.overtime.length > 0)

        _arr.forEach(item => {
          const {
            id,
            name,
            department,
            overtime
          } = item;
          const allDay = overtime.reduce((sum, overtimeItem) => sum + parseFloat(overtimeItem.jiabanshichang), 0);
          overtime.forEach(overtimeItem => {
            overtimeItem.pid = id;
            overtimeItem.name = name;
            overtimeItem.department_name = department.name
            overtimeItem.sortnumber = department.sortnumber
            overtimeItem.department_id = department.id
            overtimeItem.allDay = parseFloat(allDay).toFixed(2);
            result.push(overtimeItem);
          });
          result.sort((a, b) => {
            return a.sortnumber - b.sortnumber
          })
        });
        this.mergeCells = this.generateMergeCells(result)
        return result;
      },
      exportjbMethod({
        row
      }) {
        return `${row.kaishiriqi?row.kaishiriqi.substring(11,row.kaishiriqi.length):''}-${row.kaishiriqi?row.jieshushijian.substring(11,row.jieshushijian.length):''}`
      },
      changeDepartment(e) {
        if (e) {
          this.departments.map(item => {
            if (item.id == e) {
              this.dName = item.name
            }
          })
        } else {
          this.dName = '全部科室'
        }
      },
      // 合并单元格
      generateMergeCells(data) {
        const columns = this.$refs.table.getColumns()
        let mergeCells = [];
        const columnsToMerge = ['department_name', 'name', 'allDay'];
        columnsToMerge.forEach(key => {
          const col = columns.findIndex(item => item['field'] === key);
          if (col === -1) {
            return;
          }
          for (let i = 0; i < data.length; i++) {
            let rowspan = 1;
            const currentValue = data[i][key];
            for (let j = i + 1; j < data.length; j++) {
              if (data[j][key] === currentValue) {
                rowspan++;
              } else {
                break;
              }
            }
            if (rowspan > 1) {
              mergeCells.push({
                row: i,
                col,
                rowspan,
                colspan: 1
              });
              i += rowspan - 1;
            }
          }
        });
        return mergeCells;
      },

    },
    computed: {},
    created() {
      this.my_department_id = store.state.department?store.state.department.id:''
      this.dName = store.state.department?store.state.department.name:'全部科室'
      if(this.my_department_id){
        this.is_bgs = this.my_department_id==2?true:false
        this.select.department_id = this.my_department_id

      }
      this.getDepartmentList()
      this.getList()
    },
    mounted() {
      this.$nextTick(() => {
        if (this.$refs["table"] && this.$refs["toolbar"]) {
          this.$refs["table"].connect(this.$refs["toolbar"]);
        }
      });
    },
  }
</script>

<style scoped lang="scss">

  ::v-deep .vxe-body--column {
        border-left: 1px solid #333 !important;
        border-bottom: 1px solid #333 !important;
  }
  ::v-deep th.vxe-header--column{
      border-left: 1px solid #333 !important;
      border-bottom: 2px solid #333 !important;
      }
</style>
