<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">
            <a-form-model-item label="审计发现类别" prop="findType">
              <a-input
                v-model="form.findType"
                read-only
                :input-props="{ required: true }"
                :required="true"
                @click="showfindcat"
              />
            </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="resetForm">重置</a-button>
              <a-button 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.legend.data) !== '[]'">
        <div><sd-echart :class="$style.echarts" :options="chartData" /></div>
      </template>
      <template v-else-if="JSON.stringify(chartData.legend.data) === '[]' && !flag">
        <div :class="$style.emptyecharts"> </div>
      </template>
      <sd-data-table
        :key="tableKey"
        ref="dataTable"
        data-url="api/xcoa-mobile/v1/iam-statistics/getFindTrendAnalysisList"
        :columns="columns"
        :row-key="(record, index) => index"
        :process-req="processReq"
        :defultpagination-pagesize="50"
        @dataLoaded="dataLoaded"
        @rowClick="rowClick"
      >
        <template slot="number" slot-scope="text, record">
          {{ text ? text : '0' }}
        </template>
      </sd-data-table>
      <!-- 发现分类树 -->
    </a-card>
    <a-modal
      :visible="findcatvisible"
      title="选择"
      width="50%"
      :body-style="{
        height: '400px',
        maxHeight: '500px',
        overflowY: 'auto',
        paddingBottom: '20px',
      }"
      :destroy-on-close="true"
      @ok="handlefindcatOk"
      @cancel="handlefindcatCancel"
    >
      <!-- <div :class="$style.wrapHeight">
            <div :class="$style.rowHeight"> -->
      <AuditFindCatTree
        ref="findTypeTree"
        :single="false"
        :checkable="true"
        :value="selectfindType"
      />
      <!-- </div
          ></div> -->
    </a-modal>
  </div>
</template>

<script>
import 'echarts/lib/chart/line'
import 'echarts/lib/component/polar'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import moment from 'moment'
import AuditRangePicker from '../../../../components/picker/audit-range-picker.vue'
import AuditGroupPicker from '../../../../components/picker/audit-group-picker.vue'
import AuditFindCatTree from '../../../../components/audit-find-cat-tree.vue'
import auditFindCatTreeService from '../../../../components/audit-find-cat-tree-service'
import auditService from './iam-audit-report-service'
import components from './_import-components/iam-audit-report-problemtrends-import'
import download from '@/common/services/download'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import { message, Modal } from '@/common/one-ui'

const baseColumns = [
  {
    title: '序号',
    customRender: function (text, record, index) {
      if (record.name === '合计') {
        return ''
      }
      return index + 1
    },
    width: '80px',
  },
  {
    title: '审计发现类别',
    dataIndex: 'FIND_TYPE',
  },
]

