<template>
  <div :class="$style.personalStatistics">
    <a-card :class="$style.conditions">
      <a-form-model
        ref="problemSearchForm"
        class="ant-advanced-search-form"
        :model="problemForm"
        :rules="problemRules"
        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="problemForm.timeRange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审计机构" prop="unitNames">
              <AuditGroupPicker
                ref="unitNames"
                v-model="problemForm.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="auditUnitedName">
              <sd-group-picker
                ref="auditUnitedName"
                v-model="problemForm.auditUnitedName"
                :single="false"
                :read-only="false"
                :root-node="rootNode"
                @change="changeunit"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" :class="$style.antformitem">
          <a-col :span="8">
            <a-form-model-item label="项目分类" prop="auditType">
              <sd-select
                v-model="problemForm.auditType"
                :allow-clear="true"
                :options="auditTypeOptions"
                mode="multiple"
              />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="被审计单位" prop="auditUnitedName">
              <AuditGroupPicker
                ref="auditUnitedName"
                v-model="problemForm.auditUnitedName"
                :single="false"
                :read-only="false"
                :root-node="rootNode"
              />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-model-item label="问题名称" prop="findTitle">
              <a-input v-model="problemForm.findTitle" />
            </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="problemHandleAction('serach')">查询</a-button>
              <a-button
                :loading="exportLoading"
                type="primary"
                @click="problemHandleAction('export')"
                >导出</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/problemRectItemList"
        @dataLoaded="dataLoaded"
      >
        <div slot="projectLink" slot-scope="text, record">
          <a :title="text" @click="linkProject(record)">{{ text }}</a>
        </div>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import components from './_import-components/audit-problem-rect-item-import'
