<template>
  <div :class="$style.personalStatistics">
    <a-card :class="$style.conditions">
      <a-form-model
        ref="advancedSearchForm"
        class="ant-advanced-search-form"
        :model="form"
        :rules="rules"
        v-bind="formItemLayout"
      >
        <a-row :gutter="24" :class="$style.antformitem">
          <a-col :span="8">
            <a-form-model-item label="年度" prop="timeRange">
              <AuditRangePicker :time-range.sync="form.timeRange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审计机构" prop="unitNames">
              <AuditGroupPicker
                ref="unitNames"
                v-model="form.unitNames"
                :single="false"
                :read-only="false"
                :root-node="rootNode"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <div :class="$style.buttonContent">
              <a-button @click="handleReset">重置</a-button>
              <a-button type="primary" @click="handleAction('serach')">查询</a-button>
              <a-button :loading="exportLoading" type="primary" @click="handleAction('export')"
                >导出</a-button
              >
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <p :class="$style.tableTitle"> 人员工作情况统计 </p>
    <a-card class="reporttablecardxm">
      <div v-show="false" id="hj">
        <sd-data-table-hj
          ref="dataTablehj"
          :key="dataKeysum"
          :process-req="processReqsum"
          :columns="columnssum"
          :projectlist="true"
          :defultpagination-pagesize="50"
          data-url="api/xcoa-mobile/v1/iam-statistics/getUserStatusList"
          @dataLoaded1="dataLoadedsum"
          @fnonloadsum="fnonloadsum"
          @rowClick="rowClick"
        >
        </sd-data-table-hj>
      </div>
      <sd-data-table
        ref="dataTable"
        :key="dataKey"
        :process-req="processReq"
        :columns="columns"
        :projectlist="true"
        :defultpagination-pagesize="50"
        data-url="api/xcoa-mobile/v1/iam-statistics/getUserStatusList"
        @dataLoaded="dataLoaded"
        @rowClick="rowClick"
      >
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import AuditRangePicker from '../../components/picker/audit-range-picker.vue'
import AuditGroupPicker from '../../components/picker/audit-group-picker.vue'
import components from './_import-components/audit-personnel-work-statistics-import'
import StatisticsService from './statistics-service'
import { message } from '@/common/one-ui'
import download from '@/common/services/download'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
export default {
  name: 'AuditPersonnelWorkStatistics',
  metaInfo: {
    title: '机构人员统计',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      dataKey: 0,
      reqData: {
        dateStart: '3000',
        dateEnd: '',
        unitNames: '',
      },
      data: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '66px',
        },
        {
          title: '审计师',
          dataIndex: 'USER_NAME',
          width: '110px',
        },
        {
          title: '账户',
          dataIndex: 'USER_ACCOUNT',
          width: '110px',
        },
        {
          title: '在审项目数',
          dataIndex: 'DOING',
          width: '115px',
          sdClickable: true,
        },
        {
          title: '已审项目数',
          dataIndex: 'DONE',
          width: '115px',
          sdClickable: true,
        },
        {
          title: '担任审计组长次数',
          dataIndex: 'CHIEF_NUM',
          width: '128px',
          sdClickable: true,
        },
        {
          title: '提出问题数量',
          dataIndex: 'QUESTION_NUM',
          width: '128px',
          sdClickable: true,
        },
        {
          title: '属于零容忍事项问题',
          dataIndex: 'ZERO_TOLERATE_NUM',
          width: '128px',
          sdClickable: true,
        },
        // {
        //   title: '纳入审计项目成果物问题数量',
        //   dataIndex: 'INTO_NUM',
        //   width: '128px',
        //   sdClickable: true,
        // },
        // {
        //   title: '提出高风险问题数量',
        //   dataIndex: 'RISK_NUM',
        //   width: '128px',
        //   sdClickable: true,
        // },
        // {
        //   title: '执行问责数量',
        //   dataIndex: 'ACCOUNTABILITY_NUM',
        //   width: '128px',
        //   sdClickable: true,
        // },
      ],
      columnssum: [
        {
          title: '审计师',
          dataIndex: 'USER_NAME',
          width: '110px',
        },
        {
          title: '担任审计组长次数',
          dataIndex: 'CHIEF_NUM',
          width: '128px',
          sdClickable: true,
        },
        {
          title: '提出问题数量',
          dataIndex: 'QUESTION_NUM',
          width: '128px',
          sdClickable: true,
        },
        // {
        //   title: '纳入审计项目成果物问题数量',
        //   dataIndex: 'INTO_NUM',
        //   width: '128px',
        //   sdClickable: true,
        // },
        {
          title: '属于零容忍事项问题',
          dataIndex: 'ZERO_TOLERATE_NUM',
          width: '128px',
          sdClickable: true,
        },
        // {
        //   title: '提出高风险问题数量',
        //   dataIndex: 'RISK_NUM',
        //   width: '128px',
        //   sdClickable: true,
        // },
        // {
        //   title: '执行问责数量',
        //   dataIndex: 'ACCOUNTABILITY_NUM',
        //   width: '128px',
        //   sdClickable: true,
        // },
      ],
      form: {
        unitNames: [],
        timeRange: [],
      },
      rules: {
        timeRange: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
        unitNames: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      hj: {},
      hjarr: [],
      rootNode: {},
      dataKeysum: 0,
    }
  },
  created() {
    let userInfo = getUserInfo()
    const params = {
      orgId: userInfo.deptId,
    }
    axios({
      url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
      method: 'get',
    }).then((res) => {
      userInfo = res.data
      params.orgId = res.data.id
      axios({
        url: 'api/xcoa-mobile/v1/iamorg/findIamOrg',
        method: 'post',
        params,
      }).then((res) => {
        this.id = res.data.id
        const deptCode = res.data.orgId + ''
        const deptName = res.data.orgName
        this.rootNode = { code: deptCode, name: deptName, id: this.id }
      })
    })
  },
  mounted() {
    const ym = 'chiefTotal;questionTotal;greatProblemTotal;'
    const arrym = ym.split(';')
    this.hjarr = arrym
  },
  methods: {
    processReq(req, pagination) {
      req.data = {
        maxResults: req.data.maxResults,
        startPosition: req.data.startPosition,
        dateStart: this.reqData.dateStart,
        dateEnd: this.reqData.dateEnd,
        unitIds: this.reqData.unitNames,
      }
      return req
    },
    dataLoaded(res) {
      this.dataKeysum++
      if (res.data.length) {
        res.data.forEach((item, index) => {
          item.id = index + 1
        })

        this.hjarr.forEach((item) => {
          this.hj[item] = res.respData[item]
        })

        return res
      } else {
        if (this.reqData.dateStart !== '3000') message.warn('没有查询到相关数据！')
      }
    },
    processReqsum(req, pagination) {
      req.data = {
        maxResults: req.data.maxResults,
        startPosition: req.data.startPosition,
        dateStart: this.reqData.dateStart,
        dateEnd: this.reqData.dateEnd,
        unitIds: this.reqData.unitNames,
      }
      return req
    },
    dataLoadedsum(res) {
      if (res.data.length) {
        res.data.splice(0, res.data.length)
        const obj = {}
        let j = 0
        this.columnssum.forEach((item, index) => {
          if (index > 0) {
            obj[item.dataIndex] = res.respData[this.hjarr[j]]
            j++
          }
        })
        obj.id = 1
        obj.USER_NAME = '总计'
        res.data.push(obj)
        return res
      }
    },
    fnonloadsum() {
      // 先删除合计行
      document.querySelectorAll('.ant-table-tbody .childsum').forEach((item) => item.remove())
      setTimeout(() => {
        if (
          document
            .getElementById('hj')
            .getElementsByClassName('ant-table-tbody')[0]
            .getElementsByTagName('tr').length > 0
        ) {
          const obj = document.getElementById('hj').getElementsByClassName('ant-table-tbody')[0]
            .firstChild
          obj.firstChild.colSpan = 5
          obj.classList.add('childsum')
          document.getElementsByClassName('ant-table-tbody')[1].appendChild(obj)
        }
      }, 0)
    },

    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
    },
    handleAction(type) {
      debugger
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          // 处理时间
          this.reqData.dateStart = this.form.timeRange[0].year() + ''
          this.reqData.dateEnd = this.form.timeRange[1].year() + ''
          // 处理部门
          const arr = []
          this.form.unitNames.forEach((item) => {
            arr.push(`${item.id}`)
          })
          this.reqData.unitNames = arr.join(',')
          this.reqData.unitIds = arr.join(',')
          // 调用方法
          switch (type) {
            case 'serach':
              this.handleSearch()
              break
            case 'export':
              this.handleExport()
              break
          }
        }
      })
    },
    handleSearch() {
      this.reqData.startPosition = 0
      this.dataKey++
      this.dataKeysum++
    },
    handleExport() {
      if (this.$refs.dataTable.data.length === 0) {
        message.warning('未查询出可导出数据', 1)
        return
      }
      this.exportLoading = true
      StatisticsService.exportPersonalWorkStatisticsList(this.reqData).then((data) => {
        const url = URL.createObjectURL(data)
        download(url, '机构人员统计表.xls')
        this.exportLoading = false
      })
    },
    rowClick(record, { rowIndex, column }) {
      const param = {
        dateStart: this.reqData.dateStart,
        dateEnd: this.reqData.dateEnd,
        unitIds: this.form.unitNames.map((n) => "'" + n.id + "'").join(','),
      }
      if (record.UNIT_NAME !== '总计') {
        param.userAccount = record.USER_ACCOUNT
      }
      let url = ''
      if (
        column.dataIndex === 'DOING' ||
        column.dataIndex === 'DONE' ||
        column.dataIndex === 'CHIEF_NUM'
      ) {
        // 项目列表 在审 和已审 担任组长
        url = '#/audit-annualplancompletion-project-list?params='
        param.columnValue = column.dataIndex
      } else if (column.dataIndex === 'QUESTION_NUM') {
        // 发现列表 QUESTION_NUM
        param.unitIds = this.form.unitNames.map((n) => n.id).join(',')
        url = '#/audit-problemamount-find-list?params='
        param.findType = '01'
      } else if (column.dataIndex === 'ZERO_TOLERATE_NUM') {
        // 发现列表 ZERO_TOLERATE_NUM
        param.unitIds = this.form.unitNames.map((n) => n.id).join(',')
        url = '#/audit-problemamount-find-list?params='
        param.findType = '05'
      }
      // else if (column.dataIndex === 'INTO_NUM') {
      //   // 发现列表 INTO_NUM 纳入审计报告问题数量
      //   param.unitIds = this.form.unitNames.map((n) => n.id).join(',')
      //   url = '#/audit-problemamount-find-list?params='
      //   param.findType = '02'
      // } else if (column.dataIndex === 'RISK_NUM') {
      //   // 发现列表RISK_NUM 提出高风险问题数量
      //   param.unitIds = this.form.unitNames.map((n) => n.id).join(',')
      //   url = '#/audit-problemamount-find-list?params='
      //   param.findType = '03'
      // } else if (column.dataIndex === 'ACCOUNTABILITY_NUM') {
      //   // 发现列表 ACCOUNTABILITY_NUM 执行问责数量
      //   param.unitIds = this.form.unitNames.map((n) => n.id).join(',')
      //   url = '#/audit-problemamount-find-list?params='
      //   param.findType = '04'
      // }
      // if (column.dataIndex === 'OUTSIDE_NUM ') {
      // }
      url = url + encodeURIComponent(JSON.stringify(param)) + '&type=personnelworkstatistics'
      window.open(url)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.personalStatistics {
  :global(.ant-table-body) {
    overflow-x: scroll !important;
  }
  :global(.ant-form-item) {
    margin: 0;
  }

  :global(.ant-table-empty) {
    :global(.ant-table-body) {
      overflow-x: scroll !important;
    }
  }
  .conditions {
    margin-bottom: 20px;
  }
  .buttonContent {
    padding-top: 6px;
    text-align: right;
    button {
      margin: 0 4px;
    }
  }
  :global(.anticon-setting) {
    display: none;
  }
  .tableTitle {
    padding-top: 16px;
    margin: 0;
    font-size: 22px;
    font-weight: bold;
    color: #404040;
    text-align: center;
    background: white;
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      min-height: auto !important;
      overflow: auto;
    }
  }
  :global(.ant-table-placeholder) {
    height: auto !important;
  }
}
</style>
