<template>
  <div :class="$style.auditProRectify">
    <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">
            <a-form-model-item label="项目来源" prop="projectSource">
              <a-select v-model="form.projectSource" allow-clear>
                <a-select-option
                  v-for="(item, index) in projectSourceList"
                  :key="index"
                  :value="item.id"
                  >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <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-card>
    <p :class="$style.tableTitle"> 整改情况统计（按审计项目查询） </p>
    <a-card>
      <sd-data-table
        ref="dataTable"
        :key="dataKey"
        :columns="columns"
        :process-req="processReq"
        :data-source.sync="data"
        :defultpagination-pagesize="50"
        data-url="api/xcoa-mobile/v1/iam-statistics/getRectifyStatusList"
        @dataLoaded="dataLoaded"
        @rowClick="rowClick"
      >
        <template slot="number" slot-scope="text, record">
          {{ text ? text : '0' }}
        </template>
      </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-project-rectification-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: 'AuditProjectRectification',
  metaInfo: {
    title: '整改情况统计',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      dataKey: 0,
      projectSourceList: [],
      form: {
        projectSource: '',
        unitNames: [],
        timeRange: [],
      },
      rules: {
        timeRange: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
        unitNames: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      reqData: {
        dateStart: '3000',
        dateEnd: '',
        unitNames: '',
        projectSource: '',
      },
      data: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '66px',
        },
        {
          title: '审计机构',
          dataIndex: 'UNIT_NAME',
          width: '100px',
        },
        {
          title: '项目名称',
          dataIndex: 'PROJECT_TITLE',
          width: '100px',
        },
        {
          title: '审计类型',
          dataIndex: 'AUDIT_TYPE',
          width: '100px',
        },
        {
          title: '项目来源',
          dataIndex: 'PROJECT_SOURCE',
          width: '100px',
        },
        {
          title: '需要整改问题数',
          dataIndex: 'NUM',
          width: '144px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '已整改',
          dataIndex: 'DONE',
          width: '80px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '整改中',
          dataIndex: 'DOING',
          width: '80px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '未整改',
          dataIndex: 'TODO',
          width: '80px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '超期未整改',
          dataIndex: 'EXPIRE',
          width: '115px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '风险接受',
          dataIndex: 'RISK',
          width: '100px',
          scopedSlots: { customRender: 'number' },
          sdClickable: true,
        },
        {
          title: '整改完成率',
          dataIndex: 'PERCENT',
          width: '115px',
        },
        {
          title: '实际完成率',
          dataIndex: 'REAL_PERCENT',
          width: '115px',
        },
      ],
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      rootNode: {},
    }
  },
  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/findIamOrgId',
        method: 'post',
        params,
      }).then((res) => {
        this.id = res.data
        const deptCode = userInfo.id.toString()
        const deptName = userInfo.name
        this.rootNode = { code: deptCode, name: deptName, id: this.id }
      })
    })
  },
  mounted() {
    axios({
      url: 'api/xcoa-mobile/v1/dict-manager/dictvalues?keyId=PRODUCT_IAM_AUDIT_PROJECT_SOURCE',
      method: 'get',
    }).then((res) => {
      if (res.status === 200) {
        this.projectSourceList = res.data
      }
    })

    this.tableResize()
  },
  methods: {
    tableResize() {
      document
        .getElementsByClassName('ant-table-empty')[0]
        .getElementsByClassName('ant-table-tbody')[0]
        .appendChild(document.getElementsByClassName('ant-table-placeholder')[0])
      var width = document.getElementsByClassName('ant-table-tbody')[0].offsetWidth
      document.getElementsByClassName('ant-table-placeholder')[0].style.width = `${width}%`
    },
    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,
        projectSource: this.reqData.projectSource,
      }
      return req
    },
    dataLoaded(res) {
      if (res.data.length) {
        res.data.forEach((item, index) => {
          item.id = index + 1
        })
      } else {
        this.tableResize()
      }
      return res
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
    },
    handleAction(type) {
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          // 处理项目来源
          this.reqData.projectSource = this.form.projectSource
          // 处理时间
          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(',')
          // 调用方法
          switch (type) {
            case 'serach':
              this.handleSearch()
              break
            case 'export':
              this.handleExport()
              break
          }
        }
      })
    },
    handleSearch() {
      this.reqData.startPosition = 0
      this.dataKey++
    },
    handleExport() {
      if (this.$refs.dataTable.data.length === 0) {
        message.warning('未查询出可导出数据', 1)
        return
      }
      this.exportLoading = true
      StatisticsService.exportRectifyList(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.reqData.unitNames,
        projectSource: this.reqData.projectSource,
        projectTitle: record.PROJECT_TITLE,
      }
      if (column.dataIndex === 'DONE') {
        // 已整改
        param.rectStatus = '03'
      } else if (column.dataIndex === 'DOING') {
        // 整改中
        param.rectStatus = '02'
      } else if (column.dataIndex === 'TODO') {
        // 未整改
        param.rectStatus = '01'
      } else if (column.dataIndex === 'EXPIRE') {
        // 超期未整改
        param.isTrue = 1
      } else if (column.dataIndex === 'RISK') {
        // 风险接受
        param.rectStatus = '04'
      }
      const url = '#/audit-statistics-find-list?params=' + encodeURIComponent(JSON.stringify(param))
      window.open(url)
    },
  },
}
</script>

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

  :global(.ant-table-empty) {
    :global(.ant-table-body) {
      overflow-x: scroll !important;
    }
  }

  .conditions {
    margin-bottom: 20px;
  }
  .buttonContent {
    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>
