<template>
  <div v-loading="PriceValueLoading">
    <el-row class="butBox">
      <el-col :span="2.5">
        <button class="theSorting" @click="handelAscending">{{$t(`home.ascending`)}}</button>
      </el-col>
      <el-col :span="2.5">
        <button class="theSorting" @click="handelDescending">{{$t(`home.descending`)}}</button>
      </el-col>
      <el-col :span="3" class="timeBoxS">
        <el-select
          v-model="value"
          filterable
          size="small"
          :placeholder="$t(`arh.pleaseInterval`)"
          @change="handelTimeInterval"
        >
          <el-option
            v-for="item in timeIntervalList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="3" class="takerTime">
        <!-- <div class="timeChooseBox"> -->
        <!-- @change="handelTime" -->
        <el-date-picker
          size="small"
          :picker-options="pickerOptions0"
          v-model="chooseTime"
          value-format="yyyy-MM-dd"
          @change="handelTime"
          type="daterange"
          :default-value="timeDefaultShow"
          range-separator="-"
          :start-placeholder="$t(`home.startDate`)"
          :end-placeholder="$t(`home.endDate`)"
          unlink-panels
          editables
          style="width: 99%"
          class="timeBox"
        >
        </el-date-picker>
        <!-- </div> -->
      </el-col>
      <el-col :span="1" class="takerBtn">
        <span class="btn" @click="handelTakerBtn">{{$t(`arh.search`)}}</span>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div id="PriceValue" style="width: 100%; min-height: 700px"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getDate } from "../util/processingData";
