<template>
  <div :class="$style.searchdiv">
    <a-card :class="$style.searchWrap">
      <a-form-model
        ref="advancedSearchForm"
        layout="horizontal"
        :model="form"
        v-bind="formItemLayout"
        :rules="rules"
      >
        <a-row>
          <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="auditOrg">
              <AuditGroupPicker
                v-model="form.auditOrg"
                :read-only="false"
                :single="true"
                :root-node="rootNode"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <div class="reportbuttonContent">
              <a-button @click="resetForm">重置</a-button>
              <a-button
                style="margin: 0 5px 10px"
                type="primary"
                html-type="submit"
                @click="submitForm"
                >查询</a-button
              >
              <a-button type="primary" :loading="exportLoading" @click="exportForm">导出</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
      >
      <template v-if="JSON.stringify(chartData.series[0].data) !== '[]'">
        <div
          ><sd-echart :class="$style.echarts" :options="chartData" autoresize @click="chartClick"
        /></div>
      </template>
      <template v-else-if="JSON.stringify(chartData.series[0].data) === '[]' && !flag">
        <div :class="$style.emptyecharts"> </div>
      </template>
      <span v-else></span>
      <div id="hj" style="display: none">
        <sd-data-table-hj
          ref="dataTablehj"
          :key="dataKeysum"
          :process-req="processReqsum"
          :columns="columnssum"
          :projectlist="true"
          :defultpagination-pagesize="50"
          data-url="api/xcoa-mobile/v1/iam-statistics/getAuditFindMoneyList"
          @dataLoaded1="dataLoadedsum"
          @rowClick="rowClick"
        >
          <template slot="number" slot-scope="text, record">
            {{ text ? text : '0' }}
          </template>
        </sd-data-table-hj>
      </div>
      <sd-data-table
        :key="dataKey"
        ref="dataTable"
        data-url="api/xcoa-mobile/v1/iam-statistics/getAuditFindMoneyList"
        :columns="columns"
        :row-key="(record, index) => index"
        :process-req="processReq"
        :projectlist="true"
        :defultpagination-pagesize="50"
        @dataLoaded="dataLoaded"
        @rowClick="rowClick"
        @fnonloadsum="fnonloadsum"
      >
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/polar'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import { length } from 'lodash/merge'
import moment from 'moment'
import AuditRangePicker from '../../../../components/picker/audit-range-picker.vue'
import AuditGroupPicker from '../../../../components/picker/audit-group-picker.vue'
import auditService from './iam-audit-report-service'
import components from './_import-components/iam-audit-report-problemamount-import'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import { message } from '@/common/one-ui'
import download from '@/common/services/download'