export default {
  name: 'IamAuditReportProblemtrends',
  metaInfo: {
    title: '问题分析趋势',
  },
  components: {
    ...components,
    AuditFindCatTree,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      rules: {
        timeRange: [{ required: true, message: '请选择年度', trigger: 'change' }],
        auditOrg: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
        findType: [{ required: true, message: '请选择发现类别', trigger: 'change' }],
      },
      findcatvisible: false,
      findcat: '',
      findType: '',
      tableKey: 0,
      ipagination: {
        current: 1,
        pageSize: 10,
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      showData: false,
      startYear: null,
      endYear: null,
      form: {
        timeRange: [],
        auditOrg: [],
        findType: '',
      },
      columns: [],
      chartData: {
        title: {
          left: 'center',
          text: null,
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: [],
          bottom: 0,
        },
        grid: {
          // left: '3%',
          // right: '4%',
          // bottom: '3%',
          // containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [],
      },
      params: {
        startYear: '',
        endYear: '',
        auditOrg: [],
        findType: '',
      }, // 查询条件
      flag: true,
      selectfindType: { checked: [], halfChecked: [], selectedData: [] },
      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: {
    showfindcat() {
      this.findcatvisible = !this.findcatvisible
    },
    handlefindcatOk() {
      const findType = this.$refs.findTypeTree.getSelectedNode()
      if (this.$refs.findTypeTree.getSelectedNode().length > 20) {
        Modal.warning({
          title: '提示',
          content: '最多只支持20个类别，请重新选择!',
        })
        return false
      } else if (this.$refs.findTypeTree.getSelectedNode().length !== 0) {
        this.showfindcat()
        this.selectfindType.checked = []
        this.selectfindType.selectedData = []
        findType.forEach((f) => {
          this.selectfindType.checked.push(f.id)
          this.selectfindType.selectedData.push(f) // 选中树节点数据信息 add zhangtt 2023-2-23
        })
        this.form.findType = findType
          .map((item) => {
            return item.text
          })
          .join(',')
      } else {
        Modal.warning({
          title: '提示',
          content: '请选择分类!',
        })
        return false
      }
    },
    handlefindcatCancel() {
      this.showfindcat()
    },

    dataLoaded(eventData) {
      if (!eventData.data) {
        return
      }
      console.log(eventData.data)
      const chartData = {
        legend: [],
        xAxis: [],
        series: [],
      }
      let startYear = moment(this.form.timeRange[0]).format('YYYY')
      const endYear = moment(this.form.timeRange[1]).format('YYYY')
      while (startYear <= endYear) {
        chartData.xAxis.push(startYear.toString())
        startYear++
      }

      eventData.data.forEach((item, index) => {
        chartData.legend.push(item.FIND_TYPE)
        const seriesData = chartData.xAxis.map((year) => {
          return {
            name: item.FIND_TYPE,
            FIND_TYPE: item.FIND_TYPE,
            value: item[year] ? item[year] : 0,
            year: year,
          }
        })
        chartData.series.push({
          name: item.FIND_TYPE,
          type: 'line',
          stack: index,
          data: seriesData,
        })
      })

      this.chartData.legend.data = chartData.legend
      this.chartData.xAxis.data = chartData.xAxis
      this.chartData.series = chartData.series
    },
    yearChange(value, name) {
      this[name] = value
      this.form[name] = value.format('YYYY')
      // alert(this.form.year)
    },
    submitForm() {
      this.flag = false
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          let startYear = moment(this.form.timeRange[0]).format('YYYY')
          const endYear = moment(this.form.timeRange[1]).format('YYYY')
          const columns = []
          while (startYear <= endYear) {
            columns.push({
              title: startYear.toString(),
              dataIndex: startYear.toString(),
              scopedSlots: { customRender: 'number' },
              sdClickable: true,
            })
            startYear++
          }
          this.tableKey++
          this.columns = baseColumns.concat(columns)
          this.params = {
            startYear: moment(this.form.timeRange[0]).format('YYYY'),
            endYear: moment(this.form.timeRange[1]).format('YYYY'),
            auditOrg: this.form.auditOrg,
            findType: this.form.findType,
          }

          this.showData =
            this.params.startYear !== '' &&
            this.params.endYear !== '' &&
            this.params.auditOrg.length !== 0 &&
            this.params.findType !== ''
        }
      })
    },
    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,
      }
      if (this.params.findType !== '') {
        req.data.findType = this.params.findType
          .split(',')
          .map((item) => {
            return "'" + item + "'"
          })
          .join(',')
      } else {
        req.data.findType = ''
      }
      return req
    },
    resetForm() {
      this.startYear = null
      this.endYear = null
      this.form = {
        timeRange: [],
        auditOrg: [],
        findType: '',
      }
    },
    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(','),
            findType: this.form.findType
              .split(',')
              .map((item) => {
                return "'" + item + "'"
              })
              .join(','),
          }

          auditService
            .exportWTQSData(params)
            .then((data) => {
              const url = URL.createObjectURL(data)
              download(url, '问题趋势分析导出.xls')
              this.exportLoading = false
            })
            .catch(() => {
              message.error('导出失败')
              this.exportLoading = false
            })
        }
      })
    },
    rowClick(record, { rowIndex, column }) {
      const param = {
        planYear: column.dataIndex,
        unitIds: this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(','),
        assetType: "'" + record.FIND_TYPE + "'",
      }

      const url =
        '#/audit-problemamount-find-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=problemtrends'
      window.open(url)
    },
    chartClick(evtArgs) {
      const param = {
        planYear: evtArgs.data.year,
        unitIds: this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(','),
        // assetType: "'" + evtArgs.data.FIND_TYPE + "'",
      }

      const url =
        '#/audit-problemamount-find-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=problemtrends'
      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;
}
.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%;
  :global(.sd-has-table.ant-card) {
    min-height: calc(100vh - 270px);
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      min-height: auto !important;
      overflow: auto;
    }
  }
  :global(.ant-table-placeholder) {
    height: auto !important;
  }
}
</style>
