<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.legend.data) !== '[]'">
        <div><sd-echart :class="$style.echarts" :options="chartData" autoresize /></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/getProjectTrendAnalysisList"
        :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>
  </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 { 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-projecttrends-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'

const baseColumns = [
  {
    title: '序号',
    customRender: function (text, record, index) {
      if (record.name === '合计') {
        return ''
      }
      return index + 1
    },
    width: '80px',
  },
  {
    title: '审计机构',
    dataIndex: '0_NAME',
  },
  {
    title: '审计类型',
    dataIndex: '0_TYPE_CN',
  },
]

export default {
  name: 'IamAuditReportProjecttrends',
  metaInfo: {
    title: '项目趋势分析',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      rules: {
        timeRange: [{ required: true, message: '请选择年度', trigger: 'change' }],
        auditOrg: [{ required: true, message: '请选择审计机构', trigger: 'change' }],
      },
      tableKey: 0,
      ipagination: {
        current: 1,
        pageSize: 10,
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      startYear: null,
      endYear: null,
      form: {
        timeRange: [],
        auditOrg: [],
      },
      columns: [],
      chartData: {
        title: {
          left: 'center',
          text: null,
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            let res = params[0].name
            for (var i = 0, l = params.length; i < l; i++) {
              const seriesId = JSON.parse(params[i].seriesId)
              res +=
                '<br/>' +
                params[i].marker +
                seriesId.NAME +
                ' ' +
                seriesId.TYPE_CN +
                ' : ' +
                params[i].value
            }
            return res
          },
        },
        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: [],
      }, // 查询条件
      flag: true,
      rootNode: {},
    }
  },
  watch: {
    // 查询条件变化时刷新数据
    params() {
      this.$refs.dataTable.refresh(true)
    },
  },
  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: {
    dataLoaded(eventData) {
      if (!eventData.data) {
        return
      }

      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['0_TYPE_CN'])
        const seriesData = chartData.xAxis.map((year) => {
          return item[year] ? item[year] : 0
        })
        chartData.series.push({
          name: item['0_TYPE_CN'],
          type: 'line',
          stack: index,
          data: seriesData,
          id: JSON.stringify({
            NAME: item['0_NAME'],
            TYPE_CN: item['0_TYPE_CN'],
            TYPE: item['0_TYPE'],
          }),
        })
      })

      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')
    },
    submitForm() {
      // if (this.flag) {
      this.flag = false
      // } else {
      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,
          }
        }
      })
      // }
    },
    processReq(req) {
      let dep = ''
      if (this.params.auditOrg.length > 0) {
        dep = this.params.auditOrg[0].id
      }
      req.data = {
        ...req.data,
        dateStart: this.params.startYear,
        dateEnd: this.params.endYear,
        unitIds: "'" + dep + "'",
        pageIndex: req.data.startPosition,
        pageSize: req.data.maxResults,
      }
      return req
    },
    resetForm() {
      this.startYear = null
      this.endYear = null
      this.form = {
        timeRange: [],
        auditOrg: [],
      }
    },
    exportForm() {
      if (this.$refs.dataTable.data.length === 0) {
        message.warning('未查询出可导出数据', 1)
        return
      }
      this.exportLoading = true
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          let dep = ''
          if (this.form.auditOrg.length > 0) {
            dep = this.form.auditOrg[0].id
          }
          const params = {
            dateStart: moment(this.form.timeRange[0]).format('YYYY'),
            dateEnd: moment(this.form.timeRange[1]).format('YYYY'),
            unitIds: "'" + dep + "'",
          }

          auditService
            .exportXMQSData(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: "'" + record.UNIT_ID + "'",
        auditType: record['0_TYPE'],
        amount: '1',
      }
      if (record.UNIT_NAME === '总计') {
        param.unitIds = this.params.auditOrg
          .map((item) => {
            return "'" + item.id + "'"
          })
          .join(',')
      }

      const url =
        '#/audit-annualplancompletion-project-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=projecttrends'
      window.open(url)
    },
    chartClick(evtArgs) {
      const seriesId = JSON.parse(evtArgs.seriesId)

      const param = {
        planYear: evtArgs.name,
        unitNames: "'" + seriesId.NAME + "'",
        auditType: seriesId.TYPE,
        amount: '1',
      }

      const url =
        '#/audit-annualplancompletion-project-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=projecttrends'
      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>
