<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: 15px;"
            @click="getList">搜索</el-button>
            <el-popover
              v-if="is_bgs"
              placement="bottom-start"
              title="导入加班"
              width="400"
              trigger="click">
              <template #reference>
                <el-button style="margin-left: 10px;" type="primary" size="small" icon="el-icon-upload">导入加班</el-button>
              </template>
              <template #default>
                <el-upload
                  ref="upload"
                  :action="action"
                  :on-success="uploadSuccess"
                  accept=".xls,.xlsx"
                  :headers="{
                        'Authorization': 'Bearer ' + getToken()
                      }"
                  :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                  <el-button style="margin-left: 10px;" size="small" type="success" @click="uploadData">上传到服务器</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
                </el-upload>
              </template>
            </el-popover>
        </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"
  import { getToken } from "@/utils/auth";
  export default {
    data() {
      return {
        loading: false,
        tableData: [],
        action: `${process.env.VUE_APP_BASE_API}/api/oa/statistics/import-overtime`, // 导入加班

        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: {
      // 导入加班
      getToken,
      uploadData() {
        this.$refs.upload.submit();
      },
      uploadSuccess(response) {
        console.log(response)
        let arr = response.data
        let str = ''
          if(arr.err.length>0){
            arr.err.map(item=>{
              str+=`${item}，`
            })
            this.$message.error(`${str}导入失败`)
            this.getList(true)
          }else{
            this.$message.success(`导入成功`)
            this.getList(true)
          }
      },
      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>
