<template>
  <div class="new-bar-single">
    <div :id="index" class="base">动态排序柱状图</div>
    <div
      class="zuan"
      v-show="config.zuanFlag && config.zuanLevel > 0"
      :style="`color:${option.zuanFontColor}`"
    >
      <i
        class="el-icon-back"
        @click="onZuanBack"
        style="cursor: pointer; margin-right: 10px"
      >
      </i>
      {{ config.zuanStack.join(` ${option.zuanFenge} `) }}
    </div>
  </div>
</template>
<script>
import {
  countLabel,
  grid,
  legend,
  title,
  countLegendSelect,
  countXlabel,
} from "../../newStyles/styleCommon";
export default {
  name: "new-bar-race",
  props: ["option", "config", "modalSet", "index", "site"],
  data() {
    return {
      originData: [],
      chartOption: {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
        },
        legend: { data: [] },
        grid: {
          top: "10%",
          bottom: "10%",
          left: "10%",
          right: "10%",
        },
        xAxis: {
          max: "dataMax",
          axisLabel: {
            formatter: function (n) {
              return Math.round(n) + "";
            },
          },
        },
        yAxis: {
          type: "category",
          data: [],
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
        },
        series: [],
        animationDuration: 3000,
        animationDurationUpdate: 3000,
        animationEasing: "linear",
        animationEasingUpdate: "linear",
      },
      chart: null,
    };
  },
  watch: {
    site: {
      handler() {
        if (this.chart) {
          this.chart.resize();
        }
      },
      deep: true,
    },
    option: {
      handler() {
        if (this.originData.length) {
          this.refresh();
        }
      },
      deep: true,
    },
  },
  methods: {
    handleClick(event) {
      if (this.config.zuanLevel + 1 >= this.config.zuan.length) {
        return this.$message({
          type: "warning",
          message: "已经钻取到最后一层了",
        });
      }
      let key = this.modalSet.find((i) => i.zuan).key;
      let index = this.config[key].findIndex((i) => i.zuan);
      this.config.zuanStack.push(event.data.name[index]);
      this.config.zuanLevel += 1;
      this.$emit("preview");
    },
    onZuanBack() {
      if (this.config.zuanLevel <= 0) return;
      this.config.zuanLevel -= 1;
      this.config.zuanStack = this.config.zuanStack.slice(
        0,
        this.config.zuanLevel
      );
      this.$emit("preview");
    },
    refresh() {
      if (this.config.serie.length) {
        this.refreshSingle();
      } else {
        this.refreshNormal();
      }
    },
    refreshNormal() {
      let { dimension, measure } = this.config;
      dimension = [...dimension].filter((i) => !i.extJson.hidden);
      measure = measure.filter((i) => !i.extJson.hidden);
      if (this.config.zuanFlag) {
        let zuanField = this.config.zuan[this.config.zuanLevel];
        let zuanIndex = dimension.findIndex((i) => i.zuan);
        dimension.splice(zuanIndex, 1, zuanField);
      }
      let { barWidth, barSwitchBg, barBgColor, barBorderRadius } = this.option;
      this.chartOption.grid = grid(this.option);
      if (this.option.isTitleShow) {
        this.chartOption.title = title(this.option);
      }
      this.chartOption.legend = legend(this.option);
      let clearData = this.originData.map((i) => {
        let item = { key: [], value: [] };
        dimension.reduce((r, d) => {
          r.key.push(i[d.columnTitle]);
          return r;
        }, item);
        measure.reduce((r, d) => {
          r.value.push(parseFloat(i[d.columnTitle] || 0));
          return r;
        }, item);
        return item;
      });
      let chartOption = { ...this.chartOption };
      let xAxisData = clearData.map((i) => i.key);
      chartOption.yAxis.data = xAxisData.map((i) => i.join("-"));
      let legengData = [];
      let seriesLabel = countLabel(this.option);
      chartOption.series = measure.map((m, i) => {
        legengData.push(m.columnTitle);
        let serie = {
          name: m.columnTitle,
          type: "bar",
          barWidth,
          data: clearData.map((d, index) => ({
            value: d.value[i],
            name: xAxisData[index],
          })),
          label: seriesLabel,
          itemStyle: { borderRadius: parseInt(barBorderRadius) },
        };
        if (barSwitchBg) {
          serie.showBackground = true;
          serie.backgroundStyle = { color: barBgColor };
        }
        return serie;
      });
      chartOption.legend.data = legengData;
      this.setYlabel(chartOption);
      this.setSerieColor(chartOption);
      countLegendSelect(this.option, chartOption);
      this.chart = echarts.init(document.getElementById(this.index));
      this.chart.off("click", this.handleClick);
      if (this.config.zuanFlag) {
        this.chart.on("click", this.handleClick);
      }
      this.chart.setOption(chartOption, true);
    },
    refreshSingle() {
      let { dimension, measure, serie } = this.config;
      dimension = [...dimension].filter((i) => !i.extJson.hidden);
      measure = measure.filter((i) => !i.extJson.hidden);
      serie = serie.filter((i) => !i.extJson.hidden);
      if (this.config.zuanFlag) {
        let zuanField = this.config.zuan[this.config.zuanLevel];
        let zuanIndex = dimension.findIndex((i) => i.zuan);
        dimension.splice(zuanIndex, 1, zuanField);
      }
      let { barWidth, barSwitchBg, barBgColor, barBorderRadius, stackSwitch } =
        this.option;

      //独立分类
      let originData = this.originData;
      if (this.option.isTitleShow) {
        this.chartOption.title = title(this.option);
      }
      this.chartOption.legend = legend(this.option);
      let xAxisData = [];
      let legendData = [];
      let valueKey = measure[0].columnTitle;
      let serieKey = serie[0].columnTitle;
      let clearData = this.originData.map((i) => {
        let item = { key: "", value: "", label: "" };
        let keyArr = dimension.map((d) => i[d.columnTitle]);
        let key = keyArr.join("-");
        item.keyArr = keyArr;
        item.key = key;
        if (!xAxisData.includes(key)) {
          xAxisData.push(key);
        }
        item.value = i[valueKey];
        item.label = i[serieKey];
        return item;
      });
      let years = [];
      for (let i = 0; i < originData.length; ++i) {
        if (
          years.length === 0 ||
          years[years.length - 1] !== originData[i][serie[0].columnTitle]
        ) {
          years.push(originData[i][serie[0].columnTitle]);
        }
      }
      years = Array.from(new Set(years));
      //取第一个year
      let startIndex = 0;
      let startYear = years[startIndex];

      let chartOption = { ...this.chartOption };
      chartOption.yAxis.data = xAxisData;
      XEUtils.remove(
        chartOption.yAxis.data,
        (item) => item === dimension[0].columnTitle
      );
      legendData.push(years[0]);

      let seriesLabel = countLabel(this.option);
      let data = clearData.filter((d) => {
        return d.label === startYear;
      });
      XEUtils.remove(data, (item) => item === startYear);
      chartOption.series = legendData.map((name) => {
        let serieItem = {
          name,
          realtimeSort: true,
          seriesLayoutBy: "column",
          data: XEUtils.map(data, (item) => item.value),
          type: "bar",
          barWidth,
          label: seriesLabel,
        };
        if (barSwitchBg) {
          serieItem.showBackground = true;
          serieItem.backgroundStyle = { color: barBgColor };
        }
        if (stackSwitch) {
          serieItem.areaStyle = {};
        }
        return serieItem;
      });
      if (stackSwitch) {
        chartOption.series.forEach((item) => (item.stack = "stack"));
      }
      chartOption.legend.data = legendData;
      this.setYlabel(chartOption);
      this.setSerieColor(chartOption);
      countLegendSelect(this.option, chartOption);
      if (this.option.barRaceType === "1") {
        chartOption.graphic = {
          elements: [
            {
              type: "text",
              right: 160,
              bottom: 60,
              style: {
                text: startYear,
                font: `bolder ${
                  this.option.graphicStyleFontSize || 80
                }px monospace`,
                fill: `${
                  this.option.graphicStyleFontColor ||
                  "rgba(100, 100, 100, 0.25)"
                }`,
              },
              z: 100,
            },
          ],
        };
      }
      if (this.option.barRaceType === "2") {
        chartOption.grid.bottom = "20%";
        chartOption.timeline = {
          axisType: "category",
          // realtime: false,
          // loop: false,
          autoPlay: true,
          // currentIndex: 2,
          playInterval: 3000,
          // controlStyle: {
          //     position: 'left'
          // },
          data: years,
          label: {
            formatter: function (s) {
              // return new Date(s).getFullYear();
            },
          },
        };
      }
      this.chartOption = chartOption;
      this.chart = echarts.init(document.getElementById(this.index));
      this.chart.off("click", this.handleClick);
      if (this.config.zuanFlag) {
        this.chart.on("click", this.handleClick);
      }
      this.chart.setOption(chartOption, true);
      if (this.option.barRaceType === "1") {
        let that = this;
        for (let i = startIndex; i < years.length - 1; ++i) {
          (function (i) {
            setTimeout(function () {
              that.updateYear(years[i + 1], serie, clearData);
            }, (i - startIndex) * 3000);
          })(i);
        }
      }
    },
    async updateYear(year, serie, clearData) {
      let source = clearData.filter((d) => {
        return d.label === year;
      });
      XEUtils.remove(source, (item) => item === year);
      console.log(source);
      this.chartOption.series[0].data = source;
      this.chartOption.graphic.elements[0].style.text = year;
      this.chart.setOption(this.chartOption);
      // let imgRes = await this.saveBg();
      // this.files.push(imgRes);
    },
    // y轴设置
    setYlabel(chartOption) {
      chartOption.yAxis.max = this.option.barRaceMax || 10;
      chartOption.yAxis.axisLabel = countXlabel(this.option);
    },
    // 设置系列颜色
    setSerieColor(chartOption) {
      let list = this.option.colorList.slice(0, chartOption.series.length);
      list.forEach(({ color1, color2, direction }, index) => {
        direction = direction || "top";
        if (color1 && color2) {
          chartOption.series[index].itemStyle.color = {
            x: direction == "left" ? 1 : 0,
            y: direction == "top" ? 1 : 0,
            x2: direction == "right" ? 1 : 0,
            y2: direction == "bottom" ? 1 : 0,
            colorStops: [
              { offset: 0, color: color1 },
              { offset: 1, color: color2 },
            ],
          };
        } else if (color1 && !color2) {
          chartOption.series[index].itemStyle.color = color1;
        }
      });
    },
    update(data) {
      this.originData = data;
      this.refresh();
    },
    initRender() {
      let option = {
        tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },
        legend: {},
        grid: { left: "3%", right: "3%", bottom: "3%", containLabel: true },
        xAxis: {
          max: "dataMax",
        },
        yAxis: {
          type: "category",
          realtimeSort: true,
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          data: ["老年", "青年", "少年", "中年"],
          axisLabel: {
            fontSize: 12,
            color: "#333333",
            interval: "0",
            rotate: 0,
          },
        },
        series: [
          {
            realtimeSort: true,
            name: "大",
            data: [
              { value: 2614, name: ["老年"] },
              { value: 5480, name: ["青年"] },
              { value: 2771, name: ["少年"] },
              { value: 2578, name: ["中年"] },
            ],
            type: "bar",
            barWidth: 20,
            label: {
              show: true,
              color: "#333333",
              fontSize: 12,
              position: "right",
              textBorderWidth: 0,
              textBorderColor: "#ffffff",
              rotate: 0,
              valueAnimation: true,
            },
            itemStyle: { borderRadius: 0 },
            areaStyle: {},
            stack: "stack",
          },
        ],
        animationDuration: 3000,
        animationDurationUpdate: 3000,
        animationEasing: "linear",
        animationEasingUpdate: "linear",
      };
      this.chart = echarts.init(document.getElementById(this.index));
      this.chart.setOption(option, true);
      this.$nextTick(this.chart.resize);
    },
  },
};
</script>
<style lang="scss">
.new-bar-single {
  .base {
    width: 100%;
    height: calc(100% - 20px);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .zuan {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    line-height: 20px;
    padding: 0 10px;
    font-size: 12px;
  }
}
</style>