export default {
  data() {
    return {
      option: {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // Use axis to trigger tooltip
            type: "shadow", // 'shadow' as default; can also be 'line' or 'shadow'
          },
          formatter: function (value) {
            // console.log(value);
            let time;

            if (value[2]) {
              time = value[2].name;
            } else {
              return;
            }
            let marker = value[2].marker;
            let name = value[2].seriesName;
            let data = value[2].data;
            return `${time} <br />${marker} ${name} ${data} <br />  ${value[1].name}  <br /> ${value[1].marker} ${value[1].seriesName} ${value[1].data}`;
          },
        },
        // legend: {},
        grid: {
          top: "5%",
          left: "5%",
          right: "10%",
          bottom: "12%",
          // containLabel: true,
        },
        xAxis: [
          {
            type: "value",
            position: "top",
            data: [],
          },
          {
            // type: "value",
            position: "bottom",
            axisLabel: {
              formatter: function (value) {
                let hours = value.split(" ")[1].split(":")[0];
                let min = value.split(" ")[1].split(":")[1];
                return `${hours}:${min}`;
              },
            },
            data: [],
          },
        ],
        yAxis: [
          {
            show: true,
            //   type: "category",
            data: [],
            position: "left",
            axisLine: {
              onZero: false,
            },
          },
          {
            // type: "log",
            show: true,
            // data: [],
            position: "right",
            // min: 19000, //`dataMin`
            min: `dataMin`,
            max: `dataMax`,
            //  max: 21000,
            // interval: 500,
            axisLine: {
              onZero: false,
            },
          },
        ],

        dataZoom: [
          {
            show: true,
            type: "inside", //slider
            //  show:false,
            // minSpan: 10,
            //  orient: 'vertical',
            start: 0, //初始化时，滑动条宽度开始标度
            end: 100,
            left: "93%",
            yAxisIndex: [0],
            // handleSize: 0,
            // xAxisIndex: [1],
            minSpan: 10,
          },
          {
            // show: true,
            // show:false,
            type: "slider",
            yAxisIndex: [0],
            xAxisIndex: [1],
            start: 0, //初始化时，滑动条宽度开始标度
            end: 100,
          },
        ],

        series: [
          {
            //Y轴与柱子之间的间隔 此项数据无用 不显示 设置间隔
            name: "assist",
            type: "bar",
            stack: "1",
            itemStyle: {
              normal: {
                barBorderColor: "rgba(0,0,0,0)",
                color: "rgba(0,0,0,0)",
              },
              emphasis: {
                barBorderColor: "rgba(0,0,0,0)",
                color: "rgba(0,0,0,0)",
              },
            },
            tooltip: {
              trigger: "none",
            },
            data: [],
          },

          {
            name: "交易量",
            type: "bar",
            stack: "total",
            stack: "1",
            label: {
              show: true,
              fontSize: 10,
              color: "#000",
            },
            emphasis: {
              focus: "series",
            },
            itemStyle: {
              color: "#f58681",
            },
            data: [],
            xAxisIndex: 0,
            yAxisIndex: 0,
          },
          {
            name: "收盘价",
            type: "line",
            smooth: false, //线条是否圆滑
            symbol: "circle",
            symbolSize: 5,
            showSymbol: false,
            itemStyle: {
              color: "#888888",
              borderColor: "rgba(221,220,107,0.1)",
              borderWidth: 12,
            },
            lineStyle: {
              //线条样式
              color: "#888888",
              width: "1",
            },
            yAxisIndex: 1,
            xAxisIndex: 1,
            data: [],
            //绘制右侧Y轴
            // markLine: {
            //   symbol: ["none", "none"], //去掉箭头
            //   itemStyle: {
            //     normal: {
            //       lineStyle: { type: "solid", color: "rgba(0,0,0,0.01)" },
            //     },
            //   },
            //   // lineStyle:{
            //   //   color:"red"
            //   // },

            //   label: {
            //     formatter: "{b}",
            //     fontSize: 10,
            //     color: "rgba(0,0,0,0.8)",
            //     align: "left",
            //   },
            //   data: [
            //     {
            //       name: "10000",
            //       yAxis: 10000,
            //     },
            //     {
            //       name: "20000",
            //       yAxis: 20000,
            //     },
            //     {
            //       name: "30000",
            //       yAxis: 30000,
            //       // position: ['100%', '50'],
            //     },
            //     {
            //       name: "40000",
            //       yAxis: 40000,
            //     },
            //     {
            //       name: "50000",
            //       yAxis: 50000,
            //     },
            //     {
            //       name: "60000",
            //       yAxis: 60000,
            //     },
            //     {
            //       name: "70000",
            //       yAxis: 70000,
            //     },
            //   ],
            // },
          },
        ],
      },

      params: {
        start: "2022-8-15",
        end: "2022-8-16",
        interval: "1m",
      },
      PriceValueLoading: false,
      componentReq: "",
      introduce: "",
      arr: [],
      order: true, //true 是升序 false是降序
      orderData: [],
      lineData: [],
      value: "",
      timeIntervalList: [
        {
          value: "1m",
          label: "1分钟",
        },
        {
          value: "3m",
          label: "3分钟",
        },
        {
          value: "5m",
          label: "5分钟",
        },
        {
          value: "15m",
          label: "15分钟",
        },
        {
          value: "30m",
          label: "30分钟",
        },
        {
          value: "1h",
          label: "1小时",
        },
        {
          value: "2h",
          label: "2小时",
        },
        {
          value: "4h",
          label: "4小时",
        },
        {
          value: "6h",
          label: "6小时",
        },
        {
          value: "1d",
          label: "1天",
        },
      ],
      //限制开始时间必须是2022-09-01之后的
      pickerOptions0: {
        disabledDate: (time) => {
          // if (this.pickerMinDate) {

          //     let limitStart = new Date("2022-09-01").getTime()

          //     return time.getTime() > limitStart
          // }
          let limitStart = new Date("2022-09-01").getTime();

          return time.getTime() < limitStart;

          // return time.getTime() > Date.now();
        },
      },
      chooseTime: [],
      timeDefaultShow: "", //时间框显示范围
    };
  },
  // watch: {
  //   params: {
  //     handler() {
  //       if (this.componentReq == "priceValue") {
  //         this.fetchPriceValue(
  //           this.params.interval,
  //           this.params.start,
  //           this.params.end
  //         );
  //       }
  //     },
  //     deep: true,
  //   },
  // },
  mounted() {
    //不显示父级时间
     this.$addStorageEvent(1, "timeShow", false);
    //控制时间选择器 显示本月和上月
    this.timeDefaultShow = new Date();
    this.timeDefaultShow.setMonth(new Date().getMonth() - 1);
    //默认渲染两天的数据
    this.params.start = getDate("day", -1);
    this.params.end = getDate();

    let menuObj = localStorage.getItem("params");
    this.componentReq = JSON.parse(menuObj).componentReq;
    this.introduce = JSON.parse(menuObj).introduce;
    //监听localstorage变化
    window.addEventListener("setItem", () => {
      let menuObj = localStorage.getItem("params");
      this.componentReq = JSON.parse(menuObj).componentReq;
      this.introduce = JSON.parse(menuObj).introduce;
    });
    window.addEventListener("resize", () => {
      if (this.myChart)this.myChart.resize();
    });

    this.fetchPriceValue(
      this.params.interval,
      this.params.start,
      this.params.end
    );
  },
  methods: {
    //初始化柱状图图表
    inCharts() {
      this.myChart = echarts.init(document.getElementById("PriceValue"));
      this.myChart.setOption(this.option);
    },

    async fetchPriceValue(interval, start, end) {
      this.PriceValueLoading = true;
      const { data } = await this.$API.getPriceValue(interval, start, end);
      //折线图数据渲染
      let timeStart = start.split(" ")[0];
      let timeEnd = end.split(" ")[0];
      const lineData = await this.$API.getPriceValueLine(timeStart, timeEnd);
      this.lineData = lineData.data.data;
      this.option.series[2].data.length = 0;
      this.option.xAxis[1].data.length = 0;
      this.lineData.forEach((item) => {
        let year = item.openTime.split("T")[0];
        let hours = item.openTime.split("T")[1].split(".")[0];
        let date = `${year} ${hours}`;
        this.option.xAxis[1].data.push(date);
        this.option.series[2].data.push(item.closePrice);
      });
      //柱状图数据渲染
      this.priceData = data.data.data;

      this.option.yAxis[0].data.length = 0;
      this.option.series[1].data.length = 0;
      this.option.series[0].data.length = 0;
      this.arr.length = 0;
      this.priceData.forEach((item) => {
        this.arr.push([item.price, item.volume]);
      });

      //判断点击降序升序
      if (!this.order) {
        this.orderData = this.arrays(this.arr, false);
      } else {
        this.orderData = this.arrays(this.arr, true);
      }
      // console.log(this.orderData, 9999);

      this.orderData.forEach((item) => {
        this.option.yAxis[0].data.push(Math.trunc(item[0]));
        this.option.series[1].data.push(item[1]);
        this.option.series[0].data.push(20); //Y轴与柱子之间的间隔
      });

      this.inCharts();
      this.PriceValueLoading = false;
    },
    //点击升序
    handelAscending() {
      this.order = true;
      this.fetchPriceValue(
        this.params.interval,
        this.params.start,
        this.params.end
      );
    },
    //点击降序Descending
    handelDescending() {
      this.order = false;
      this.fetchPriceValue(
        this.params.interval,
        this.params.start,
        this.params.end
      );
    },
    //父级时间
    handelSonTime(start, end) {
      if (start) {
        this.params.start = start;
        this.params.end = end;
      } else {
        this.params.start = getDate("day", -1);
        this.params.end = getDate();
      }
      this.fetchPriceValue(
        this.params.interval,
        this.params.start,
        this.params.end
      );
    },
    //选择下拉框
    handelTimeInterval(value) {
     
      this.params.interval = value;
      // this.fetchPriceValue(
      //   this.params.interval,
      //   this.params.start,
      //   this.params.end
      // );
      this.timeInterval = value;
    },
    //根据数据大小排序
    Sort(arr, index) {
      //参数arr代表数组，index代表数组元素下标
      arr[index][0] += arr[index + 1][0]; //a+=b;
      arr[index + 1][0] = arr[index][0] - arr[index + 1][0]; // b = a - b;
      arr[index][0] -= arr[index + 1][0]; //a -= b;
    },
    //排序函数
    arrays(arr, asc) {
      //参数arr代表数组，sac为设置升降序
      for (var i = 1; i < arr.length; i++) {
        for (var k = 0; k < arr.length - 1; k++) {
          if (asc) {
            //如果asc为true则通过，否则则不通过

            if (arr[k][0] > arr[k + 1][0]) {
              this.Sort(arr, k); //在这里调用两值互换函数
            }
          } else {
            if (arr[k][0] < arr[k + 1][0]) {
              this.Sort(arr, k); //在这里调用两值互换函数
            }
          }
        }
      }
      return arr;
    },
    //根据时间排序
    dateSort(arr) {
      let newArr = [...arr];

      let temp = newArr.sort(function (obj1, obj2) {
        let a = new Date(obj1.date) / 1000;
        let b = new Date(obj2.date) / 1000;

        return a - b;
      });

      return temp;
    },
    //选择时间
    handelTime() {
      if (this.chooseTime) {
        this.params.start = this.chooseTime[0];
        this.params.end = this.chooseTime[1];
      } else {
        this.params.start = getDate("day", -1);
        this.params.end = getDate();
      }
      this.fetchPriceValue(this.value, this.params.start, this.params.end);
    },
    //点击搜索
    handelTakerBtn(){
      this.fetchPriceValue(this.value, this.params.start, this.params.end);
    }
  },
};
</script>

