import * as echarts from "echarts";
import { exchangeRate,exchangeRateChart } from "../../api/pages"
import { chartsWidth, emptyData, handelLineType,handelProfitrate, handelZoom, handelWatermark, handelSwitchs, fetchBtcPrice, fetchEthPrice, handelSmaData, getDateArray } from "../../util/processingData"

export default {
    data() {
        return {
            exchangeRateLoading: false,           
            option: {
                tooltip: {
                    trigger: "axis",
                    //解决tooltip显示不全问题1 
                    confine: true,

                    // formatter: function (params) {
                    //     var res = params[0].axisValueLabel;

                    //     for (let i = 0; i < params.length; i++) {
                    //         res += `</br>${params[i].marker} ${params[i].seriesName} &nbsp&nbsp&nbsp&nbsp <span style="font-weight: bold">$${params[i].value} </span>`


                    //     }


                    //     return res;
                    // },

                },
                legend: {
                    right: "100",
                    top:"10",

                    
                },
                xAxis: {
                    // type: "time",
                    boundaryGap: false,
                    //   axisLabel: {
                    //     formatter: `{yyyy}-{MM}-{dd}`,
                    //   },
                    data: []
                },
                yAxis: [
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        axisLabel: {
                            formatter: function (e) {

                                let value;
                                if (e > 100000000) {
                                    value = `${e / 100000000}E`;
                                } else if (e > 1000000) {//百万
                                    value = `${e / 1000000}M`;
                                } else if (e >= 10000) {//万
                                    value = `${e / 10000}W`;
                                } else if (e < -1000000) {//百万
                                    value = `${e / 1000000}M`;
                                } else if (e < -10000) {//万
                                    value = `${e / 10000}W`;
                                }
                                else {
                                    value = e;
                                }
                                return value;
                            },
                        },
                        min: "dataMin",
                        max: "dataMax",
                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        show: true,
                        min: "dataMin",
                        max: "dataMax",
                        position: "right"
                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        min: "dataMin",
                        max: "dataMax",
                        show: false,
                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        min: "dataMin",
                        max: "dataMax",
                        show: false,
                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        min: "dataMin",
                        max: "dataMax",
                        show: false,
                    },
                ],
                dataZoom: [
                    {
                        type: "inside",
                        start: 0,
                        end: 100,
                    },
                    {
                        start: 0,
                        end: 100,
                    },
                ],
                series: [
                    {
                        name: "ExchangeRate",
                        type: "line",
                        smooth: false,
                        symbol: "circle",
                        showSymbol: false,
                        symbolSize: 5,
                        // areaStyle: {},
                        itemStyle: {
                            color: "#f7864c",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        yAxisIndex: 0,
                        lineStyle: {
                            //线条样式
                            color: "#f7864c",
                            width: "2",
                        },
                        data: [],
                    },
                 

                ],
            },
            tableData:[{
                date:"",
                symbol:"",
                value:"",
            }],
            params:{
                start:"",
                end:"",
                symbol:"",
            },
            chartLoading:false,
            timer:null,
            zoomStart: 0,
            zoomEnd: 0,

          


        }
    },
    mounted() {

        this.fetchexchangeRate()
     
        //禁用时间框
        this.$addStorageEvent(1, "timeDisable", true);
        // this.switch3 = handelSwitchs(this.option, this.switch3)
        this.$addStorageEvent(1, "zoomStart", this.zoomStart);
        this.$addStorageEvent(1, "zoomEnd", this.zoomEnd);
          //监听localstorage变化
          window.addEventListener("setItem", () => {
            this.zoomStart = localStorage.getItem("zoomStart")
            this.zoomEnd = localStorage.getItem("zoomEnd")
        });
        this.oldY = this.option.yAxis
        if (this.timer) {
            clearInterval(this.timer)
        }
        // 1分钟请求一次页面
        this.timer = setInterval(() => {          
            this.fetchexchangeRate()
        }, 60000)
  
       
       
    },
    methods: {
        //初始化图表
        inCharts() {
            if (this.myChart == null) {
                this.myChart = echarts.init(document.getElementById("exchangeRateBox"));
            }
            this.option = handelZoom(this.myChart, this.option, this, this.zoomStart, this.zoomEnd)

            this.myChart.setOption(this.option);
            chartsWidth("exchangeRateBox", this);
            window.addEventListener("resize", () => {
                if (this.myChart) this.myChart.resize();
            });
        },
        async fetchexchangeRate(params) {
            this.exchangeRateLoading = true
          
            const { data } = await exchangeRate(params)
            this.tableData = data.data
             
                if (this.tableData.length == 0) {
                    
                    this.exchangeRateLoading = false
                    return
                }else{
                    this.tableData.sort((a, b)=>{
                        if (a.cn === "美元指数") {
                          return -1; // "美元指数" 排在前面
                        } else if (b.cn === "美元指数") {
                          return 1; // "美元指数" 排在前面
                        } else {
                          return 0; // 其他项保持原有顺序
                        }
                      });
                      if (!this.params.symbol) {
                        this.params.symbol=this.tableData[0].symbol
                      }
                 
                    this.fetchChart(this.params)
                    this.tableData.forEach(item => {
                        item.date = `${item.date.split(`T`)[1].split(`.`)[0]}`
                    });
                   
                }      

              
                
                  //添加水印
            this.option = handelWatermark(this.option)
        
            this.exchangeRateLoading = false
           
        },
        async fetchChart(params) {
            this.chartLoading=true
            const {data} = await exchangeRateChart(params)
            let chartData = data.data
              //空数据处理
              let noData = emptyData(data.data, this.option.series, this.inCharts, this)
              if (noData) {
                  this.chartLoading = false
                  return
              }


            let ValueList = []
            let timeList = []
            chartData.forEach(item => {
                let time =`${item.date.split("T")[0]} ${item.date.split("T")[1].split(".")[0]} ` 
                ValueList.push(Number(item.value))
                timeList.push(time)
            })
           

            this.option.series[0].data =ValueList
            this.option.xAxis.data=timeList
            this.inCharts()
            this.chartLoading=false

        },

        //点击对应行
        handelLi(row){
            // this.$addStorageEvent(1, "symbol", JSON.stringify(row.symbol));
            this.params.symbol = row.symbol         
            this.fetchChart(this.params)
        },

        //接收Home传的时间handelParmesTime
        handelSonTime(start, end) {
            this.params.start = start;
            this.params.end = end;
            this.fetchChart(this.params)
        },
        //点击对数/线性按钮切换
        handelLineSwitch() {
            this.option = handelLineType(this.option, this.oldY)
            this.switch3 = handelSwitchs(this.option, this.switch3)
            this.myChart.setOption(this.option);

        },
        //父级点击BTC价格按钮
        handelSonBtcPrice(radius, flag) {
            this.btcFlag = flag
            fetchBtcPrice("BTC", this.option.series[2], this.start, this.end, this.inCharts, this, this.btcFlag)

        },
        //父级点击ETH价格按钮
        handelSonEthPrice(radius, flag) {
            this.ethFlag = flag
            fetchEthPrice("ETH", this.option.series[2], this.start, this.end, this.inCharts, this, this.ethFlag)
        },
        //父级选择Sma
        handelSonSma(smaDataList) {

            // this.params.sma = smaDataList
            // this.fetchexchangeRate(this.params)
            // this.$addStorageEvent(1, "sma", smaDataList);
          
        },
        handelRefresh(){
            this.fetchChart(this.params)
        }

    },
    beforeDestroy(){
        clearInterval(this.timer)
    }
    
}