<template>
  <div :class="$style.personalStatistics">
    <a-card :class="$style.conditions">
      <a-form-model
        ref="StatisticsSearchForm"
        class="ant-advanced-search-form"
        :model="rectForm"
        :rules="rectRules"
        v-bind="formItemLayout"
      >
        <div>
          <a-card>
            <a-row :gutter="24" :class="$style.antformitem">
              <a-col :span="8">
                <span>查询维度: </span>
                <a-radio-group
                  v-model="radioValue"
                  :class="$style.radioGroup"
                  @change="radioOnChange"
                >
                  <a-radio :value="'01'">
                    审计情况
                  </a-radio>
                  <a-radio :value="'02'">
                    被审计情况
                  </a-radio>
                </a-radio-group>
              </a-col>
            </a-row>
          </a-card>
        </div>
        <a-row :gutter="24" :class="$style.antformitem">
          <a-col :span="8">
            <a-form-model-item label="年度" prop="timeRange">
              <AuditRangePicker :time-range.sync="rectForm.timeRange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审计机构" prop="unitNames">
              <AuditGroupPicker
                ref="unitNames"
                v-model="rectForm.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="auditType">
              <sd-select
                v-model="rectForm.auditType"
                :allow-clear="true"
                :options="auditTypeOptions"
                mode="multiple"
              />
            </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="handleRectStatistics('serach')">查询</a-button>
              <a-button
                :loading="exportLoading"
                type="primary"
                @click="handleRectStatistics('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="10"
          data-url="api/xcoa-mobile/v1/spicAuditReportList/projectRectStatisticsList"
          @dataLoaded1="dataLoadedsum"
          @fnonloadsum="fnonloadsum"
        >
        </sd-data-table-hj>
      </div>
      <sd-data-table
        ref="dataTable"
        :key="dataKey"
        :columns="columns"
        :projectlist="true"
        :process-req="processReq"
        :defultpagination-pagesize="10"
        data-url="api/xcoa-mobile/v1/spicAuditReportList/projectRectStatisticsList"
        @dataLoaded="dataLoaded"
      >
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import components from './_import-components/audit-project-rect-statistics-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: 'AuditProjectRectStatistics',
  metaInfo: {
    title: '审计项目整改完成情况及成果统计表',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      auditTypeOptions: [],
      exportLoading: false,
      radioValue: '01',
      radioType: true,
      dataKey: 0,
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '100px',
        },
        {
          title: '项目名称',
          dataIndex: 'projectTitle',
          width: '300px',
        },
        {
          title: '项目实施年度',
          dataIndex: 'planYear',
          width: '200px',
        },
        {
          title: '纠正违规金额（万元）',
          dataIndex: 'accounts',
          width: '200px',
        },
        {
          title: '节约成本费用数额（万元）',
          dataIndex: 'svaingSum',
          width: '250px',
        },
        {
          title: '挽回损失（万元）',
          dataIndex: 'improperSum',
          width: '200px',
        },
        {
          title: '增加收入数额（万元）',
          dataIndex: 'recoverySum',
          width: '200px',
        },
        {
          title: '督促清理往来款项收回资金（万元）',
          dataIndex: 'wasteAmount',
          width: '300px',
        },
        {
          title: '工程结算及竣工决算项目数量（个）',
          dataIndex: 'completionNumber',
          width: '300px',
        },
        {
          title: '新建修订制度、流程、标准数量（项）',
          dataIndex: 'itemNum',
          width: '330px',
        },

        {
          title: '追责问责',
          children: [
            {
              title: '追责问责人次',
              dataIndex: 'personNum',
              width: '200px',
            },
            {
              title: '经济处罚金额（万元）',
              dataIndex: 'economicMoney',
              width: '200px',
            },
          ],
        },
        {
          title: '移送纪检监察线索（条）',
          dataIndex: 'clue',
          width: '250px',
        },

        {
          title: '整改完成情况',
          children: [
            {
              title: '审计发现主要问题汇总表问题数量',
              dataIndex: 'findNum',
              width: '300px',
            },
            {
              title: '审计发现主要问题汇总表累计整改完成率（%）',
              dataIndex: 'rectRates',
              width: '400px',
            },
            {
              title: '审计发现主要问题汇总表到期整改完成率（%）',
              dataIndex: 'rectRate',
              width: '400px',
            },
            {
              title: '审计意见书问题数量（个）',
              dataIndex: 'giveOptionsNum',
              width: '250px',
            },
            {
              title: '审计意见书累计整改完成率（%）',
              dataIndex: 'optionsRectRates',
              width: '400px',
            },
            {
              title: '审计意见书到期整改完成率（%）',
              dataIndex: 'optionsRectRate',
              width: '400px',
            },
            {
              title: '审计建议数量（条）',
              dataIndex: 'suggestion',
              width: '200px',
            },
            {
              title: '建议采纳率（%）',
              dataIndex: 'rectTypeRate',
              width: '200px',
            },
            {
              title: '揭示风险（条）',
              dataIndex: 'peoblemNatuer',
              width: '200px',
            },
            {
              title: '截止本月审计发现主要问题汇总表问题整改完成数',
              dataIndex: 'wanChengNum',
              width: '400px',
            },
            {
              title: '截止本月审计意见书问题整改完成数',
              dataIndex: 'wanChengOptionsNum',
              width: '300px',
            },
          ],
        },
      ],
      columnssum: [
        {
          title: '年度',
          dataIndex: 'sumName',
          width: '200px',
        },
        {
          title: '纠正违规金额（万元）',
          dataIndex: 'accountsTotal',
          width: '200px',
        },
        {
          title: '节约成本费用数额（万元）',
          dataIndex: 'svaingSumTotal',
          width: '250px',
        },
        {
          title: '挽回损失（万元）',
          dataIndex: 'improperSumTotal',
          width: '200px',
        },
        {
          title: '增加收入数额（万元）',
          dataIndex: 'recoverySumTotal',
          width: '200px',
        },
        {
          title: '督促清理往来款项收回资金（万元）',
          dataIndex: 'wasteAmountTotal',
          width: '300px',
        },
        {
          title: '工程结算及竣工决算项目数量（个）',
          dataIndex: 'completionNumberTotal',
          width: '300px',
        },
        {
          title: '新建修订制度、流程、标准数量（项）',
          dataIndex: 'itemNumTotal',
          width: '330px',
        },
        {
          title: '追责问责人次',
          dataIndex: 'personNumTotal',
          width: '200px',
        },
        {
          title: '经济处罚金额（万元）',
          dataIndex: 'economicMoneyTotal',
          width: '200px',
        },

        {
          title: '移送纪检监察线索（条）',
          dataIndex: 'clueTotal',
          width: '250px',
        },

        {
          title: '审计发现主要问题汇总表问题数量',
          dataIndex: 'findNumTotal',
          width: '300px',
        },
        {
          title: '审计发现主要问题汇总表累计整改完成率（%）',
          dataIndex: 'rectRatesTotal',
          width: '400px',
        },
        {
          title: '审计发现主要问题汇总表到期整改完成率（%）',
          dataIndex: 'rectRateTotal',
          width: '400px',
        },
        {
          title: '审计意见书问题数量（个）',
          dataIndex: 'giveOptionsNumTotal',
          width: '250px',
        },
        {
          title: '审计意见书累计整改完成率（%）',
          dataIndex: 'optionsRectRatesTotal',
          width: '400px',
        },
        {
          title: '审计意见书到期整改完成率（%）',
          dataIndex: 'optionsRectRateTotal',
          width: '400px',
        },
        {
          title: '审计建议数量（条）',
          dataIndex: 'suggestionTotal',
          width: '200px',
        },
        {
          title: '建议采纳率（%）',
          dataIndex: 'rectTypeRateTotal',
          width: '200px',
        },
        {
          title: '揭示风险（条）',
          dataIndex: 'peoblemNatuerTotal',
          width: '200px',
        },
        {
          title: '截止本月审计发现主要问题汇总表问题整改完成数',
          dataIndex: 'wanChengNumTotal',
          width: '400px',
        },
        {
          title: '截止本月审计意见书问题整改完成数',
          dataIndex: 'wanChengOptionsNumTotal',
          width: '300px',
        },
      ],
      reqData: {
        dateStart: '',
        dateEnd: '',
        unitNames: '',
        auditType: '',
      },
      rectForm: {
        unitNames: [],
        timeRange: [],
        auditType: [],
      },
      rectRules: {
        timeRange: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
        unitNames: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      rootNode: {},
      hj: {},
      hjarr: [],
      dataKeysum: 0,
    }
  },
  // computed: {
  //   dataUrl() {
  //     debugger
  //     const userInfo = getUserInfo()
  //     const id = userInfo.getdeptId + ''
  //     const date = new Date()
  //     const year = date.getFullYear

  //     return (
  //       'api/xcoa-mobile/v1/spicAuditReportList/projectRectStatisticsList?dateStart=' +
  //       year +
  //       '&dateEnd=' +
  //       year +
  //       'unitIds=' +
  //       id
  //     )
  //   },
  // },
  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 =
      'accountsTotal;svaingSumTotal;improperSumTotal;recoverySumTotal;wasteAmountTotal;' +
      'completionNumberTotal;itemNumTotal;personNumTotal;economicMoneyTotal;clueTotal;findNumTotal;' +
      'rectRatesTotal;rectRateTotal;giveOptionsNumTotal;optionsRectRatesTotal;optionsRectRateTotal;' +
      'suggestionTotal;rectTypeRateTotal;peoblemNatuerTotal;wanChengNumTotal;wanChengOptionsNumTotal'
    const arrym = ym.split(';')
    this.hjarr = arrym
    this.tableResize()
    // 初始化审计类型数据字典信息
    this.initDictionaryInfo()
    this.initDatePicker()
    this.initGroupPicker()
    // this.handleRectStatistics('serach')
  },
  methods: {
    radioOnChange(e, info) {
      debugger
      if (this.radioValue === '01') {
        this.rectRules.unitNames[0].required = true

        this.initGroupPicker()
      } else {
        this.rectRules.unitNames[0].required = false
        this.rectForm.unitNames = []
        this.handleRectStatistics('serach')
      }
    },
    initDatePicker() {
      const datePick = []
      const time = moment(new Date())
      datePick.push(time)
      datePick.push(time)
      this.rectForm.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.rectForm.unitNames = userDeptValue
          this.$refs.StatisticsSearchForm.validate()
          this.handleRectStatistics('serach')
        })
      })
    },
    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
        }
      })
    },
    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.sumName = '合计'
        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 = 3
          obj.classList.add('childsum')
          document.getElementsByClassName('ant-table-tbody')[1].appendChild(obj)
        }
      }, 0)
    },
    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) {
      this.dataKeysum++
      if (res.data.length) {
        res.data.forEach((item, index) => {
          item.id = index + 1
        })
      } else {
        this.tableResize()
      }
      return res
    },
    handleReset() {
      this.$refs.StatisticsSearchForm.resetFields()
    },
    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,
        auditType: this.reqData.auditType,
      }
      return req
    },
    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,
        auditType: this.reqData.auditType,
      }
      return req
    },
    handleSearch() {
      this.reqData.startPosition = 0
      this.dataKey++
      this.dataKeysum++
    },
    handleRectStatistics(type) {
      this.$refs.StatisticsSearchForm.validate((valid, values) => {
        if (valid) {
          if (type === 'serach') {
            if (
              this.rectForm.timeRange.length === 0 &&
              this.rectForm.unitNames.length === 0 &&
              this.problemForm.auditType.length === 0
            ) {
              this.handleSearch()
            } else {
              // 处理时间
              this.reqData.dateStart = this.rectForm.timeRange[0].year() + ''
              this.reqData.dateEnd = this.rectForm.timeRange[1].year() + ''
              // 处理部门
              const arr = []
              this.rectForm.unitNames.forEach((item) => {
                arr.push(`'${item.id}'`)
              })
              this.reqData.unitNames = arr.join(',')
              this.reqData.unitIds = arr.join(',')

              if (this.rectForm.auditType.length !== 0) {
                const auditTypes = []
                this.rectForm.auditType.forEach((item) => {
                  auditTypes.push(`'${item.id}'`)
                })
                this.reqData.auditType = auditTypes.join(',')
              } else {
                this.reqData.auditType = ''
              }

              this.handleSearch()
            }
          } else {
            debugger
            if (this.rectForm.timeRange.length === 0 && this.rectForm.unitNames.length === 0) {
              this.projectRectExport()
            } else {
              // 处理时间
              this.reqData.dateStart = this.rectForm.timeRange[0].year() + ''
              this.reqData.dateEnd = this.rectForm.timeRange[1].year() + ''
              // 处理部门
              const arr = []
              this.rectForm.unitNames.forEach((item) => {
                arr.push(`'${item.id}'`)
              })
              this.reqData.unitNames = arr.join(',')
              this.reqData.unitIds = arr.join(',')

              if (this.rectForm.auditType.length !== 0) {
                const auditTypes = []
                this.rectForm.auditType.forEach((item) => {
                  auditTypes.push(`'${item.id}'`)
                })
                this.reqData.auditType = auditTypes.join(',')
              } else {
                this.reqData.auditType = ''
              }
              this.projectRectExport()
            }
          }
        }
      })
    },

    projectRectExport() {
      axios({
        method: 'post',
        url: 'api/xcoa-mobile/v1/spicAuditReportExport/exportProjectRectStatistics',
        responseType: 'blob',
        data: {
          unitIds: this.reqData.unitIds,
          dateStart: this.reqData.dateStart,
          dateEnd: this.reqData.dateEnd,
          auditType: this.reqData.auditType,
        },
      }).then((res) => {
        const url = URL.createObjectURL(res.data)
        download(url, '审计项目整改完成情况及成果统计表.xls')
      })
    },
  },
}
</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>
