<template>
  <span>
    <a-empty
      v-show="!hasData | !selectYear | !selectUnidId"
      :class="$style.empty"
      :description="description"
    ></a-empty>
    <!-- <sd-echart
      v-show="hasData && selectYear && selectUnidId"
      :class="$style.onepieClass"
      :options="chartData"
      autoresize
    /> -->
    <div v-show="selectYear && selectUnidId" :class="$style.typeRadio">
      <a-form-model-item>
        <a-radio-group v-model="statisticsKey">
          <a-radio v-for="mp in statisticsOptions" :key="mp.id" :value="mp.id">
            {{ mp.text }}
          </a-radio>
        </a-radio-group>
      </a-form-model-item>
    </div>
    <div v-show="statisticsKey === '2'" :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="clickFindAuditTree(cate)">
            <div :class="$style.pdiv" :style="{ background: bgcolor[index] }"></div>
            {{ cate.text + ' |' + cate.percent + ' ' + cate.value }}
          </li>
        </ul>
      </div>
      <sd-echart
        v-show="hasData && selectYear && selectUnidId"
        :class="$style.onepieClass"
        :options="pieoption"
        autoresize
      />
    </div>
    <span v-show="statisticsKey === '1'">
      <sd-echart
        v-show="hasData && selectYear && selectUnidId"
        :class="$style.onepieClass"
        :options="option"
        autoresize
      />
    </span>
  </span>
</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 { message } from '@/common/one-ui'
import iamAuditDscService from '../iam-audit-dsc-service'
import components from './_import-components/iam-audit-threepie-import'
const echarts = require('echarts/lib/echarts')