import AuditRangePicker from '@product/iam/components/picker/audit-range-picker.vue'
import AuditGroupPicker from '@product/iam/components/picker/audit-group-picker.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
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: 'AuditProblemRectItem',
  metaInfo: {
    title: '审计问题整改明细台账',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      radioValue: '01',
      radioType: true,
      auditTypeOptions: [],
      exportLoading: false,
      dataKey: 0,
      data: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '100px',
        },
        {
          title: '项目单位',
          dataIndex: 'unitName',
          width: '300px',
        },
        {
          title: '被审单位',
          dataIndex: 'auditedUnitNames',
          width: '280px',
        },
        {
          title: '项目名称',
          dataIndex: 'projectTitle',
          width: '200px',
          scopedSlots: { customRender: 'projectLink' },
        },
        {
          title: '项目分类',
          dataIndex: 'auditType',
          width: '250px',
        },
        {
          title: '问题名称',
          dataIndex: 'findTitle',
          width: '250px',
        },

        {
          title: '问题分类',
          dataIndex: 'problemType',
          width: '300px',
        },
        {
          title: '问题类型',
          dataIndex: 'rectType',
          width: '200px',
        },
        {
          title: '问题整改状态',
          dataIndex: 'rectState',
          width: '200px',
        },
        {
          title: '销号状态',
          dataIndex: 'cancellStatus',
          width: '150px',
        },
        {
          title: '是否完成当年整改阶段目标',
          dataIndex: 'whetherFinsh',
          width: '300px',
        },
        {
          title: '措施执行情况',
          dataIndex: 'draftRectMeasure',
          width: '200px',
        },
        {
          title: '计划完成时间',
          dataIndex: 'draftFinishDate',
          width: '200px',
        },
        {
          title: '审计发现问题整改（金额类）（万元）',
          children: [
            {
              title: '调整会计账目',
              dataIndex: 'adjustAccounts',
              width: '200px',
            },
            {
              title: '收回资金：增加收入数额',
              dataIndex: 'recoveryFunds',
              width: '250px',
            },
            {
              title: '收回资金：督促清理往来款项收回资金',
              dataIndex: 'avoidingWasteAmount',
              width: '350px',
            },
            {
              title: '收回资金：其他',
              dataIndex: 'reduceInvestmentAmount',
              width: '220px',
            },
            {
              title: '挽回损失：节约成本费用（开支）数额',
              dataIndex: 'costSavingAmount',
              width: '350px',
            },
            {
              title: '挽回损失：工程审减金额',
              dataIndex: 'engineeringReduction',
              width: '220px',
            },
            {
              title: '挽回损失：清退不当得利',
              dataIndex: 'improperClearanceAmount',
              width: '220px',
            },
            {
              title: '挽回损失：其他',
              dataIndex: 'recoveryLossAmount',
              width: '220px',
            },
            {
              title: '归还原资金渠道',
              dataIndex: 'repaymentChannels',
              width: '220px',
            },
            {
              title: '补缴税费',
              dataIndex: 'paymentTaxesFees',
              width: '220px',
            },
            {
              title: '其他',
              dataIndex: 'otherAmount',
              width: '220px',
            },
          ],
        },
        {
          title: '审计发现问题整改（非金额类）（个）',
          children: [
            {
              title: '新建制度、流程、标准（项）',
              dataIndex: 'newItems',
              width: '300px',
            },
            {
              title: '修订制度、流程、标准（项）',
              dataIndex: 'reviseItems',
              width: '300px',
            },
          ],
        },
        {
          title: '追责问责处理情况',
          children: [
            {
              title: '移送纪检监察部门案件线索（件）',
              dataIndex: 'transferMonitorClue',
              width: '300px',
            },
            {
              title: '追责问责人次',
              dataIndex: 'personNum',
              width: '220px',
            },
            {
              title: '党纪处分：警告',
              dataIndex: 'dealWay01',
              width: '220px',
            },
            {
              title: '党纪处分：严重警告',
              dataIndex: 'dealWay02',
              width: '220px',
            },
            {
              title: '党纪处分：撤销党内职务',
              dataIndex: 'dealWay03',
              width: '220px',
            },
            {
              title: '党纪处分：留党察看',
              dataIndex: 'dealWay04',
              width: '220px',
            },
            {
              title: '党纪处分：开除党籍',
              dataIndex: 'dealWay05',
              width: '220px',
            },
            {
              title: '政务处分：警告',
              dataIndex: 'dealWay06',
              width: '220px',
            },
            {
              title: '政务处分：记过',
              dataIndex: 'dealWay07',
              width: '220px',
            },
            {
              title: '政务处分：记大过',
              dataIndex: 'dealWay08',
              width: '220px',
            },
            {
              title: '政务处分：降级',
              dataIndex: 'dealWay09',
              width: '220px',
            },
            {
              title: '政务处分：撤职',
              dataIndex: 'dealWay10',
              width: '220px',
            },
            {
              title: '政务处分：开除',
              dataIndex: 'dealWay11',
              width: '220px',
            },
            {
              title: '内部纪律处分',
              dataIndex: 'dealWay12',
              width: '220px',
            },
            {
              title: '经济处罚金额（万元）',
              dataIndex: 'amountSum',
              width: '220px',
            },
          ],
        },
        {
          title: '根据审计建议给予党纪、政务和内部纪律处分',
          children: [
            {
              title: '合计',
              dataIndex: 'mentNum',
              width: '220px',
            },
            {
              title: '党纪处分：警告',
              dataIndex: 'dealManner01',
              width: '220px',
            },
            {
              title: '党纪处分：严重警告',
              dataIndex: 'dealManner02',
              width: '220px',
            },
            {
              title: '党纪处分：撤销党内职务',
              dataIndex: 'dealManner03',
              width: '220px',
            },
            {
              title: '党纪处分：留党察看',
              dataIndex: 'dealManner04',
              width: '220px',
            },
            {
              title: '党纪处分：开除党籍',
              dataIndex: 'dealManner05',
              width: '220px',
            },
            {
              title: '政务处分：警告',
              dataIndex: 'dealManner06',
              width: '220px',
            },
            {
              title: '政务处分：记过',
              dataIndex: 'dealManner07',
              width: '220px',
            },
            {
              title: '政务处分：记大过',
              dataIndex: 'dealManner08',
              width: '220px',
            },
            {
              title: '政务处分：降级',
              dataIndex: 'dealManner09',
              width: '220px',
            },
            {
              title: '政务处分：撤职',
              dataIndex: 'dealManner10',
              width: '220px',
            },
            {
              title: '政务处分：开除',
              dataIndex: 'dealManner11',
              width: '220px',
            },
            {
              title: '内部纪律处分',
              dataIndex: 'dealManner12',
              width: '220px',
            },
          ],
        },
        {
          title: '向司法机关移送或报告案件线索',
          dataIndex: 'accountability',
          width: '300px',
        },
        {
          title: '其中：涉案人员',
          dataIndex: 'otherItems',
          width: '300px',
        },
      ],
      problemForm: {
        unitNames: [],
        timeRange: [],
        auditType: [],
        auditUnitedName: [],
        findTitle: '',
      },
      problemRules: {
        timeRange: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
        unitNames: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
        auditUnitedName: [{ required: false, message: '请选择被审计单位', trigger: 'change' }],
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      rootNode: {},
      reqData: {
        dateStart: '',
        dateEnd: '',
        unitNames: '',
        auditType: '',
        auditUnitedName: '',
        findTitle: '',
      },
      auditUnitedName: [],
    }
  },
  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.problemHandleAction('serach')
  },
  methods: {
    hsaReadAuthorityPermission(record) {
      if (
        record.readAuthorityCodes != null &&
        record.readAuthorityCodes.indexOf(getUserInfo().account) > -1
      ) {
        return true
      }
      return false
    },
    linkProject(record) {
      if (
        (record.operatePermission || this.hsaReadAuthorityPermission(record)) &&
        (record.itemStatus === '02' ||
          record.itemStatus === '03' ||
          record.itemStatus === '04' ||
          record.itemStatus === '05' ||
          record.itemStatus === '07')
      ) {
        window.open('#/audit-work/?projectId=' + record.projectId)
      } else {
        var url = '/audit-project-detail?record=' + record.projectId
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
          }
        })
      }
    },
    initDatePicker() {
      const datePick = []
      const time = moment(new Date())
      datePick.push(time)
      datePick.push(time)
      this.problemForm.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.problemForm.unitNames = userDeptValue
          this.$refs.problemSearchForm.validate()
          this.problemHandleAction('serach')
        })
      })
    },
    initUnitedGroupPicker() {
      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.problemForm.auditUnitedName = userDeptValue
          this.$refs.problemSearchForm.validate()
          this.problemHandleAction('serach')
        })
      })
    },
    changeunit(values) {
      debugger
      this.problemForm.auditUnitedName = []
      values.forEach((element) => {
        const auditedUnit = {
          code: element.code + '',
          name: element.name,
          id: element.code,
          type: element.type,
        }

        this.problemForm.auditUnitedName.push(auditedUnit)
      })
    },

    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
        }
      })
    },

    radioOnChange(e, info) {
      debugger
      if (this.radioValue === '01') {
        this.problemRules.unitNames[0].required = true
        this.problemRules.auditUnitedName[0].required = false
        this.problemForm.auditUnitedName = []
        this.initGroupPicker()
      } else {
        this.problemRules.unitNames[0].required = false
        this.problemRules.auditUnitedName[0].required = true
        this.problemForm.unitNames = []
        this.initUnitedGroupPicker()
      }
    },
    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.problemSearchForm.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,
        auditType: this.reqData.auditType,
        auditUnitedId: this.reqData.auditUnitedName,
        findTitle: this.reqData.findTitle,
      }
      return req
    },
    handleSearch() {
      this.reqData.startPosition = 0
      this.dataKey++
    },

    // 审计问题整改明细台账
    problemHandleAction(type) {
      debugger
      this.$refs.problemSearchForm.validate((valid, values) => {
        if (valid) {
          if (type === 'serach') {
            if (
              this.problemForm.timeRange.length === 0 &&
              this.problemForm.unitNames.length === 0 &&
              this.problemForm.auditType.length === 0 &&
              this.problemForm.auditUnitedName.length === 0 &&
              this.problemForm.findTitle === ''
            ) {
              this.handleSearch()
            } else {
              // 处理时间
              this.reqData.dateStart = this.problemForm.timeRange[0].year() + ''
              this.reqData.dateEnd = this.problemForm.timeRange[1].year() + ''
              // 处理部门
              const arr = []
              this.problemForm.unitNames.forEach((item) => {
                arr.push(`'${item.id}'`)
              })
              this.reqData.unitNames = arr.join(',')
              this.reqData.unitIds = arr.join(',')
              if (this.problemForm.auditUnitedName.length !== 0) {
                const arrs = []
                this.problemForm.auditUnitedName.forEach((item) => {
                  arrs.push(`'${item.id}'`)
                })
                this.reqData.auditUnitedName = arrs.join(',')
                this.reqData.auditUnitedId = arrs.join(',')
              } else {
                this.reqData.auditUnitedName = ''
                this.reqData.auditUnitedId = ''
              }
              if (this.problemForm.auditType.length !== 0) {
                const auditTypes = []
                this.problemForm.auditType.forEach((item) => {
                  auditTypes.push(`'${item.id}'`)
                })
                this.reqData.auditType = auditTypes.join(',')
              } else {
                this.reqData.auditType = ''
              }
              if (this.problemForm.findTitle !== '') {
                this.reqData.findTitle = this.problemForm.findTitle + ''
              } else {
                this.reqData.findTitle = ''
              }

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

              this.problemHandleExport()
            }
          }
        }
      })
    },

    problemHandleExport() {
      axios({
        method: 'post',
        url: 'api/xcoa-mobile/v1/spicAuditReportExport/exportProblemRectItem',
        responseType: 'blob',
        data: {
          unitIds: this.reqData.unitIds,
          dateStart: this.reqData.dateStart,
          dateEnd: this.reqData.dateEnd,
          auditType: this.reqData.auditType,
          auditUnitedId: this.reqData.auditUnitedId,
          findTitle: this.reqData.findTitle,
        },
      }).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>
