<template >
  <!-- 每日币价K线 -->
  <div style="width: 100%; min-height: 700px">
    <!-- 对数线性显示切换 -->
    <el-row>
      <el-col>
        <!-- @handelSwitch="handelSwitch"     -->
         <el-button @click="handelLineSwitch"
         style="margin-left:100px;height:35px;border-radius:6px;"
         >{{ $t(`home.switch`)
          }}<span class="according"> {{ $t(switch3) }}</span></el-button
        >
      </el-col>
    </el-row>

    <div
      id="echartsBox"
      v-loading="ETHloading"
      style="width: 100%; min-height: 700px"
    ></div>
    <!-- margin-left: -80px -->
    <!-- <div
      id="echarts"
      v-loading="ETHloading"
      style="width: calc(100vw - 320px); height: 400px; margin-left: -80px"
    ></div> -->
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  handelKlineGraph,
  handelData,
  handelTotalData,
  handelClosePrice,
  resetTheChart,
  handelCapReal,
  handelLineType,
  handelSwitchs,
  handelWatermark
} from "../util/processingData";
export default {
  props: [`time`],
  data() {
    return {
      option: {
        title: {
          show: "false",
          text: "",
          top: 10,
          left: "center",
        },
        legend: {
          right: 100,
          itemWidth: 8,
          itemHeight: 9,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false,
            type: "cross",
            lineStyle: {
              color: "#376df4",
              width: 2,
              opacity: 0,
            },
            crossStyle: {
              //十字轴横线
              opacity: "0",
            },
          },
        },
        xAxis: {
          type: "time",
          data: [],
          axisLine: { lineStyle: { color: "#8392A5" } },
          axisLabel: {
            //  formatter (val,i){
            //     let year = val.split(`-`)[0]
            //     let month =val.split(`-`)[1]
            //     return `${year}-${month}`
            //  }
          },
        },
        yAxis: [
          {
            scale: true,
            axisLine: { lineStyle: { color: "#8392A5" } },
            splitLine: { show: false },
            type: "value",
          },
          {
            position: "right",
            type: "value",
            show: false,
          },
          {
            type: "value",
            // position: "right",
            // type: "log",
            // min: `dataMin`,
            // max: `dataMax`,
            show: false,
          },
        ],
        grid: {
          bottom: 80,
        },
        dataZoom: [
          {
            // textStyle: {
            //   color: "#8392A5",
            // },
            // handleIcon://滚动条两边可以加图片样式
            // dataBackground: {
            //   areaStyle: {
            //     color: "#8392A5",
            //   },
            //   lineStyle: {
            //     opacity: 0.8,
            //     color: "#8392A5",
            //   },
            // },
            type: "slider",
            start: 75,
            end: 100,
            maxSpan: 100,
            minSpan: 1,
            brushSelect: true,
          },
          {
            type: "inside",
            start: 0,
            end: 20,
            showDetail: false,
          },
        ],
        series: [
          {
            type: "candlestick",
            name: "Day",
            data: [],
            itemStyle: {
              color: "#FD1050",
              color0: "#0CF49B",
              borderColor: "#FD1050",
              borderColor0: "#0CF49B",
            },
          },
          {
            name: "close_price",
            type: "line",
            data: [],
            smooth: false,
            symbol: "circle",
            symbolSize: 5,
            showSymbol: false,
            itemStyle: {
              color: "#a829ee",
              borderColor: "rgba(221,220,107,0.1)",
              borderWidth: 12,
            },
            lineStyle: {
              color: "#a829ee",
              width: 1,
            },
          },
          {
            name: "Price[BTC]",
            type: "line",
            smooth: false, //线条是否圆滑
            symbol: "circle",
            symbolSize: 5,
            showSymbol: false,
            itemStyle: {
              color: "#000",
              borderColor: "rgba(221,220,107,0.1)",
              borderWidth: 12,
            },
            lineStyle: {
              //线条样式
              color: "#000",
              width: "1",
            },
            yAxisIndex: 1,
            data: [],
            //绘制右侧Y轴
            markLine: {
              symbol: ["none", "none"], //去掉箭头
              itemStyle: {
                
                normal: {
                  lineStyle: { type: "solid", color: "rgba(0,0,0,0.01)" },
                },
              },
              //  lineStyle:{
              //   opacity:0
              // },
              label: {
                formatter: "{b}",
                fontSize: 10,
                color: "rgba(0,0,0,0.8)",
                align: "left",
              },
              data: [
                // {
                //   name: "$0.40",
                //   yAxis: 0.4,
                // },
                // {
                //   name: "$0.80",
                //   yAxis: 0.8,
                // },
                // {
                //   name: "$2",
                //   yAxis: 2,
                // },
                // {
                //   name: "$6",
                //   yAxis: 6,
                // },
                // {
                //   name: "$10",
                //   yAxis: 10,
                // },
                // {
                //   name: "$40",
                //   yAxis: 40,
                // },
                // {
                //   name: "$80",
                //   yAxis: 80,
                // },
                // {
                //   name: "$200",
                //   yAxis: 200,
                // },
                {
                  name: "$600",
                  yAxis: 600,
                },
                {
                  name: "$1K",
                  yAxis: 1000,
                },
                {
                  name: "$4K",
                  yAxis: 4000,
                },
                {
                  name: "$8K",
                  yAxis: 8000,
                },
                {
                  name: "$20K",
                  yAxis: 20000,
                },
                {
                  name: "$60K",
                  yAxis: 60000,
                },
                {
                  name: "$100K",
                  yAxis: 100000,
                },
              ],
            },
          },
        
          // {
          //   name: "CapReal [USD]",
          //   type: "line",
          //   smooth: false, //线条是否圆滑
          //   symbol: "circle",
          //   symbolSize: 5,
          //   showSymbol: false,
          //   itemStyle: {
          //     color: "#fbc116",
          //     borderColor: "rgba(221,220,107,0.1)",
          //     borderWidth: 12,
          //   },
          //   lineStyle: {
          //     //线条样式
          //     color: "#fbc116",
          //     width: "1",
          //   },
          //   yAxisIndex: 2,
          //   data: [],
          // },
        ],
      },

      ETHloading: "false",
      parmesTime: {
        start: "",
        end: "",
      },
      show: "",
      params: {
        req: "OHLCPrice",
        radius: "BTC",
      },
      color: "#a829ee",
      priceParams: {
        req: "price",
        radius: "",
        start: "",
        end: "",
      },
      priceData: [],
      BTCbuttonShow: "",
      ETHbuttonShow: "",
      priceEthData: [],
      capRealData: [],
      switch3: "",
      oldY: null,
    };
  },
  mounted() {
    this.show = localStorage.getItem("currentTabComponent");
    this.params.radius = localStorage.getItem("radius");
    this.priceParams.radius = localStorage.getItem("radius");
    window.addEventListener("setItem", () => {
      let obj = localStorage.getItem("src");
      this.ETHloading = localStorage.getItem("ETHloading");
      this.show = localStorage.getItem("currentTabComponent");
      this.params.radius = localStorage.getItem("radius");
      // this.color = JSON.parse(obj).color;
      this.priceParams.radius = localStorage.getItem("radius");
      this.BTCbuttonShow = localStorage.getItem("BTCbutton");
      this.ETHbuttonShow = localStorage.getItem("ETHbutton");
    });

    //进入页面发起请求
    this.fetchOHL(this.params.req, this.params.radius);
  
    if (this.params.radius == "BTC") {
      this.fetchPrice(
        this.priceParams.req,
        this.priceParams.radius,
        this.parmesTime.start,
        this.parmesTime.end
      );
    } else {
      this.fetchPriceEth(this.parmesTime.start, this.parmesTime.end);
    }

    this.switch3 = handelSwitchs(this.option, this.switch3);
    this.oldY = this.option.yAxis;
  },
  watch: {
    //监听时间变化 按照时间渲染数据
    // parmesTime: {
    //   handler(val) {
    //     // this.option.xAxis.data.length = 0;
    //     this.option.series[0].data.length = 0;
    //     this.option.series[1].data.length = 0;

    //     if (val.start && this.show == "ETH") {
    //       this.fetchOHL(
    //         this.params.req,
    //         this.params.radius,
    //         this.parmesTime.start,
    //         this.parmesTime.end
    //       );

    //       //判断是否渲染了价格 渲染了再发起时间请求
    //       if (this.BTCbuttonShow == "true") {
    //         this.fetchPrice(
    //           this.priceParams.req,
    //           this.priceParams.radius,
    //           this.parmesTime.start,
    //           this.parmesTime.end
    //         );
    //       }

    //       if (this.ETHbuttonShow == "true") {
    //         this.fetchPriceEth(this.parmesTime.start, this.parmesTime.end);
    //       } else {
    //         return;
    //       }
    //     }
    //   },
    //   deep: true,
    //   immediate: true,
    // },

    //监听币种变化渲染
    params: {
      handler(val) {
        if (this.show == "ETH") {
          this.fetchOHL(this.params.req, val.radius);
        }
      },
      deep: true,
      immediate: true,
    },
    // //监听BTC按钮点击请求数据
    // BTCbuttonShow(val) {
    //   if (this.show == "ETH") {
    //     if (val == "true") {
    //       this.fetchPrice(
    //         this.priceParams.req,
    //         this.priceParams.radius,
    //         this.parmesTime.start,
    //         this.parmesTime.end
    //       );
    //     } else if (val == "false") {
    //       this.option.series[2].data.length = 0;

    //       this.initCharts();
    //     }
    //   }
    // },
    // //监听etH按钮点击请求数据
    // ETHbuttonShow(val) {
    //   if (this.show == "ETH") {
    //     if (val == "true") {
    //       this.fetchPriceEth(this.parmesTime.start, this.parmesTime.end);
    //     } else if (val == "false") {
    //       this.option.series[3].data.length = 0;
    //       this.initCharts();
    //     }
    //   }
    // },
  },

  methods: {
    initCharts() {
      this.myChart = echarts.init(document.getElementById("echartsBox"));
      this.myChart.clear();
      this.myChart.setOption(this.option);
      //  当窗口或者大小发生改变时执行resize，重新绘制图表
      window.addEventListener("resize", () => {
        if (this.myChart) this.myChart.resize();
      });
    },
    //请求OHLCPrice数据
    async fetchOHL(req, radius, start, end) {
      this.ETHloading = true;
        //添加水印
        this.option= handelWatermark(this.option)
      if (start && end) {
        const ndqaList = await this.$API.getPriceOHLC(req, radius, start, end);
        // const capReal = await this.$API.getCapReal(start, end);
        // this.capRealData = capReal.data.data;

        let data = ndqaList.data.data;
        this.option.series[0].data.length = 0;
        this.option.series[1].data.length = 0;
        // this.option.series[4].data.length = 0;
        this.option.xAxis.data.length = 0;
        //根据时间显示数据改变X轴
        this.option.xAxis.type = "category";
        data.forEach((item) => {
          //X轴数据处理
          let time = item.time.split("T")[0];
          this.option.xAxis.data.push(time);
          this.option.series[0].data.push([
            //series数据处理
            item.openPrice.toFxied(2),
            item.closePrice.toFxied(2),
            item.lowestPrice.toFxied(2),
            item.highestPrice.toFxied(2),
          ]);

          //收盘价处理渲染
          this.option.series[1].data.push(item.closePrice.toFxied(2));
        });
        //渲染新增capReal 另一个接口 需要找到日期在对应数据

        // this.capRealData.forEach((item) => {
        //   let time = item.time.split("T")[0];
        //   // let date = +new Date(time);
        //   this.option.series[4].data.push(item.capReal);
        // });
       

        this.option.dataZoom[0].start = 0;
        this.option.dataZoom[0].end = 100;
        this.option.dataZoom[0].minSpan = 1;
        if (ndqaList.data.msg == "按月返回数据") {
          this.option.title.show = true;
          this.option.title.text = "月数据";
        } else if (ndqaList.data.msg == "按周返回数据") {
          this.option.title.show = true;
          this.option.title.text = "周数据";
        }
        resetTheChart(this);

        this.initCharts();
      } else {
        const ndqaList = await this.$API.getPriceOHLC(req, radius);
        // const capReal = await this.$API.getCapReal();
        // this.capRealData = capReal.data.data;
        // this.capRealValueList = handelCapReal(this.capRealData);

        let data = ndqaList.data.data;
        this.option.xAxis.type = "time";
        this.option.series[0].data.length = 0;
        this.option.series[1].data.length = 0;
        // this.option.series[4].data.length = 0;
        this.option.series[0].data = handelKlineGraph(data);

        //收盘价处理渲染
        this.closePrice = handelClosePrice(data);
        // 收盘价处理成二维数组
        this.option.series[1].data = handelKlineGraph(data, this.closePrice);

        // this.option.series[4].data = handelKlineGraph(
        //   this.capRealData,
        //   this.capRealValueList
        // );
      }
      //判断币种不同颜色不同
      // if (this.params.radius != "BTC") {
      //   this.option.series[1].itemStyle.color = this.color;
      //   this.option.series[1].lineStyle.color = this.color;
      // } else {
      //   this.option.series[1].itemStyle.color = "#a829ee";
      //   this.option.series[1].lineStyle.color = "#a829ee";
      // }

      this.$forceUpdate();
      resetTheChart(this);
      this.initCharts();
      this.ETHloading = false;
    },

    //请求BTC价格
    async fetchPrice(req, radius, start, end) {
      this.ETHloading = true;
      this.option.xAxis.data.length = 0;
      this.option.series[2].data.length = 0;
      let screening = "ohlc";
      if (req && radius && !start) {
        const price = await this.$API.getActiveaddress(req, radius);
        this.priceData = price.data.data;
        this.option.xAxis.type = "time";
        this.priceValueList = handelData(this.priceData);

        this.option.series[2].data = handelTotalData(
          this.priceData,
          this.priceValueList
        );
      } else {
        const price = await this.$API.getActiveaddress(
          req,
          `${radius},${screening}`,
          start,
          end
        );
        this.priceData = price.data.data;
        this.option.xAxis.type = "category";
        this.option.series[2].data.length = 0;
        this.option.xAxis.data.length = 0;
        this.priceData.forEach((item) => {
          let time = item.time.split("T")[0];
          this.option.xAxis.data.push(time);
          this.option.series[2].data.push(item.value);
        });
      }
      resetTheChart(this);
        this.option.series[2].name = "Price[BTC]"
       this.option.series[2].itemStyle.color = "#000"
      this.option.series[2].lineStyle.color = "#000"
      this.initCharts();
      this.ETHloading = false;
    },

    //ETH价格
    async fetchPriceEth(start, end) {
      this.ETHloading = true;
      if (start && end) {
        const price = await this.$API.getActiveaddress(
          "price",
          "eth,ohlc",
          start,
          end
        );
        this.priceEthData = price.data.data;
        this.option.xAxis.type = "category";
        this.option.series[2].data.length = 0;
        this.option.xAxis.data.length = 0;
        this.priceEthData.forEach((item) => {
          let time = item.time.split("T")[0];
          this.option.xAxis.data.push(time);
          this.option.series[2].data.push(item.value.toFxied(2));
        });
      } else {
        this.option.series[2].data.length = 0;
        const price = await this.$API.getActiveaddress("price", "eth");
        this.priceEthData = price.data.data;
        this.option.xAxis.type = "time";
        this.priceEthValueList = handelData(this.priceEthData);
        this.option.series[2].data = handelTotalData(
          this.priceEthData,
          this.priceEthValueList
        );
      } 
      resetTheChart(this);
       this.option.series[2].name = "price[ETH]"
       this.option.series[2].itemStyle.color = "#627eea"
      this.option.series[2].lineStyle.color = "#627eea"
       
      this.initCharts();
      this.ETHloading = false;
    },
    //接收Home传的时间handelParmesTime
    handelSonTime(start, end) {
      this.parmesTime.start = start;
      this.parmesTime.end = end;
        this.fetchOHL(
            this.params.req,
            this.params.radius,
            this.parmesTime.start,
            this.parmesTime.end
          );
         if (this.params.radius == "BTC") {
      this.fetchPrice(
        this.priceParams.req,
        this.priceParams.radius,
        this.parmesTime.start,
        this.parmesTime.end
      );
    } else {
    
      this.fetchPriceEth(this.parmesTime.start, this.parmesTime.end);
    }
    },
    //点击对数/线性按钮切换
    handelLineSwitch() {
      this.option = handelLineType(this.option, this.oldY);
      this.switch3 = handelSwitchs(this.option, this.switch3);
      this.myChart.setOption(this.option);
    },
  },

  beforeDestroy() {
    /* 页面组件销毁的时候，移除绑定的监听resize事件，多渲染几次 容易导致内存泄漏和额外CPU或GPU占用*/
    window.removeEventListener("resize", () => {
      if (this.myChart) this.myChart.resize();
    });
  },
};
</script>

<style>
.a {
  margin: 0 auto;
}
</style>