<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="true"
                :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">
                <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
      >
      <template v-if="flagpie && JSON.stringify(pieoption.series[0].data) !== '[]'">
        <div :class="$style.piespan">
          <!-- <div :class="$style.cate">
            <a-icon
              v-show="historyFindCate.length > 1"
              type="left-circle"
              theme="filled"
              :class="$style.backicon"
              @click="gotoHistory"
            ></a-icon>
            <ul>
              <li v-for="(cate, index) in findCate" :key="cate.id" @click="rowClick_lb(cate)">
                <div :class="$style.pdiv" :style="{ background: bgcolor[index] }"></div>
                <span :class="$style.cateliSpan">{{ cate.text }}</span>
                <span :class="$style.cateliPoint">{{ ' |' + cate.percent + '\u2002\u2002' }}</span>
                <span style="color:#0162eb">{{ cate.value }}</span>
              </li>
            </ul>
          </div> -->
          <div :class="$style.cate">
            <a-icon
              v-show="historyFindCate.length > 1"
              type="left-circle"
              theme="filled"
              :class="$style.backicon"
              @click="gotoHistory"
            ></a-icon>
            <ul>
              <li
                v-for="(cate, index) in findCate"
                :key="cate.id"
                @click="clickFindAuditTree(cate)"
              >
                <div :class="$style.pdiv" :style="{ background: bgcolor[index] }"></div>
                <!-- {{ cate.text + ' |' + cate.percent + ' ' + cate.value }} -->
                <span :class="$style.cateliSpan">{{ cate.text }}</span>
                <span :class="$style.cateliPoint">{{ ' |' + cate.percent + '\u2002\u2002' }}</span>
                <span style="color: #0162eb" @click.stop="rowClick_lb(cate)">{{ cate.value }}</span>
              </li>
            </ul>
          </div>
          <sd-echart :class="$style.echarts" :options="pieoption" autoresize />
        </div>
      </template>
      <template v-else-if="flagtb && option.series.length !== 0">
        <div>
          <sd-echart :key="optionkey" :class="$style.echarts" :options="option" autoresize
        /></div>
      </template>
      <template
        v-else-if="
          JSON.stringify(pieoption.series[0].data) === '[]' && option.series.length === 0 && !flag
        "
      >
        <div :class="$style.emptyecharts"> </div>
      </template>
      <sd-data-table
        v-show="!flagpie"
        :key="tableKey"
        ref="dataTable"
        class="findTable"
        :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"
        @rowClick="rowClick"
        @fnonloadsum="fnonloadsum"
      >
        <template slot="SUM1" slot-scope="text, record">
          <span v-if="text === '0' || text === 0">{{ text }}</span>
          <a v-else @click="rowClick(record, 1)">{{ text }}</a>
        </template>
        <template slot="SUM2" slot-scope="text, record">
          <span v-if="text === '0' || text === 0">{{ text }}</span>
          <a v-else @click="rowClick(record, 2)">{{ text }}</a>
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import 'echarts/lib/chart/treemap'
import 'echarts/lib/chart/pie'
import 'echarts/lib/chart/pictorialBar'
import 'echarts/lib/component/title'
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/legendScroll'
import 'echarts/lib/component/tooltip'
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-find-import'
import { Modal, message } from '@/common/one-ui'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import TableColumnTypes from '@/common/services/table-column-types'
import download from '@/common/services/download'
const echarts = require('echarts/lib/echarts')
export default {
  name: 'AuditStatisticsFind',
  metaInfo: {
    title: '审计发现统计',
  },
  components: {
    ...components,
    AuditRangePicker,
    AuditGroupPicker,
  },
  data() {
    return {
      exportLoading: false,
      optionkey: 0,
      bgcolor: [
        '#7585A2',
        '#73A0FA',
        '#8CCF9E',
        '#E15F30',
        '#EA9200',
        '#5553CE',
        '#1363D5',
        '#73DEB3',
        '#CFE615',
        '#FFB94E',
      ],
      parentId: null,
      historyFindCate: ['AUDIT_FIND_CATEGORY'],
      findCate: [],
      data: [],
      columns: [],
      findcolumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          sdHidden: false,
        },
        {
          title: '发现类别',
          dataIndex: 'FIND_TYPE',
        },
        {
          title: '占比',
          dataIndex: 'PERCENT',
        },
        {
          title: '数量',
          dataIndex: 'NUM',
        },
      ],
      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%',
      },
      flag: true,
      flagpie: false,
      flagtb: false,
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            show: true,
            interval: 0,
            rotate: -40,
            inside: false,
            margin: 6,
          },
        },
        yAxis: {
          type: 'value',
        },
        series: [
          // {
          //   data: [],
          //   type: 'bar',
          //   itemStyle: {
          //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //       { offset: 0, color: '#6ee394' },
          //       { offset: 0.5, color: '#5ac5c5' },
          //       { offset: 1, color: '#49adef' },
          //     ]),
          //   },
          // },
        ],
      },
      total: 0,
      // pieoption: {
      //   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',
      //           },
      //         },
      //       },
      //     },
      //   ],
      //   tooltip: {
      //     trigger: 'item',
      //     formatter: '{b} <br/>{c}个  {d}%',
      //   },
      //   legend: {
      //     show: false,
      //     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,
      //     },
      //   ],
      // },

      pieoption: {
        textStyle: {
          color: '#8a8a8a',
          fontSize: 13,
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b} <br/>{c}个  {d}%',
        },
        legend: {
          show: false,
          type: 'scroll',
          orient: 'vertical',
          right: 59,
          icon: 'circle',
          top: 50,
          textStyle: {
            color: '#8a8a8a',
            lineHeight: 18,
          },
          data: [],
        },
        series: [
          {
            top: 30,
            left: -100,
            type: 'pie',
            radius: ['45%', '60%'],
            avoidLabelOverlap: true,
            data: [],
            label: {
              padding: [0, -90],
              formatter: '{b}\n',
            },
            labelLine: {
              length2: 90,
            },
          },
          {
            type: 'pie',
            top: 30,
            left: -100,
            radius: [9999, 9999],
            label: {
              show: true,
              position: 'center',
              fontSize: 20,
              fontWeight: 'bold',
              formatter: ['{name|{b}}', '{num|{c}}'].join('\n'),
              rich: {
                name: {
                  fontSize: 14,
                  lineHeight: 30,
                  color: '#333',
                },
                num: {
                  fontSize: 30,
                  fontWeight: 600,
                  color: '#333',
                },
              },
            },
            emphasis: {
              disabled: true,
              scale: true,
              scaleSize: 0,
            },
            tooltip: {
              show: false,
            },
            labelLine: {
              show: true,
            },
            data: [],
          },
        ],
      },
      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 }
      })
    })
    // 获取审计发现类别
    this.getFindAuditTree(this.historyFindCate[0])
  },
  methods: {
    /**
     * 点击分类，获取下级
     */
    clickFindAuditTree(cate) {
      if (cate.leaf) {
        message.info('已是末级节点')
        return false
      }
      this.getFindAuditTree(cate.id)
      this.historyFindCate.push(cate.id)
    },
    /**
     * 获取审计发现类别
     */
    getFindAuditTree(parentId) {
      this.params.parentId = parentId
      this.parentId = parentId
      if (!parentId) this.parentId = 'AUDIT_FIND_CATEGORY'
      StatisticsService.getFindAuditTree(this.parentId).then((res) => {
        this.findCate = res.data
        this.dataLoaded({
          data: [],
        })
      })
    },
    /**
     * 返回上一层级
     */
    gotoHistory() {
      const l = this.historyFindCate.length - 2
      const parentId = this.historyFindCate[l]
      this.historyFindCate.splice(l + 1, 1)
      this.getFindAuditTree(parentId)
    },
    dataLoaded(eventData) {
      if (this.flag) {
        return
      }
      eventData.data.forEach((item, index) => {
        item.sortNum = index + 1
        item.id = index
      })
      const ndata = []
      if (this.type === '2') {
        const params = {
          // columns: columns.join(','),
          maxResults: 9999,
          startPosition: 0,
          expressions: [],
          dimension: 'findType',
          dateStart: '' + this.params.dateStart,
          dateEnd: '' + this.params.dateEnd,
          unitNames: this.form.unitNames.map((n) => "'" + n.id + "'").join(','),
          unitIds: this.form.unitNames.map((n) => "'" + n.id + "'").join(','),
          pageIndex: 0,
          pageSize: 9999,
          parentId: this.parentId,
        }
        // 按审计发现类别
        StatisticsService.getReportFindList(params).then((res) => {
          const dataObj = res.data
          // 有数据才展示
          if (dataObj.data.length > 0) {
            this.hasData = true
          } else {
            this.hasData = false
          }
          dataObj.data.forEach((item, index) => {
            item.sortNum = index + 1
            item.id = index
          })
          const ndata = []

          const npie = []
          let isAllZero = true
          dataObj.data.forEach((item, index) => {
            const obj = {
              name: item.FIND_TYPE.replace(/"/g, ''),
              value: parseFloat(item.NUM),
              PERCENT: item.PERCENT,
              label: {
                show: parseFloat(item.NUM) !== 0,
              },
              labelLine: {
                show: parseFloat(item.NUM) !== 0,
              },
            }
            if (parseFloat(item.NUM) !== 0) {
              isAllZero = false
            }
            npie.push(obj)
            ndata.push(item.FIND_TYPE)

            // 根据类别名，将数量又写会cate里面
            this.findCate.forEach((cate) => {
              if (cate.text === item.FIND_TYPE.replace(/"/g, '')) {
                this.$set(cate, 'value', item.NUM)
                this.$set(cate, 'percent', item.PERCENT)
              }
            })
          })
          if (isAllZero) {
            npie.forEach((item) => {
              item.label.show = true
              item.labelLine.show = true
            })
          }
          this.findCate.sort((a, b) => {
            if (parseFloat(a.value) > parseFloat(b.value)) return -1
            if (parseFloat(a.value) < parseFloat(b.value)) return 1
            if (parseFloat(a.value) === parseFloat(b.value)) return 0
          })
          // this.pieoption.title[0].text = '{name|问题总计}\n{val|' + dataObj.sum + '}'
          this.pieoption.series[1].data = []
          this.pieoption.series[1].data.push({ value: dataObj.sum, name: '问题总计' })
          this.pieoption.series[0].data = npie
          this.pieoption.legend.data = ndata
          this.pieoption.legend.formatter = function (name) {
            const obj = npie.find((item) => item.name === name)
            return name + ' |' + obj.PERCENT + ' ' + obj.value
          }
        })

        // const npie = []
        // this.findCate = []
        // eventData.data.forEach((item) => {
        //   const obj = {
        //     name: item.FIND_TYPE,
        //     value: item.NUM,
        //     PERCENT: item.PERCENT,
        //   }
        //   npie.push(obj)
        //   ndata.push(item.FIND_TYPE)
        //   // 根据类别名，将数量又写会cate里面
        //   this.findCate.push({
        //     text: item.FIND_TYPE.replace(/"/g, ''),
        //     value: item.NUM,
        //     percent: item.PERCENT,
        //   })
        // })
        // this.findCate.sort((a, b) => {
        //   if (parseFloat(a.value) > parseFloat(b.value)) return -1
        //   if (parseFloat(a.value) < parseFloat(b.value)) return 1
        //   if (parseFloat(a.value) === parseFloat(b.value)) return 0
        // })
        // this.pieoption.title[0].text = '{name|问题总计}\n{val|' + eventData.respData.sum + '}'
        // this.pieoption.series[0].data = npie
        // this.pieoption.legend.data = ndata
        // this.pieoption.legend.formatter = function(name) {
        //   const obj = npie.find((item) => item.name === name)
        //   return name + ' |' + obj.PERCENT + ' ' + obj.value
        // }
        this.flagpie = true
        this.flagtb = false
      } else {
        // 先默认给个空
        // this.historyFindCate = ['AUDIT_FIND_CATEGORY']
        const ntb = []
        this.option.series = ntb
        eventData.data.forEach((item) => {
          ntb.push(item[this.params.dateEnd])
          ndata.push(item.AUDITED_UNIT)
        })
        // 计算开始时间到结束时间的年份
        let st = parseFloat(this.params.dateStart)
        const et = parseFloat(this.params.dateEnd)
        // 开始时间结束时间差
        const ss = et - st
        for (let i = 0; i <= ss; i++) {
          const dataList = []
          eventData.data.forEach((item) => {
            dataList.push(item[st])
          })
          ntb.push({
            name: st + '',
            data: dataList,
            type: 'bar',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#6ee394' },
                { offset: 0.5, color: '#5ac5c5' },
                { offset: 1, color: '#49adef' },
              ]),
            },
          })
          st++
        }
        // this.option.series[0].data = ntb
        this.option.series = ntb
        this.option.xAxis.data = ndata
        this.flagtb = true
        this.flagpie = false
        this.optionkey++
      }
      return eventData
    },
    fnonloadsum() {
      if (this.flag) {
        document.querySelector('.findTable .ant-table-wrapper').style.display = 'none'
      } else {
        document.querySelector('.findTable .ant-table-wrapper').style.display = ''
      }
    },
    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 type = this.form.statisticsRange
          this.type = type
          this.params.dateStart = startYear
          this.params.dateEnd = endYear
          if (type === '1') {
            this.params.dimension = 'units'
            this.columns = [
              {
                title: '序号',
                dataIndex: 'sortNum',
                width: '80px',
                sdHidden: false,
              },
              {
                title: '被审计单位id',
                dataIndex: 'AUDITED_UNIT_IDS',
                width: '30%',
                sdHidden: true,
              },
              {
                title: '被审计单位',
                dataIndex: 'AUDITED_UNIT',
                width: '30%',
                sdHidden: false,
              },
            ]
            while (startYear <= endYear) {
              this.columns.push({
                title: startYear.toString(),
                dataIndex: startYear.toString(),
                scopedSlots: { customRender: 'number' },
                sdClickable: true,
              })
              startYear++
            }
          } else if (type === '2') {
            this.params.dimension = 'findType'
            this.columns = this.findcolumns
          }
          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) {
      if (!this.params.dimension) {
        this.params.dimension = 'units'
      }
      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('导出失败')
          this.exportLoading = false
        })
    },
    rowClick_lb(cate) {
      const param = {}
      const unit = this.form.unitNames.map((n) => "'" + n.id + "'")
      const unitName = unit.join(',')
      param.unitIds = unitName
      param.dateStart = this.params.dateStart
      param.dateEnd = this.params.dateEnd
      param.findType = cate.id
      param.dimension = 'findType'
      const url =
        '#/audit-problemamount-find-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=projectlist'
      window.open(url)
    },
    rowClick(record, lb) {
      const type = this.form.statisticsRange
      const param = {}
      if (this.form.unitNames.length) {
        const unit = this.form.unitNames.map((n) => "'" + n.id + "'")
        const unitName = unit.join(',')
        param.unitIds = unitName
      }
      // if (lb === 1) {
      //   param.dateStart = this.params.dateStart
      // } else {
      //   param.dateStart = this.params.dateEnd
      // }
      param.dateStart = lb.column.dataIndex
      if (type === '1') {
        param.auditedUnitId = record.AUDITED_UNIT_IDS
      } else {
        param.findType = record.findType
      }
      const url =
        '#/audit-problemamount-find-list?params=' +
        encodeURIComponent(JSON.stringify(param)) +
        '&type=projectlist'
      window.open(url)
      // let time = ''
      // if (lb === 1) {
      //   time = this.params.dateStart
      // } else {
      //   time = this.params.dateEnd
      // }
      // window.open(`#/audit-statistics-find-list?unit=${record.AUDITED_UNIT}&time=${time}`, '_blank')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
// .conditions {
//   margin-bottom: 10px;
// }
// .statistics {
//   background-color: #f0f2f5;
//   .toggle {
//     float: right;
//     margin-right: 8px;
//   }
//   .text-right {
//     // text-align: right;
//   }
//   .reset-btn {
//     margin: 0 5px 10px;
//   }
//   .buttonContent {
//     text-align: right;
//     button {
//       margin: 0 4px;
//     }
//   }
//   .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%;
  background-color: #f0f2f5;
  :global(.sd-has-table.ant-card) {
    min-height: calc(100vh - 320px);
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: calc(100vh - 350px);
      overflow: auto;
    }
  }
}

.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;
}
.piespan {
  position: relative;
  margin-left: -600px;
  .cate {
    position: absolute;
    top: 30px;
    right: 300px;
    z-index: 5;
    // overflow: auto;
    // height: 250px;
    li {
      position: relative;
      padding-left: 15px;
      font-size: 13px;
      line-height: 23px;
      color: #919191;
      list-style: none;
      cursor: pointer;
    }
  }
}
.pdiv {
  position: absolute;
  top: 5px;
  left: -7px;
  width: 14px;
  height: 14px;
  background: #54c5eb;
  border-radius: 11px;
}
.cateli-span {
  display: inline-block;
  width: 180px;
  color: #0162eb;
}
.cateli-point {
  display: inline-block;
  width: 80px;
}
.backicon {
  position: absolute;
  top: 3px;
  left: 5px;
  cursor: pointer;
}
</style>