export default {
  name: 'IamAuditThreepie',
  metaInfo: {
    title: 'IamAuditOnepie',
  },
  components,
  props: {
    /**
     * 统计的组织ID
     */
    unidId: {
      type: Array,
      default: () => {
        return []
      },
    },
    /**
     * 统计的年份
     */
    planYear: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      bgcolor: [
        '#7585A2',
        '#73A0FA',
        '#8CCF9E',
        '#E15F30',
        '#EA9200',
        '#5553CE',
        '#1363D5',
        '#73DEB3',
        '#CFE615',
        '#FFB94E',
      ],
      parentId: null,
      historyFindCate: ['AUDIT_FIND_CATEGORY'],
      findCate: [],
      statisticsKey: '1',
      statisticsOptions: [
        { text: '按被审计单位', id: '1' },
        { text: '按审计发现类别', id: '2' },
      ],
      hasData: false, // 是否检查出数据
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            show: true,
            interval: 0,
            rotate: 40,
            inside: false,
            margin: 6,
            formatter: (val) => {
              if (val.length > 5) {
                return (
                  val
                    .split('')
                    .splice(0, 5)
                    .join('') + '...'
                )
              } else {
                return val
              }
            },
          },
        },
        grid: {
          left: 50,
          right: 30,
          bottom: 50,
          top: 30,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: [],
            barWidth: 30,
            type: 'bar',
            itemStyle: {
              barBorderRadius: [20, 20, 0, 0],
              // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              //   { offset: 0, color: '#6ee394' },
              //   { offset: 0.5, color: '#5ac5c5' },
              //   { offset: 1, color: '#49adef' },
              // ]),
              color: '#54c5eb',
            },
          },
        ],
      },
      total: 0,
      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: -300,
            type: 'pie',
            radius: [60, 90],
            avoidLabelOverlap: true,
            data: [],
            label: {
              padding: [0, -90],
              formatter: '{b}\n',
            },
            labelLine: {
              length2: 90,
            },
          },
          {
            type: 'pie',
            top: 30,
            left: -300,
            radius: [1111, 1111],
            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: [],
          },
        ],
      },
    }
  },
  computed: {
    // 因为props传值不会自动更新，使用计算值
    selectYear() {
      return this.planYear
    },
    // 因为props传值不会自动更新，使用计算值
    selectUnidId() {
      if (this.unidId.length > 0) {
        return this.unidId[0].id
      } else {
        return null
      }
    },
    description() {
      if (!this.selectYear | !this.selectUnidId) {
        return '未选择年份以及审计机构'
      } else {
        return '暂无数据'
      }
    },
  },
  watch: {
    statisticsKey() {
      this.getData(true)
      this.historyFindCate = ['AUDIT_FIND_CATEGORY']
    },
  },
  created() {
    // 获取项目总览
    this.getData(true)
  },
  methods: {
    /**
     * 点击分类，获取下级
     */
    clickFindAuditTree(cate) {
      if (cate.leaf) {
        message.info('已是末级节点')
        return false
      }
      this.getFindAuditTree(cate.id)
      this.historyFindCate.push(cate.id)
    },
    /**
     * 获取审计发现类别
     */
    getFindAuditTree(parentId) {
      this.parentId = parentId
      if (!parentId) this.parentId = 'AUDIT_FIND_CATEGORY'
      iamAuditDscService.getFindAuditTree(this.parentId).then((res) => {
        this.findCate = res.data
        this.getData()
      })
    },
    /**
     * 返回上一层级
     */
    gotoHistory() {
      const l = this.historyFindCate.length - 2
      const parentId = this.historyFindCate[l]
      this.historyFindCate.splice(l + 1, 1)
      this.getFindAuditTree(parentId)
    },
    getData(isFirst) {
      // 获取项目总览
      // 如果没有选时间或组织机构，则直接返回
      if (!this.selectYear | !this.selectUnidId) {
        return
      }
      if (isFirst) {
        // 获取审计发现类别
        this.getFindAuditTree()
      }

      // 获取项目总览
      const columns = ['sortNum', 'AUDITED_UNIT']
      for (let i = parseFloat(this.selectYear) - 2; i < parseFloat(this.selectYear) + 3; i++) {
        columns.push(i + '')
      }
      // columns.push(parseFloat(this.selectYear) - 1)
      // columns.push(this.selectYear)

      const params = {
        columns: columns.join(','),
        maxResults: 9999,
        startPosition: 0,
        expressions: [],
        dimension: this.statisticsKey === '1' ? 'units' : 'findType',
        dateStart:
          '' + this.statisticsKey === '1' ? parseFloat(this.selectYear) - 1 : this.selectYear,
        dateEnd: this.selectYear + '',
        unitNames: "'" + this.selectUnidId + "'",
        unitIds: "'" + this.selectUnidId + "'",
        pageIndex: 0,
        pageSize: 9999,
        parentId: this.parentId,
      }
      if (this.statisticsKey === '1') {
        // 按审计单位
        iamAuditDscService.getAuditProjectList(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 ntb = []
          dataObj.data.forEach((item) => {
            ntb.push(item[params.dateEnd])
            ndata.push(item.AUDITED_UNIT)
          })
          this.option.series[0].data = ntb
          this.option.xAxis.data = ndata
        })
      } else {
        // 按审计发现类别
        iamAuditDscService.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
          }
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.onepie-class {
  width: 100%;
  height: 300px;
}
.empty {
  padding-top: 80px;
  margin: 0;
}
.type-radio {
  position: absolute;
  top: 60px;
  right: 10px;
}
.piespan {
  position: relative;
  .cate {
    position: absolute;
    right: 60px;
    top: 30px;
    z-index: 5;
    overflow: auto;
    height: 250px;
    li {
      cursor: pointer;
      list-style: none;
      font-size: 13px;
      line-height: 23px;
      color: #919191;
      padding-left: 15px;
      position: relative;
    }
  }
}
.pdiv {
  height: 14px;
  width: 14px;
  background: #54c5eb;
  border-radius: 11px;
  position: absolute;
  left: -7px;
  top: 5px;
}
.backicon {
  position: absolute;
  top: 3px;
  left: 5px;
  cursor: pointer;
}
</style>
