<template>
  <div :class="$style.searchdiv">
    <a-card :class="$style.searchWrap">
      <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 v-model="form.timeRange" :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="statisticsRange">
              <a-radio-group v-model="form.statisticsRange" :class="$style.typeRadio">
                <a-radio v-for="mp in statisticsOptions" :key="mp.id" :value="mp.id">
                  {{ mp.text }}
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="16"> </a-col>
          <a-col :class="$style.searchbutton" :span="8">
            <div class="reportbuttonContent" style="margin-right: 15%">
              <a-button @click="handleReset">重置</a-button>
              <a-button type="primary" html-type="submit" @click="submitForm">查询</a-button>

              <a-button :loading="exportLoading" type="primary" @click="exportData">导出</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card class="reporttablecardxm">
      <span class="header_sd-header_common"
        ><span :class="['toptitle', $style.toptitle]">审计项目统计</span></span
      >
      <sd-data-table
        v-if="flagcs === 1 || flagcs === 2"
        :key="tableKey"
        ref="dataTable"
        :projectlist="true"
        data-url="api/xcoa-mobile/v1/iam-statistics/getAuditProjectList"
        :columns="columns"
        :row-key="(record, index) => index"
        :process-req="processReq"
        :defultpagination-pagesize="50"
        @dataLoaded="dataLoaded"
        @fnonloadsum="fnonloadsum"
        @rowClick="rowClick"
      >
        <template slot="SUM" slot-scope="text, record">
          {{ text ? text : '0' }}
          <!-- <span v-if="text === '0' || text === 0">{{ text }}</span>
          <a v-else @click="rowClick(record, text, aa)">{{ text }}</a> -->
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import AuditRangePicker from '../../components/picker/audit-range-picker.vue'
import AuditGroupPicker from '../../components/picker/audit-group-picker.vue'
import StatisticsService from './statistics-service'
import components from './_import-components/audit-statistics-project-import'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import { message } from '@/common/one-ui'
import TableColumnTypes from '@/common/services/table-column-types'
import download from '@/common/services/download'