export default {
  name: 'IamAuditReportProblemamount',
  metaInfo: {
    title: '问题涉及金额',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      flag: true,
      dataKey: 0,
      dataKeysum: 0,
      hj: 0,
      rules: {
        timeRange: [{ required: true, message: '请选择年度', trigger: 'change' }],
        auditOrg: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      // tableKey: 0,
      showData: false,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      startYear: null,
      endYear: null,
      form: {
        timeRange: [],
        auditOrg: [],
      },
      params: {
        startYear: '',
        endYear: '',
        auditOrg: [],
      }, // 查询条件
      total: 0,
      chartData: {
        title: [
          {
            text: '{name|金额总计}\n{val|' + this.total + '}',
            top: 'center',
            left: 'center',
            textStyle: {
              rich: {
                name: {
                  fontSize: 14,
                  fontWeight: 'normal',
                  color: '#666666',
                  padding: [10, 0],
                },
                val: {
                  fontSize: 32,
                  fontWeight: 'bold',
                  color: '#333333',
                },
              },
            },
          },
        ],
        legend: {
          show: true,
          data: [],
          icon: 'circle',
          orient: 'vertical',
          x: 'right',
          top: 'middle',
          align: 'left',
          left: '70%',
        },
        series: [
          {
            type: 'pie',
            radius: ['45%', '60%'],
            center: ['50%', '50%'],
            data: [],
            hoverAnimation: false,
          },
        ],
      },
      columns: [
        {
          title: '序号',

          customRender: (text, record, index) => {
            if (record.UNIT_NAME === '总计') {
              return {
                children: '',
              }
            } else {
              return { children: index + 1 }
            }
          },
          width: '80px',
        },
        {
          title: '问题金额性质',
          dataIndex: 'ASSET_TYPE_CN',
        },
        {
          title: '问题金额（万元）',
          dataIndex: 'ASSET_TYPE_SUM',
          sdClickable: true,
        },
        {
          title: '比例',
          dataIndex: 'PERCENT',
        },
      ],
      columnssum: [
        {
          title: '问题金额性质',
          dataIndex: 'ASSET_TYPE_CN',
        },
        {
          title: '问题金额（万元）',
          dataIndex: 'ASSET_TYPE_SUM',
          sdClickable: true,
        },
        {
          title: '比例',
          dataIndex: 'PERCENT',
        },
      ],
      assetType: [],
      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 }
      })
    })
  },
  methods: {
    processReq(req) {
      req.data = {
        ...req.data,
        dateStart: this.params.startYear,
        dateEnd: this.params.endYear,
        unitIds: this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(','),
        // pageIndex: req.data.startPosition,
        // pageSize: req.data.maxResults,
      }
      return req
    },
    dataLoaded(params) {
      const respData = params.respData
      this.hj = respData.sum
      this.assetType = []
      this.chartData.title[0].text = '{name|金额总计}\n{val|' + respData.sum + '}'
      this.chartData.series[0].data = respData.data.map((item) => {
        this.assetType.push(item.ASSET_TYPE_CN)
        return {
          name: item.ASSET_TYPE_CN,
          value: parseFloat(item.ASSET_TYPE_SUM, 10),
          ASSET_TYPE: item.ASSET_TYPE,
          PERCENT: item.PERCENT,
        }
      })
      const data = this.chartData.series[0].data
      this.chartData.legend.data = respData.data.map((item) => {
        return item.ASSET_TYPE_CN
      })
      this.chartData.legend.formatter = function (name) {
        const obj = data.find((item) => item.name === name)
        return name + ' | ' + obj.PERCENT + ' ' + obj.value + '万元'
      }
    },
    processReqsum(req) {
      req.data = {
        ...req.data,
        dateStart: this.params.startYear,
        dateEnd: this.params.endYear,
        unitIds: this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(','),
      }
      return req
    },
    dataLoadedsum(res) {
      if (res.data.length) {
        res.data.splice(0, res.data.length)
        const obj = {}
        obj.ASSET_TYPE_SUM = res.respData.sum
        obj.id = 1
        obj.ASSET_TYPE_CN = '金额总计'
        res.data.push(obj)
        return res
      }
    },
    getTitle() {},
    yearChange(value, name) {
      this[name] = value
      this.form[name] = value.format('YYYY')
      // alert(this.form.year)
    },
    submitForm() {
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          this.flag = false
          this.params = {
            startYear: moment(this.form.timeRange[0]).format('YYYY'),
            endYear: moment(this.form.timeRange[1]).format('YYYY'),
            auditOrg: this.form.auditOrg,
          }
          this.showData =
            this.params.startYear !== '' &&
            this.params.endYear !== '' &&
            this.params.auditOrg.length !== 0
          this.dataKey++
          this.dataKeysum++
        }
      })
    },
    resetForm() {
      this.startYear = null
      this.endYear = null
      this.form.timeRange = []
      this.form.auditOrg = []
    },
    exportForm() {
      if (this.$refs.dataTable.data.length === 0) {
        message.warning('未查询出可导出数据', 1)
        return
      }
      this.exportLoading = true
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          const params = {
            dateStart: moment(this.form.timeRange[0]).format('YYYY'),
            dateEnd: moment(this.form.timeRange[1]).format('YYYY'),
            unitIds: this.form.auditOrg
              .map((item) => {
                return "'" + item.id + "'"
              })
              .join(','),
          }

          auditService
            .exportData(params)
            .then((data) => {
              const url = URL.createObjectURL(data)
              download(url, '问题涉及金额导出.xls')
              this.exportLoading = false
            })
            .catch(() => {
              message.error('导出失败')
              this.exportLoading = false
            })
        }
      })
    },
    chartClick(evtArgs) {
      const param = {
        dateStart: this.params.startYear,
        dateEnd: this.params.endYear,
        unitIds: this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(','),
        assetType: "'" + evtArgs.data.ASSET_TYPE + "'",
      }

      const url =
        '#/audit-problemamount-find-list?params=' + encodeURIComponent(JSON.stringify(param))
      window.open(url)
    },
    fnonloadsum() {
      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 = 2
          obj.classList.add('childsum')
          document.getElementsByClassName('ant-table-tbody')[1].appendChild(obj)
        }
      }, 1000)
    },
    rowClick(record, { rowIndex, column }) {
      const param = {
        dateStart: this.params.startYear,
        dateEnd: this.params.endYear,
        unitIds: this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(','),
      }
      if (record.ASSET_TYPE_CN !== '金额总计') {
        param.assetType = "'" + record.ASSET_TYPE + "'"
      }

      const url =
        '#/audit-problemamount-find-list?params=' + encodeURIComponent(JSON.stringify(param))
      window.open(url)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.emptyecharts {
  width: 600px;
  height: 400px;
  margin: auto auto;
  text-align: center;
  &::after {
    display: block;
    padding-top: 150px;
    content: '无数据';
  }
}
.echarts {
  width: 100%;
  height: 400px;
  margin: auto auto;
  text-align: center;
}
.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%;
  :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;
  }
}
.toptitle {
  margin-left: calc(50% - 150px);
  font-size: 22px;
  font-weight: bold;
  color: #404040;
}
</style>
