<template>
  <div :class="$style.personalStatistics">
    <a-card :class="$style.conditions">
      <a-form-model
        ref="projectSearchForm"
        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
              >

              <!-- <a-button :loading="exportLoading" type="primary" @click="exportGroup"
                    >导出单位及内部审计机构基本情况</a-button
                  > -->
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <p :class="$style.tableTitle"> 审计项目完成情况 </p>
    <a-card class="reporttablecardxm">
      <sd-data-table
        ref="dataTable"
        :key="dataKey"
        :columns="columns"
        :process-req="processReq"
        :defultpagination-pagesize="10"
        data-url="api/xcoa-mobile/v1/spicAuditReportList/projectCompletionStatusList"
        @dataLoaded="dataLoaded"
      >
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import components from './_import-components/audit-project-completion-status-import'
import AuditRangePicker from '@product/iam/components/picker/audit-range-picker.vue'
import AuditGroupPicker from '@product/iam/components/picker/audit-group-picker.vue'
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: 'AuditProjectCompletionStatusVue',
  metaInfo: {
    title: '审计项目完成情况',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      auditTypeOptions: [],
      exportLoading: false,
      dataKey: 0,
      reqData: {
        dateStart: '',
        dateEnd: '',
        unitNames: '',
      },
      data: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '100px',
        },
        {
          title: '单位',
          dataIndex: 'unitName',
          width: '300px',
        },
        {
          title: '计划内项目数',
          dataIndex: 'inPlanNum',
          width: '150px',
        },
        {
          title: '计划外项目数',
          dataIndex: 'outPlanNum',
          width: '150px',
        },
        {
          title: '完成数',
          dataIndex: 'closeNum',
          width: '120px',
        },
        {
          title: '完成率（%）',
          dataIndex: 'finshedCate',
          width: '150px',
        },
        {
          title: '纳入审计全覆盖范围项目数',
          dataIndex: 'coverNum',
          width: '230px',
        },
        {
          title: '审计子企业户数（户）',
          dataIndex: 'childOrgNum',
          width: '200px',
        },
        {
          title: '其中：审计境外子企业户数(户)',
          dataIndex: 'overseasOrgNum',
          width: '280px',
        },
        {
          title: '审计资产总额(亿元)',
          dataIndex: 'auditAssets',
          width: '200px',
        },
        {
          title: '其中：审计境外资产总额(亿元)',
          dataIndex: 'overseasAuditAssets',
          width: '280px',
        },
        {
          title: '贯彻落实国家重大政策措施审计',
          dataIndex: 'auditType01',
          width: '280px',
        },
        {
          title: '经济责任审计-离任审计',
          dataIndex: 'auditType03',
          width: '220px',
        },
        {
          title: '经济责任审计-任中审计',
          dataIndex: 'auditType04',
          width: '220px',
        },
        {
          title: '资产负债损益审计',
          dataIndex: 'auditType05',
          width: '200px',
        },
        {
          title: '基本建设项目审计',
          dataIndex: 'auditType06',
          width: '200px',
        },
        {
          title: '境外审计',
          dataIndex: 'auditType07',
          width: '120px',
        },
        {
          title: '大数据审计',
          dataIndex: 'auditType08',
          width: '150px',
        },
        {
          title: '回头看审计',
          dataIndex: 'auditType09',
          width: '150px',
        },
        {
          title: '信息系统审计',
          dataIndex: 'auditType10',
          width: '150px',
        },
        {
          title: '风险管理审计',
          dataIndex: 'auditType11',
          width: '150px',
        },
        {
          title: '内部控制审计',
          dataIndex: 'auditType02',
          width: '150px',
        },
        {
          title: '绩效审计',
          dataIndex: 'auditType12',
          width: '120px',
        },
        {
          title: '金融业务审计',
          dataIndex: 'auditType13',
          width: '150px',
        },
        {
          title: '燃料专项审计',
          dataIndex: 'auditType14',
          width: '150px',
        },
        {
          title: '投资专项审计',
          dataIndex: 'auditType15',
          width: '150px',
        },
        {
          title: '科研经费审计',
          dataIndex: 'auditType16',
          width: '150px',
        },
        {
          title: '资金管理审计',
          dataIndex: 'auditType17',
          width: '150px',
        },
        {
          title: '其他',
          dataIndex: 'auditType18',
          width: '120px',
        },
      ],
      form: {
        unitNames: [],
        timeRange: [],
      },
      rules: {
        timeRange: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
        unitNames: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      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/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() {
    this.tableResize()
    // 初始化审计类型数据字典信息
    this.initDictionaryInfo()
    this.initDatePicker()
    this.initGroupPicker()
    // this.handleAction('serach')
  },
  methods: {
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PRODUCT_IAM_AUDIT_TYPE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.auditTypeOptions = res.data
        }
      })
    },
    initDatePicker() {
      const datePick = []
      const time = moment(new Date())
      datePick.push(time)
      datePick.push(time)
      this.form.timeRange = datePick
    },
    initGroupPicker() {
      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) => {
          const userDeptValue = []
          const userDept = {
            code: res.data.orgId + '',
            name: res.data.orgName,
            text: res.data.orgName,
            id: res.data.orgId,
            type: 'Group',
          }
          userDeptValue.push(userDept)
          this.form.unitNames = userDeptValue
          this.$refs.projectSearchForm.validate()
          this.handleAction('serach')
        })
      })
    },
    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}%`
    },

    dataLoaded(res) {
      if (res.data.length) {
        res.data.forEach((item, index) => {
          item.id = index + 1
        })
      } else {
        this.tableResize()
      }
      return res
    },
    handleReset() {
      this.$refs.projectSearchForm.resetFields()
    },
    processReq(req) {
      req.data = {
        maxResults: req.data.maxResults,
        startPosition: req.data.startPosition,
        dateStart: this.reqData.dateStart,
        dateEnd: this.reqData.dateEnd,
        unitIds: this.reqData.unitNames,
      }
      return req
    },
    handleAction(type) {
      this.$refs.projectSearchForm.validate((valid, values) => {
        if (valid) {
          debugger
          if (type === 'serach') {
            if (this.form.timeRange.length === 0 && this.form.unitNames.length === 0) {
              this.handleSearch()
            } else {
              // 处理时间
              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(',')
              this.handleSearch()
            }
          } else {
            debugger
            if (this.form.timeRange.length === 0 && this.form.unitNames.length === 0) {
              this.handleExport()
            } else {
              // 处理时间
              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(',')
              this.handleExport()
            }
          }
        }
      })
    },
    handleSearch() {
      this.reqData.startPosition = 0
      this.dataKey++
    },
    handleExport() {
      axios({
        method: 'post',
        url: 'api/xcoa-mobile/v1/spicAuditReportExport/exportProjectCompletionStatus',
        responseType: 'blob',
        data: {
          unitIds: this.reqData.unitIds,
          dateStart: this.reqData.dateStart,
          dateEnd: this.reqData.dateEnd,
        },
      }).then((res) => {
        const url = URL.createObjectURL(res.data)
        download(url, '审计项目完成情况-内审.xlsx')
      })
    },
  },
}
</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>
