<!--
 * @Descripttion: 
 * @version: 
 * @Author: langxue
 * @Date: 2022-04-07 10:50:31
 * @LastEditors: langxue
 * @LastEditTime: 2022-04-28 16:56:10
-->

<template>
  <div :id="id" :style="{ width, height }"></div>
</template>

<script>
const unwarp = (obj) => obj && (obj.__v_raw || obj.valueOf() || obj);

export default {
  name: "MetaPieChart",
  data() {
    return {
      chart: null,
      echarts: window.echarts,
    };
  },
  props: {
    id: {
      type: String,
      default: () => {
        return "pie_" + Date.now() + Math.random().toString(36).substr(2);
      },
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    // 图表数据
    series: {
      type: Array,
      default: () => {
        return [];
      },
      required: true,
    },
    // 图表类型 饼图:pie 环形 rang
    chartType: {
      type: String,
      default: "pie",
    },
    // 环形图的原型角度
    chartRadius: {
      type: Array,
      default: () => {
        return ["40%", "70%"];
      },
    },
    // 图表的标题
    chartTitle: {
      type: String,
      default: "",
    },
    // 图表的小标题
    chartSubTitle: {
      type: String,
      default: "",
    },
    // 图表位置
    chartCenter: {
      type: Array,
      default: () => {
        return ["35%", "50%"];
      },
    },
    // 图例位置 左侧：left 右侧：right 上侧：top 下侧：bottom
    legendPosition: {
      type: String,
      default: "right",
    },
    // 图例方向 竖直：vertical 水平：horizontal
    legendOrient: {
      type: String,
      default: "vertical",
    },
    // 图例类型 滚动：scroll 普通图例: plain
    legendType: {
      type: String,
      default: "scroll",
    },
    // 图例数据
    legendData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 是否显示图例 默认显示
    showLegend: {
      type: Boolean,
      default: true,
    },
    // 提示框组件自定义显示内容
    tooltip: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 图表自定义配置
    chartConfig: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    series: {
      deep: true,
      handler() {
        if (this.chart) {
          this.renderChart();
        } else {
          this.initChart();
        }
      },
    },
  },
  mounted() {
    this.addResizeEvent();
    this.initChart();
  },
  beforeUnmount() {
    this.removeResizeEvent();
    this.chart.off("click");
  },
  computed: {
    //   图表位置
    getChartCenter() {
      return this.chartCenter;
    },
    // 根据图表类型 渲染radius
    getChartRadiusByType() {
      let radius = "";
      if (this.chartType === "pie") {
        radius = "50%";
      }

      if (this.chartType === "range") {
        radius = this.chartRadius;
      }

      return radius;
    },
    //   图例的位置
    getLegendPosition() {
      let positon = {};
      switch (this.legendPosition) {
        case "left":
          positon = {
            top: "20%",
            left: 0,
            bottom: "20%",
          };
          break;
        case "right":
          positon = {
            top: "20%",
            right: 0,
            bottom: "20%",
          };
          break;
        case "top":
          positon = {
            top: 0,
          };
          break;
        case "bottom":
          positon = {
            bottom: 0,
          };
      }
      return positon;
    },
    // 图例的方向
    getLegendOrient() {
      return { orient: this.legendOrient };
    },
    // 图例类型
    getLegendType() {
      return { type: this.legendType };
    },
    // 图例数据
    getLegendData() {
      return { data: this.legendData };
    },
  },
  methods: {
    renderChart() {
      this.chart.setOption(this.setChartOptions(), true);
    },
    // 基于准备好的dom，初始化echarts实例
    initChart() {
      const dom = document.getElementById(this.id);
      this.chart = this.echarts.init(dom, null, { renderer: "svg" });
      unwarp(this.chart).setOption(this.setChartOptions());
      this.onClick();
    },
    // 添加窗口大小监听方法
    addResizeEvent() {
      const _this = this;
      window.addEventListener("resize", _this.handleResizeChart);
    },
    // 适应图表大小
    handleResizeChart() {
      this.chart && this.chart.resize();
    },
    // 移除窗口大小监听方法
    removeResizeEvent() {
      const _this = this;
      window.removeEventListener("resize", _this.handleResizeChart);
    },
    // 绑定鼠标点击事件
    onClick() {
      const _this = this;
      this.chart.on("click", (e) => {
        _this.$emit("handleClick", e);
      });
    },
    // 隐藏tooltip
    hideTooltip() {
      this.chart.dispatchAction({
          type: 'hideTip'
      })
    },
    // 显示tooltip
    /**
     * seriesIndex  系列的 index，在 tooltip 的 trigger 为 axis 的时候可选。
     * dataIndex 数据项的 index，如果不指定也可以通过 name 属性根据名称指定数据项
     * position  本次显示 tooltip 的位置。只在本次 action 中生效 缺省则使用 option 中定义的 tooltip 位置
     */
    showTooltip(seriesIndex=0, dataIndex=0, position) {
      this.hideTooltip();
      setTimeout(() => {
        this.chart.dispatchAction({
          type: 'showTip',
          seriesIndex,
          dataIndex,
          position
        })
      },  10)
      
    },
    // 如果要高亮系列：
    handleHighlight(seriesIndex = 0, dataIndex = 0) {
      this.downHighlight()
      setTimeout(() => {
        this.chart.dispatchAction({
          type: 'highlight',
          seriesIndex,
          dataIndex,
        });
      }, 10)
    },
    downHighlight() {
      this.chart.dispatchAction({
        type: 'downplay'
      })
    },
    // 设置 options
    setChartOptions() {
      const option = {
        title: {
          text: this.chartTitle,
          subtext: this.chartSubTitle,
          left: "center",
        },
        tooltip: {
          trigger: "item",
          confine: true,
          // alwaysShowContent: true,
          // position: ["25%", 10],
          className: 'echarts-tooltip',
          ...this.tooltip,
        },
        legend: {
          show: this.showLegend,
          ...this.getLegendType,
          ...this.getLegendOrient,
          ...this.getLegendPosition,
          ...this.getLegendData,
        },
        ...this.chartConfig,
        series: [
          {
            type: "pie",
            radius: this.getChartRadiusByType,
            center: this.getChartCenter,
            label: {
              show: false,
              position: "center",
            },
            data: this.series,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      return option;
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.echarts-tooltip) {
  z-index: 1 !important;
}
</style>
