<template>
  <div :id="id" style="width:100%;height:100%;"></div>
</template>

<script>
import * as echarts from 'echarts';
import { stringify } from "querystring";
import { on, off } from '@/libs/tools'
export default {
  props: {
    id: String,
    EchartsData: {},
    histogram: Boolean,
    title: String,
    compound: Boolean,
    bar: Boolean,
    compoundBartype: String
  },
  data() {
    return {
      Charts: null,
      option: {
        title: {
          text: "",
          // top: "15",
          left: "5%",
          padding: 0,
          textStyle: {
            color: "#000",
            fontStyle: "normal",
            fontSize: 14,
            fontWeight: 540
          }
        },
        color: [],
        tooltip: {
          trigger: "axis",
          backgroundColor: "#fff",
          textStyle: {
            color: "#333333"
          },
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
            shadowStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(5,61,120,0.5)" // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(24,61,133,0.5)" // 100% 处的颜色
                  }
                ],
                global: false // 缺省为 false
              }
            }
          },
          extraCssText: "box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);",
          confine: true
        },
        legend: {
          show: false,
          data: [],
          top: 12,
          textStyle: {
            color: "white"
          },
          itemWidth: 12,
          itemHeight: 10
        },
        grid: {
          left: "5%",
          top: "10%",
          bottom: "5%",
          right: "5%",
          z: 22,
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            axisTick: {
              show: true
            },
            axisLine: {
              lineStyle: {
                color: "#1056A0"
              }
            },
            triggerEvent: "true",
            data: [],
            splitLine: { show: false },
            axisLabel: {
              show: true,
              interval: 0,
              rotate: 0,
              textStyle: {
                color: "#606264",
                fontSize: 12
              }
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            barWidth: 10,
            // splitNumber: 5,
            splitLine: {
              show: false
            },
            name: "",
            show: true,
            nameTextStyle: {
              show: true
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: "#606264"
              }
            },
            axisTick: {
              //决定是否显示坐标刻度
              alignWithLabel: true,
              show: true
            },
            axisLine: {
              show: true
            }
          }
        ],
        series: []
      }
    };
  },
  methods: {
    initEchart(response) {
      let xTitle = response.xtitle;
      let data = response.data;
      //直方图 
      if (this.histogram) {
        let newData = this.exchangeData(data, xTitle);
        this.option.series = [];
        let totalWid =
          Math.floor(document.getElementById(this.id).clientWidth * 0.85);

        this.option.series = [
          {
            name: "",
            type: "bar",
            data: newData,
            barWidth: totalWid / xTitle.length,
            itemStyle: {
              color: "#D14A61"
            }
          }
        ];
        this.option.xAxis[0].data = xTitle;
      }
      //复式柱图
      if (this.compound) {
        //设置颜色
        let colorList = ["#3DE2B0", "#699EFF", "#D14A61", "#FFC700", "#FB775D"];
        if (this.compoundBartype == "1") {
          this.option.xAxis[0].data = xTitle;
          //获取分组
          let mData = [];
          let obj = Object.values(data[0])[0];
          for (let i in obj) {
            mData.push(i);
          }
          //组装数据
          let newShowarr = [];
          mData.forEach((items, index) => {
            newShowarr[index] = [];
            data.forEach(ite => {
              newShowarr[index].push(
                Object.values(Object.values(ite)[0][items])[0]
              );
            });
          });
          //组成
          this.option.series = [];
          newShowarr.forEach((items, index) => {
            this.option.series.push({
              name: mData[index],
              type: "bar",
              data: items,
              itemStyle: {
                color: colorList[index]
              }
            });
          });
          //   this.option.legend.show=true
          //   this.option.legend.data = mData;
        } else if ((this.compoundBartype = "2")) {
          //提取x轴
          let newXarr = [];
          xTitle.forEach(items => {
            newXarr.push(items.split("::")[0]);
          });
          let showXtitle = this.removeRepeatForArr(newXarr);
          this.option.xAxis[0].data = showXtitle;
          //提取分组
          let newMarr = [];
          xTitle.forEach(items => {
            newMarr.push(items.split("::")[1]);
          });
          let showMdata = this.removeRepeatForArr(newMarr);
          //组装数据
          let newShowData = [];
          showMdata.forEach((items, index) => {
            newShowData[index] = [];
            data.forEach(ite => {
              if (Object.keys(ite)[0].split("::")[1] == items) {
                newShowData[index].push(
                  Object.values(Object.values(ite)[0])[0]
                );
              }
            });
          });
          //组装series
          this.option.series = [];
          newShowData.forEach((items, index) => {
            this.option.series.push({
              name: showMdata[index],
              type: "bar",
              data: items,
              barGap: '20%',
              barWidth: 20,
              itemStyle: {
                color: colorList[index]
              }
            });
          });
          let that = this;
          this.option.tooltip.formatter = function (param) {
            let sr = "";
            sr = param[0].axisValueLabel + '<br/>';
            param.forEach(items => {
              sr +=
                items.seriesName + ":" + that.scieData(items.value) + "<br/>";
            });
            return sr;
          };
        }
      }
      //柱状图
      if (this.bar) {
        let xTitle = []
        let showData = [];
        data.forEach((items, index) => {
          showData.push(items.value);
          xTitle.push(items.label)
        });
        this.option.series = [];
        this.option.series = [
          {
            name: "",
            type: "bar",
            data: showData,
            barWidth: '60%',
            itemStyle: {
              normal: {
                barBorderRadius: 5,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#956FD4" },
                  { offset: 1, color: "#3EACE5" }
                ])
              }
            }
          }
        ];
        this.option.xAxis[0].data = xTitle;
      }

      this.option.title.text = this.title;
      var chartsDiv = document.getElementById(this.id);
      this.Charts = echarts.init(chartsDiv);
      this.Charts.setOption(this.option);
      on(window, 'resize', this.Charts.resize)
    },
    //小于1 的转科学计数法
    scieData(number) {
      let newNumber = 0;
      if (number < 1) {
        let len = (number + "").split(".")[1].length;
        let str = (number + "").split(".")[1];
        let arr = (number + "").split(".")[1].split("");
        let unzero = [];
        arr.forEach((items, index) => {
          if (items != 0) {
            unzero.push(index);
          }
        });
        let p = unzero[0] + 1;
        let ne = str.substr(3, len);
        let neLe = ne.split("").length;
        newNumber = ne.substr(0, 1) + "." + ne.substr(1, neLe) + " e-" + p;
      } else {
        newNumber = number;
      }
      return newNumber;
    },
    //转数据格式
    exchangeData(data, xTitle) {
      let newData = [];
      //直方图的数据格式转换
      if (this.histogram) {
        xTitle.forEach((items, index) => {
          newData.push(Object.values(data[index][items])[0]);
        });
      }

      return newData;
    },
    //数据去重
    removeRepeatForArr(arr) {
      return arr.filter((item, index) => {
        return arr.indexOf(item) === index;
      });
    }
  },
  mounted() { },
  watch: {
    EchartsData(newValue, oldValue) {
      this.initEchart(newValue);
    }
  },
  beforeDestroy() {
    off(window, 'resize', this.Charts.resize)
  }
};
</script>