<style lang="scss" scoped>
.butBox {
  /* outline: 1px solid  red; */
  padding: 10px 20px;
  /* padding-left: 10px; */
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.theSorting {
  width: 50px;
  height: 30px;
  border: 1px solid rgba(0, 0, 0, 0.4);
  border-radius: 4px;
  margin-left: 10px;
  background: #fff;
}
.theSorting:hover {
  background: rgba(255, 231, 147, 0.1);
  color: gray;
}
.timeBoxS {
  margin-left: 20px;
}
.takerTime {
  // outline:  1px solid red;
  margin-left: 10px;
  padding-top: 2px;
}
// .timeChooseBox{
//   // outline:  1px solid red;
// }
.takerBtn {
  // outline: 1px solid red;
  // padding: 7px 0px;
  height: 0px;
  margin-left: 5px;
  .btn {
    display: inline-block;
    // outline: 1px solid red;
    line-height: 28px;
    font-size: 14px;
    width: 80%;
    text-align: center;
    outline: 1px solid rgba(0, 0, 0, 0.3);
    border-radius: 4px;
    font-size: 12px;
    padding: 0px 10px;
    
  }
  .btn:hover {
    background: rgba(255, 231, 147, 0.1);
  }
}
</style>
<style >
.timeBoxS .el-input__inner {
  height: 30px !important;
  color: rgba(0, 0, 0, 0.5) !important;
}
.el-range-editor--small.el-input__inner {
  height: 30px;
}
</style>