<template>
  <base-chart
    :option="chartOption"
    class="pie-chart-wrap"
    :style="customChartStyle"
  />
</template>
<script>
import chartsMixins from "../../chartsMixins.js";
export default {
  name: "pie-chart",
  mixins: [chartsMixins],
  props: {
    customChartStyle: {
      default: "",
      type: String,
    },
    dataSource: {
      type: Array,
      default: () => {
        return [];
      },
    },
    pieChartName: {
      default: "",
      type: String,
    },
    titleText: {
      default: "",
    },
    title: {
      type: Object,
      default: () => ({}),
    },

    showLegend: {
      type: Boolean,
      default: true,
    },
    legend: {
      default: () => ({}),
      type: Object,
    },
    radius: {
      default: () => [60, 100],
    },
    decimals: {
      default: 0,
      type: Number,
    },
    showSeriesLabel: {
      default: false,
      type: Boolean,
    },
    seriesLabelFormatter: {
      type: Function,
    },
    showSeriesLabelPer: {
      default: true,
      type: Boolean,
    },
    colors: {
      default: () => [],
      type: Array,
    },
    tooltipFormatter: {
      type: Function,
    },
    tooltip: {
      default: () => ({}),
      type: Object,
    },
  },
  data() {
    return {};
  },
  methods: {
    getTotal() {
      const sumValue = this.dataSource.reduce((total, cur) => {
        const val = parseFloat(cur && cur.value);
        return isNaN(val) ? total : total + val;
      }, 0);
      if (sumValue >= 1000000000000) {
        return {
          value: this.toFormatMoney(sumValue / 1000000000000, 2),
          unit: "万亿",
        };
      } else if (sumValue >= 100000000000) {
        return {
          value: this.toFormatMoney(sumValue / 100000000000, 2),
          unit: "千亿",
        };
      } else if (sumValue >= 10000000000) {
        return {
          value: this.toFormatMoney(sumValue / 10000000000, 2),
          unit: "百亿",
        };
      } else if (sumValue >= 1000000000) {
        return {
          value: this.toFormatMoney(sumValue / 1000000000, 2),
          unit: "十亿",
        };
      } else if (sumValue >= 100000000) {
        return {
          value: this.toFormatMoney(sumValue / 100000000, 2),
          unit: "亿",
        };
      } else if (sumValue >= 10000000) {
        return {
          value: this.toFormatMoney(sumValue / 10000000, 2),
          unit: "千万",
        };
      } else if (sumValue >= 1000000) {
        return {
          value: this.toFormatMoney(sumValue / 1000000, 2),
          unit: "百万",
        };
      } else if (sumValue >= 100000) {
        return {
          value: this.toFormatMoney(sumValue / 100000, 2),
          unit: "十万",
        };
      } else if (sumValue >= 10000) {
        return { value: this.toFormatMoney(sumValue / 10000, 2), unit: "万" };
      } else {
        return {
          value: this.toFormatMoney(sumValue, this.decimals, ""),
          unit: "",
        };
      }
    },
    getPieColor() {
      if (
        this.colors?.every((cur) => typeof cur === "string") &&
        this.colors.length
      ) {
        return this.colors;
      } else {
        if (this.dataSource.length > 8 && this.dataSource.length % 9 === 0) {
          return [...this.getColorList(), ...this.getColorList().slice(1)];
        } else {
          return this.getColorList();
        }
      }
    },
    percentFilter(val, def = "--", needAbs) {
      let v = parseFloat(val);
      if (isNaN(v) || (!v && v !== 0)) return def;
      if (needAbs) {
        v = Math.abs(v);
      }
      return `${v.toFixed(2)}%`;
    },
  },
  computed: {
    chartOption() {
      const total = this.getTotal();
      const hasData = this.dataSource && this.dataSource.length;
      return {
        legend: {
          top: "bottom",
          selectedMode: false,
          itemWidth: 12,
          itemHeight: 12,
          show: this.showLegend && hasData,
          type: "scroll",
          borderWidth: 0,
          ...this.legend,
        },
        title: {
          left: "center",
          top: this.showLegend && hasData && this.titleText ? 100 : "center",
          padding: 0,
          show: true,
          text: `{value|${total.value}}{unit|${total.unit}}\n{name|${this.titleText}}`,
          textStyle: {
            rich: {
              value: {
                height: 32,
                fontSize: 24,
                color: "#303133",
                lineHeight: 32,
                marginBottom: 4,
                fontWeight: 700,
              },
              unit: {
                height: 32,
                fontSize: 14,
                color: "#303133",
                lineHeight: 32,
                marginBottom: 4,
                fontWeight: 700,
              },
              name: {
                height: 18,
                fontSize: 13,
                color: "#909399",
                lineHeight: 18,
                fontWeight: 400,
              },
            },
          },
          ...(hasData ? this.title : {}),
        },
        toolbox: {
          show: false,
        },
        tooltip: {
          show: hasData,
          borderColor: "transparent",
          formatter: (params) => {
            if (this.tooltipFormatter) {
              return this.tooltipFormatter(params);
            }
            return (
              `<div style="font-size:12px; ">` +
              (this.pieChartName
                ? `<div style="margin-bottom: 8px; margin-top:4px; line-height:14px;color: #303133;">${this.pieChartName}</div>`
                : "") +
              `<div style="${
                this.defaultStyle
              };position: relative;padding-left:10px;height: 16px;line-height:18px"><span><span style="position:absolute; left:0;bottom: 5px;;background:${
                params.color
              };margin-right: 4px;width: 5px;height:5px;border-radius:6px;"> </span><span style="margin-right:32px;color:#606266;">${
                params.name
              }</span></span><span style="color: #303133;">${this.toFormatMoney(
                params.value,
                this.decimals
              )}（${this.percentFilter(params.percent)}）</span></div>` +
              `</div>`
            );
          },
          backgroundColor: "rgba(255,255,255,0.95)",
          ...this.tooltip,
        },
        series: [
          {
            name: hasData ? this.pieChartName : "",
            type: "pie",
            radius: this.radius,
            center: [
              "50%",
              this.showLegend && hasData
                ? this.legend && this.legend.orient
                  ? "center"
                  : "45%"
                : "50%",
            ],
            itemStyle: {
              borderColor: "#fff",
              borderWidth: 1,
              opacity: 0.8,
            },
            label: {
              show: this.showSeriesLabel,
              formatter: (params) => {
                if (this.seriesLabelFormatter) {
                  return this.this.seriesLabelFormatter(params);
                }
                if (this.showSeriesLabelPer) {
                  return `{b|${params.name}}：{b|${this.percentFilter(
                    params.percent
                  )}}`;
                }
                return `{b|${params.name}}`;
              },
              rich: {
                a: {
                  fontSize: 18,
                  color: "#303133",
                },
                b: {
                  fontSize: 12,
                  color: "#606266",
                },
              },
            },
            emptyCircleStyle: {
              color: "#e6e6e6",
              opacity: 0.3,
            },
            data: this.dataSource,
          },
        ],
        color: this.getPieColor(),
      };
    },
  },
};
</script>
<style scoped lang="scss">
.pie-chart-wrap {
  height: 264px;
}
</style>