export default {
  name: 'AuditStatisticsProject',
  metaInfo: {
    title: '项目统计',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      data: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          sdHidden: false,
        },
        {
          title: '审计机构',
          dataIndex: 'UNIT_NAME',
          width: '150px',
        },
        {
          title: '被审计单位',
          dataIndex: 'AUDITED_UNIT_NAME',
          width: '150px',
        },
      ],
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      dateFormat: 'YYYY',
      form: {
        statisticsRange: '1',
        unitNames: [],
        timeRange: [],
      },
      rules: {
        timeRange: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
        unitNames: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
        statisticsRange: [{ required: true, message: '请选择统计维度', trigger: 'change' }],
      },
      statisticsOptions: [
        { text: '按审计类型', id: '1' },
        { text: '按审计域', id: '2' },
      ],
      params: {},
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
        width: '100%',
      },
      sjlxcolumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          sdHidden: false,
        },
        {
          title: '审计机构',
          dataIndex: 'UNIT_NAME',
          width: '150px',
        },
        {
          title: '被审计单位',
          dataIndex: 'AUDITED_UNIT_NAME',
          width: '150px',
        },
      ],
      sjlxoptions: [],
      sjycolumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          sdHidden: false,
        },
        {
          title: '审计机构',
          dataIndex: 'UNIT_NAME',
          width: '150px',
        },
        {
          title: '被审计单位',
          dataIndex: 'AUDITED_UNIT_NAME',
          width: '150px',
        },
      ],
      sjyoptions: [],
      flagcs: 0,
      flag: false,
      type: '',
      tableKey: 0,
      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() {
    // 初始化数据字典信息
    this.initDictionaryInfo()
  },
  methods: {
    fnonloadsum() {
      if (!this.flag) {
        if (document.getElementsByClassName('ant-pagination').length > 0) {
          document.getElementsByClassName('ant-pagination')[0].style.display = 'none'
        }
        this.flag = true
      } else {
        if (document.getElementsByClassName('ant-pagination').length > 0) {
          document.getElementsByClassName('ant-pagination')[0].style.display = ''
        }
      }
    },
    initDictionaryInfo() {
      // 涉及审计域
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=AUDIT_DOMAIN',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.sjyoptions = res.data
          res.data.forEach((item) => {
            const obj = {
              title: item.name,
              dataIndex: 'SUM_' + item.id,
              width: '150px',
              scopedSlots: { customRender: 'SUM' },
              sdClickable: true,
            }
            this.sjycolumns.push(obj)
          })
          this.sjycolumns.push({
            title: '项目总数',
            dataIndex: 'TOTAL',
            width: '100px',
            scopedSlots: { customRender: 'SUM' },
            sdClickable: true,
          })
        }
      })
      // 审计类型
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PRODUCT_IAM_AUDIT_TYPE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.sjlxoptions = res.data
          res.data.forEach((item) => {
            const obj = {
              title: item.name,
              dataIndex: 'SUM_' + item.id,
              width: '150px',
              scopedSlots: { customRender: 'SUM' },
              sdClickable: true,
            }
            this.sjlxcolumns.push(obj)
          })
          this.sjlxcolumns.push({
            title: '项目总数',
            dataIndex: 'TOTAL',
            width: '100px',
            scopedSlots: { customRender: 'SUM' },
            sdClickable: true,
          })
          this.flagcs = 1
          this.submitForm()
        }
      })
    },
    dataLoaded(eventData) {
      if (this.flagcs === 2) {
        eventData.data.forEach((item, index) => {
          item.sortNum = index + 1
          item.id = index
        })
      } else if (this.flagcs === 1) {
        eventData.data.splice(0, eventData.total)
        eventData.data.splice(eventData.total)
        this.flagcs = 2
      } else {
        eventData.data = []
      }
      return eventData
    },
    submitForm() {
      if (this.flagcs === 1) {
        this.params.dimension = 'type'
        this.columns = this.sjlxcolumns
        this.tableKey++
      } else {
        this.$refs.advancedSearchForm.validate((valid, values) => {
          if (valid) {
            const startYear = moment(this.form.timeRange[0]).format('YYYY')
            const endYear = moment(this.form.timeRange[1]).format('YYYY')
            const type = this.form.statisticsRange
            this.type = type
            this.params.dateStart = startYear
            this.params.dateEnd = endYear
            if (type === '1') {
              this.params.dimension = 'type'
              this.columns = this.sjlxcolumns
            } else if (type === '2') {
              this.params.dimension = 'domains'
              this.columns = this.sjycolumns
            }
            this.params.unitNames = this.form.unitNames.map((n) => "'" + n.id + "'").join(',')
            this.params.unitIds = this.form.unitNames.map((n) => "'" + n.id + "'").join(',')
            this.tableKey++
          }
        })
      }
    },
    processReq(req) {
      req.data = {
        ...req.data,
        dateStart: this.params.dateStart,
        dateEnd: this.params.dateEnd,
        dimension: this.params.dimension,
        unitIds: this.params.unitNames,
        pageIndex: req.data.startPosition,
        pageSize: req.data.maxResults,
      }
      return req
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
      // 特殊处理，清空字段值
      // this.handlesearch()
    },
    // 导出接口
    exportData() {
      if (this.$refs.dataTable.data.length === 0) {
        message.warning('未查询出可导出数据', 1)
        return
      }
      this.exportLoading = true
      StatisticsService.exportData(this.params)
        .then((data) => {
          const url = URL.createObjectURL(data)
          download(url, '审计项目统计.xls')
          this.exportLoading = false
        })
        .catch(() => {
          message.error('导出失败', 3)
          this.exportLoading = false
        })
    },
    rowClick(record, { rowIndex, column }) {
      let type = '1'
      if (this.params.dimension === 'domains') {
        type = '2'
      }
      const param = {
        dateStart: this.params.dateStart,
        dateEnd: this.params.dateEnd,
        dimension: this.params.dimension,
        unitIds: "'" + record.UNIT_ID + "'",
        auditedUnitNames: "'" + record.AUDITED_UNIT_NAME + "'",
      }
      if (type === '1') {
        param.columnValue = this.convertAttrName(this.sjlxcolumns, column.dataIndex)
      } else {
        param.columnValue = this.convertAttrName(this.sjycolumns, column.dataIndex)
      }
      // window.open(`#/sd-webflow/done-pages/${record.instId}`)
      const url =
        '#/audit-annualplancompletion-project-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=projectlist'
      window.open(url)
    },
    convertAttrName(columns, name) {
      let names = name.split('_')
      names = names.map((item, index) => {
        if (index === 0) {
          if (item.toLowerCase() === 'sum') {
            return ''
          } else {
            return item.toLowerCase()
          }
        } else {
          return item.substr(0, 1) + item.substr(1).toLowerCase()
        }
      })
      return names.join('')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.toptitle {
  margin-left: calc(50% - 150px);
  font-size: 22px;
  font-weight: bold;
  color: #404040;
}
.search-wrap {
  margin-bottom: $padding-lg;
  :global(.ant-advanced-search-form) {
    padding: 0;
    background: transparent;
    border: none;
  }
  :global .ant-divider-horizontal {
    margin: 10px 0;
  }
}
.searchdiv {
  height: 100%;
  background-color: #f0f2f5;
  :global(.sd-has-table.ant-card) {
    min-height: 50%;
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      min-height: auto !important;
      overflow: auto;
    }
  }
  :global(.ant-table-placeholder) {
    height: auto !important;
  }
}
:global(.statistics) {
  :global(.ant-table-wrapper) {
    margin-top: 40px;
  }
}
</style>
