<template>
  <div>
    <!-- :style='{'height':dynamicHeight,'width':dynamicWidth}' -->
    <div
      v-if='!showEmpty'
      :id='domId'
      :style="{
        width: '100%',
        height: height + 'px',
        'padding-top': '15px',
        margin: 'auto',
      }"
    ></div>
    <empty v-else :height='height'></empty>
    <div v-if='showTooltip' :style='style' class='tooltip'>
      {{ tooltipText }}
    </div>
    <echartfull ref="echartFull"  @fullscreen="fullscreen"/>
  </div>
</template>
<script>

/* eslint-disable*/
// 饼图
import { generateUUID } from '@/utils/index'
import empty from '@/components/Common/empty'
import echartfull from './echartFull.vue'
export default {
  name: 'pie',
  components: { empty, echartfull },
  props: {
    // 标签是否换行
    labelWrap: {
      type: Boolean,
      default: false
    },
    // 外部控制隐藏
    propShowEmpty: {
      type: Boolean,
      default: false
    },
    // 数据 必填 格式在最下面
    data: {
      type: Object,
      default: () => {
        return {
          name: '',
          data: []
        }
      }
    },
    // x轴 必填 格式在最下面  这里用在表格头不用表格不用传
    xCategory: {
      type: Object,
      default: () => {
        return { name: '' }
      }
    },
    // y轴 必填 格式在最下面  这里用在表格头不用表格不用传
    yCategory: {
      type: Object,
      default: () => {
        return { name: '' }
      }
    },
    // 单位
    unit: {
      type: String,
      default: ''
    },
    formatter: {
      type: [String, Function],
      default: () => {
        return ''
      }
    },
    // 中空
    radius: {
      type: Boolean,
      default: false
    },

    homepageLabel: {
      type: Boolean,
      default: false
    },
    // 详细label
    specificLabel: {
      type: Boolean,
      default: false
    },
    // summary 附加数据
    summary: {
      type: [Object, Array]
    },
    height: {
      type: Number,
      default: 400
    },
    title: {
      type: String
    },
    centerTitle: {
      type: Boolean,
      default: false
    },
    legendOrder: {
      type: String,
      default: 'left'
    },
    tooltipText: {
      type: String,
      default: ''
    },
    iscolor: {
      type: Boolean,
      default: false
    },
    showtoolbox: {
      type: Boolean,
      default: true
    },
    // 图例颜色大小
    legendWidth: {
      type: Number,
      default: 25
    },
    // 是否展示图例
    showPieLegend: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      domId: generateUUID(),
      chart: {},
      option: {},
      showEmpty: false,
      showTooltip: false,
      style: {
        display: 'none',
        position: 'fixed'
      },
      timer: null,
      colorList: [
        '#5470c6',
        '#91cc75',
        '#fac858',
        '#ee6666',
        '#73c0de',
        '#3ba272',
        '#fc8452',
        '#9a60b4',
        '#ea7ccc'
      ]
    }
  },
  watch: {
    data: {
      handler (newval, oldval) {
        if (Object.keys(this.chart).length) {
          this.chart.dispose()
        }
        this.$nextTick(() => {
          this.initMap()
        })
      },
      deep: true
    },
  },
  mounted () {
    this.initMap()
  },
  methods: {
    fullscreen () {
      this.$emit('fullscreen')
    },
    initMap () {
      if (this.propShowEmpty) {
        this.showEmpty = true
        return
      }

      if (!this.data?.data?.length) {
        this.showEmpty = true
        return
      } else {
        this.showEmpty = false
      }

      var formatter =
        Object.keys(this.formatter).length ||
        typeof this.formatter === 'function'
          ? this.formatter
          : (params) => {
              if (params.value !== 0) {
                return (
                  params.name + ' : ' + params.data.value + ' ' + this.unit
                )
              }
            }

      var label = this.specificLabel
        ? {
            alignTo: 'edge',
            formatter: '{value|{c} ' + this.unit + '}',
            minMargin: 1,
            lineHeight: 5,
            rich: {
              value: {
                fontSize: 14,
                color: '#999'
              }
            }
          }
        : {
            position: 'inner',
            formatter: (e) => {
              // return (e.name + ': ' + e.value + this.unit).replace(/[^\x00-\xff]/g,'$&\x01').replace(/.{8}\x01?/g,'$&\n').replace(/\x01/g,'')
              // let formatter = this.labelWrap ? e.name + ': '+ '\n' + e.value + this.unit : e.name + ': ' + e.value + this.unit
              // return formatter
              let formatter = null
              if (this.labelWrap && e.name.length > 2) {
                formatter = e.name + ': ' + '\n' + e.value + this.unit
              } else {
                formatter = e.name + ': ' + e.value + this.unit
              }
              return formatter
            }
          }

      let title = {
        text: this.title,
        left: '10%'
      }

      if (this.centerTitle) {
        title = Object.assign(title, {
          // left: 'center',
          // textVerticalAlign:'center',
          textAlign: 'center',
          top: '51%',
          left: '49%'
        })
      } else {
        title = Object.assign(title, {
          top: 0
        })
      }
      title.triggerEvent = true
      var legend = {
        show: this.showPieLegend,
        padding: 0,
        itemGap: 8,
        top:
          this.legendOrder === 'left' && this.title && !this.centerTitle
            ? 30
            : 0,
        type: 'scroll',
        itemWidth: this.legendWidth
      }

      if (this.legendOrder === 'left') {
        legend.orient = 'horizontal'
      } else {
        legend.orient = 'vertical'
        legend.left = 0
      }

      this.$nextTick(() => {
        this.chart = this.$echarts.init(
          document.getElementById(this.domId),
          null,
          { renderer: 'svg' }
        )
        // window.addEventListener('resize', () => {
        //   this.chart.resize()
        // })
        this.option = {
          title: title,
          legend: legend,
          grid: {
            right: '8%',
            top: 'middle',
            containLabel: false
          },
          color: this.iscolor ? ['#E040Fb', '#5c7bd9'] : this.colorList,
          label: label,
          labelLine: {
            length: 1,
            length2: 0
          },
          tooltip: {
            trigger: 'item',
            formatter: formatter
          },
          toolbox: {
            show: this.showtoolbox,
            top: 20,
            feature: {
              myTool: {
                show: true,
                title: "放大查看",
                //阿里图标库直接使用symbol引入自动生成路径 ，看path路径
                icon: "path://M184 789.088L389.309 583.78a8 8 0 0 1 11.313 0l39.598 39.598a8 8 0 0 1 0 11.313L234.912 840H384c8.837 0 16 7.163 16 16v48a8 8 0 0 1-8 8H144c-17.673 0-32-14.327-32-32V632a8 8 0 0 1 8-8h48c8.837 0 16 7.163 16 16v149.088z m656-554.422L634.569 440.098a8 8 0 0 1-11.314 0L583.657 400.5a8 8 0 0 1 0-11.314L788.843 184H640c-8.837 0-16-7.163-16-16v-48a8 8 0 0 1 8-8h248c17.673 0 32 14.327 32 32v248a8 8 0 0 1-8 8h-48c-8.837 0-16-7.163-16-16V234.666z",
                // 弹框
                onclick: (e) => {
                  this.$refs.echartFull.show("", e.getOption(this.option), "id");
                },
              },
              saveAsImage: {},
            }
          },
          series: [
            {
              type: 'pie',
              name: this.data.name,
              data: this.data.data,
              // radius: this.radius ? ['50%', '75%'] : [0, '75%'],
              radius: this.radius ? this.specificLabel ? ['50%', '75%'] : ['23%', '43%'] : [0, '75%'],
              center:
                this.legendOrder === 'left' && this.title && !this.centerTitle
                  ? ['50%', '55%']
                  : ['50%', '55%'],
              top: this.specificLabel ? 5 : -50
            }
          ]
        }
        this.chart.setOption(this.option)

        this.chart.on('click', (param) => {
          this.$emit('click', param, this.summary)
        })

        this.chart.on('mousemove', this.onMousemove)
        this.chart.on('mouseout', this.onMouseout)
      })
    },
    onMousemove (event) {
      if (event.componentType === 'title') {
        this.handlerShowTooltip(event)
      } else {
        this.$emit('mousemove', event)
      }
    },
    onMouseout (event) {
      if (event.componentType === 'title') {
        this.handlerHideTooltip(event)
        this.$emit('mouseoutTitle', event)
      } else {
        this.$emit('mouseout', event)
      }
    },
    handlerShowTooltip (e) {
      if (!this.tooltipText) return
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const { clientX, clientY } = e.event.event
        this.style = {
          position: 'fixed',
          top: clientY + 'px',
          left: clientX + 4 + 'px'
        }
        if (!this.showTooltip) {
          this.showTooltip = true
        }
      }, 100)
    },
    handlerHideTooltip (e) {
      this.showTooltip = false
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
    }
  }
}
</script>
<style scoped>
.tooltip {
  background: #1f68be;
  color: #fff;
  z-index: 2176;
  border-radius: 4px;
  padding: 10px;
  z-index: 2000;
  font-size: 12px;
  line-height: 1.2;
  min-width: 10px;
  max-width: 150px;
  word-wrap: break-word;
  opacity: 0.85;
}
</style>
