import * as echarts from "echarts";
import { handelLineType,dataLength,  emptyData,chartsWidth, handelSwitchs, fetchBtcPrice, handelZoom, fetchEthPrice, handelWatermark, handelProfitrate, handelSmaData, getDateArray } from "../../util/processingData"
export default {
    data() {
        return {
            lengthTimer:null,
            maLoading: false,
            option: {
                legend: {
                    right: 100,
                    formatter: function (name) {
                        return name;
                    },
                },
                tooltip: {
                    trigger: "axis",
                    textStyle: {
                        align: "left",
                    },
                    animation: false,
                    // formatter: function (params) {
                    //     var res = params[0].axisValueLabel;

                    //     for (let i = 0; i <= params.length - 1; i++) {
                    //         res += `</br>${params[i].marker} <span style="font-weight: bold">${params[i].value[1]}</span> ${params[i].seriesName}`;
                    //     }
                    //     return res;
                    // },
                    axisPointer: {
                        animation: false,
                        snap: true,
                        label: {
                            precision: 2, //坐标轴保留的位数
                        },
                        type: "cross", //cross shadow
                        crossStyle: {
                            //十字轴横线
                            // opacity: "0",
                            width: 0.5,
                        },
                        lineStyle: {
                            // opacity: 0,
                        },
                    },
                },

                xAxis: {
                    type: "time",
                    boundaryGap: false,
                    data: [],
                    axisTick: {
                        //去除刻度
                        show: false,
                    },
                    axisLine: {
                        //去除轴线
                        show: false,
                    },
                },
                yAxis: [
                    {
                        // name:this.$t(`home.figure`),
                        position: "left",
                        type: "value",
                        axisLabel: {
                            formatter: function (value) {

                                return `${value / 10000} W`
                            }
                        }
                    },
                    {
                        position: "right",
                        // type: "log",
                        splitNumber: "5",
                        show: false,
                    },
                    {
                        position: "right",
                        // type: "log",
                        splitNumber: "5",
                        show: false,
                    },
                    {
                        position: "right",
                        // type: "log",
                        splitNumber: "5",
                        show: false,
                    },
                ],
                dataZoom: [
                    {
                        type: "inside",
                        start: 10,
                        end: 100,
                        maxSpan: 100,
                        minSpan: 2,
                        animation: false,
                    },
                    {
                        start: 0,
                        end: 20,
                        showDetail: false,
                    },
                ],
                series: [
                    {
                        name: "200-days MA Multiplier",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#f7931a",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#f7931a",
                            width: "1",
                        },
                        data: [],
                    },
                    {
                        name: "1-Year MA Multiplier",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#aa069f",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#aa069f",
                            width: "1",
                        },
                        data: [],
                    },
                    {
                        name: "2-Year MA Multiplier",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#ab334f",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#ab334f",
                            width: "1",
                        },
                        data: [],
                    },
                    {
                        name: "2-Year MA Multiplier X 5",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#1a7f54",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#1a7f54",
                            width: "1",
                        },
                        data: [],
                    },
                    {
                        name: "Price [ETH]",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#627eea",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#627eea",
                            width: "1",
                        },
                        yAxisIndex: 0,
                        data: [],
                    },


                ],
            },
            dayoption: {
                legend: {
                    right: 140,
                    formatter: function (name) {
                        return name;
                    },
                },
                tooltip: {
                    trigger: "axis",
                    textStyle: {
                        align: "left",
                    },
                    animation: false,
                    // formatter: function (params) {
                    //     var res = params[0].axisValueLabel;

                    //     for (let i = 0; i <= params.length - 1; i++) {
                    //         res += `</br>${params[i].marker} <span style="font-weight: bold">${params[i].value[1]}</span> ${params[i].seriesName}`;
                    //     }
                    //     return res;
                    // },
                    axisPointer: {
                        animation: false,
                        snap: true,
                        label: {
                            precision: 2, //坐标轴保留的位数
                        },
                        type: "cross", //cross shadow
                        crossStyle: {
                            //十字轴横线
                            // opacity: "0",
                            width: 0.5,
                        },
                        lineStyle: {
                            // opacity: 0,
                        },
                    },
                },

                xAxis: {
                    // type: "time",
                    boundaryGap: false,
                    data: [],
                    axisTick: {
                        //去除刻度
                        show: false,
                    },
                    axisLine: {
                        //去除轴线
                        show: false,
                    },
                    axisLabel: {
                        formatter: function (value) {
                            let hours = value.split(" ")[1].split(":")[0];
                            let min = value.split(" ")[1].split(":")[1];
                            return `${hours}:${min}`;
                        },
                    },
                },
                yAxis: [
                    {
                        // name:this.$t(`home.figure2`),
                        position: "left",
                        type: "value",
                        min: `dataMin`,
                        max: `dataMax`,
                        axisLabel: {
                            formatter: function (value) {

                                let data = (value / 1000).toFixed(4)
                                return `${data} K`
                            }
                        }
                    },
                    {
                        position: "right",
                        type: "value",
                        min: `dataMin`,
                        max: `dataMax`,
                        show: true,
                    },
                    {
                        position: "right",
                        type: "log",
                        min: `dataMin`,
                        max: `dataMax`,
                        // splitNumber: "5",
                        show: false,
                    },
                    {
                        position: "right",
                        type: "log",
                        min: `dataMin`,
                        max: `dataMax`,
                        // splitNumber: "5",
                        show: false,
                    },
                    {
                        position: "right",
                        type: "log",
                        min: `dataMin`,
                        max: `dataMax`,
                        // splitNumber: "5",
                        show: false,
                    },
                ],
                dataZoom: [
                    {
                        type: "inside",
                        start: 10,
                        end: 100,
                        maxSpan: 100,
                        minSpan: 2,
                        animation: false,
                    },
                    {
                        start: 0,
                        end: 20,
                        showDetail: false,
                    },
                ],
                series: [
                    {
                        name: "200-days MA Multiplier",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#f7931a",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#f7931a",
                            width: "1",
                        },
                        data: [],
                    },
                    {
                        name: "1-Year MA Multiplier",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#aa069f",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#aa069f",
                            width: "1",
                        },
                        data: [],
                        // yAxisIndex: 2,
                    },
                    {
                        name: "2-Year MA Multiplier",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#ab334f",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#ab334f",
                            width: "1",
                        },
                        data: [],
                    },
                    {
                        name: "2-Year MA Multiplier X 5",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#1a7f54",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#1a7f54",
                            width: "1",
                        },
                        data: [],
                        // yAxisIndex: 0,
                    },
                    {
                        name: "Price [ETH]",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#627eea",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#627eea",
                            width: "1",
                        },
                        yAxisIndex: 1,
                        data: [],
                    },

                ],
            },
            maData: [],
            maDayData: [],
            timeParams: {
                req: "ma730",
                start: "",
                end: ""
            },
            dayParams: {
                req: "ma730day",
                start: "",
                end: ""
            },
            timer: null,
            radius: "btc",
            switch3: "",
            btcFlag: null,
            ethFlag: null,
            fatherSmaData: [],
            start: "",
            end: "",
            sma: "",
            zoomStart: 0,
            zoomEnd: 0,


        }
    },
    watch: {
        radius(val) {

            this.fetchMaData(this.timeParams.req, this.radius)
            this.fetchMaDayData(this.dayParams.req, this.radius)

        }

    },
    mounted() {
        if (this.timer) {
            clearInterval(this.timer)
        }
        this.radius = localStorage.getItem("radius");
        //监听localstorage变化
        window.addEventListener("setItem", () => {
            this.radius = localStorage.getItem("radius");
        });
        //清除定时器
        if (this.timer) {
            clearInterval(this.timer)
        }
        //5分钟请求一次
        this.timer = setInterval(() => {
            this.fetchMaData(this.timeParams.req, this.radius)
            this.fetchMaDayData(this.dayParams.req, this.radius)
        }, 300000)

        this.switch3 = handelSwitchs(this.option, this.switch3)

        this.ethFlag = JSON.parse(localStorage.getItem("ethFlag"));
        this.btcFlag = JSON.parse(localStorage.getItem("btcFlag"));
        this.$addStorageEvent(1, "zoomStart", this.zoomStart);
        this.$addStorageEvent(1, "zoomEnd", this.zoomEnd);

        window.addEventListener("setItem", () => {
            this.ethFlag = JSON.parse(localStorage.getItem("ethFlag"));
            this.btcFlag = JSON.parse(localStorage.getItem("btcFlag"));
            this.zoomStart = localStorage.getItem("zoomStart")
            this.zoomEnd = localStorage.getItem("zoomEnd")


        })


    },
    methods: {
        inChart() {
            if (this.myChart == null) {
                this.myChart = echarts.init(document.getElementById("maBox"));
            }
            this.option = handelZoom(this.myChart, this.option, this, this.zoomStart, this.zoomEnd)

            this.myChart.setOption(this.option);
            chartsWidth("maBox", this);
            window.addEventListener("resize", () => {
                if (this.myChart) this.myChart.resize();
            });
        },
        dayinChart() {
            if (this.myChartday == null) {
                this.myChartday = echarts.init(document.getElementById("maDayBox"));
            }
            this.dayoption = handelZoom(this.myChartday, this.dayoption, this, this.zoomStart, this.zoomEnd)

            this.myChartday.setOption(this.dayoption);
            chartsWidth("maDayBox", this);
            window.addEventListener("resize", () => {
                this.myChartday.resize();
            });
        },
        //请求渲染数据
        async fetchMaData(req, radius, start, end, sma) {
            this.maLoading = true
            const { data } = await this.$API.getMa370(req, radius, start, end, sma)
            this.maData = data.data

            //空数据处理
            let noData = emptyData(data.data, this.option.series, this.inChart, this)
            if (noData) {
                this.maLoading = false
                return
            }


            this.start = this.maData[0].date.split("T")[0]
            this.end = this.maData[this.maData.length - 1].date.split("T")[0]
            //添加水印
            this.option = handelWatermark(this.option)
            //根据渲染的数据时间渲染对应的价格线和移动平均线
            // this.$nextTick(() => {

            //     //点击时间 移动平均线有值 就渲染查询移动平均线
            //     if (this.fatherSmaData[0] && this.start) {
            //         this.handelSonSma(this.fatherSmaData, this.start, this.end)
            //     }
            //       //渲染ETH
            //       if (this.ethFlag) {                 
            //         this.$addStorageEvent(1, "ethFlag", JSON.stringify(this.ethFlag));
            //         this.handelSonEthPrice("ETH",this.ethFlag)
            //     }
            //      //渲染BTC价格
            //      if (this.btcFlag) {
            //         this.$addStorageEvent(1, "btcFlag", JSON.stringify(this.btcFlag));
            //         this.handelSonBtcPrice("BTC", this.btcFlag)
            //     }
            // })

            //不同币种显示不同价格曲线
            //    if (radius == "BTC") {
            //     this.option.series = this.option.series.filter(item => item.name !== "Price [ETH]")
            //     this.handelSonBtcPrice("BTC", true)
            // } else if (radius == "ETH") {
            //     this.option.series = this.option.series.filter(item => item.name !== "Price[BTC]")
            //     this.handelSonEthPrice("ETH", true)
            // }


            let ma200ValueList = []
            let ma365ValueList = []
            let ma730ValueList = []
            let ma730x5ValueList = []
            let priceList = []
            this.maData.forEach(item => {
                ma200ValueList.push(Number(item.ma200.toFixed(2)))
                ma365ValueList.push(Number(item.ma365.toFixed(2)))
                ma730ValueList.push(Number(item.ma730.toFixed(2)))
                ma730x5ValueList.push(Number(item.ma730x5.toFixed(2)))
                priceList.push(Number(item.price.toFixed(2)))
            })

            this.option.series[0].data = handelProfitrate(this.maData, ma200ValueList)
            this.option.series[1].data = handelProfitrate(this.maData, ma365ValueList)
            this.option.series[2].data = handelProfitrate(this.maData, ma730ValueList)
            this.option.series[3].data = handelProfitrate(this.maData, ma730x5ValueList)
            this.option.series[4].data = handelProfitrate(this.maData, priceList)
            this.inChart()
            this.maLoading = false
             //判定页面条数是否一致
             if (this.lengthTimer) {
                clearTimeout(this.lengthTimer)
            }
            this.lengthTimer = setTimeout(() => {

                this.$addStorageEvent(1, "lengthFlag", dataLength(this.option, this.option.series[0].data.length), );
                
                this.$addStorageEvent(1, "lengthFlag", dataLength(this.dayoption, this.dayoption.series[0].data.length), );

            }, 15000)
        },
        //请求渲染day数据
        async fetchMaDayData(req, radius, start, end) {

            const { data } = await this.$API.getMa370(req, radius, start, end)
            this.maDayData = data.data
            //空数据处理
            let noData = emptyData(data.data, this.dayoption.series, this.dayinChart, this)
            if (noData) {
               
                return
            }
            this.dayoption.xAxis.data.length = 0
            this.dayoption.series[0].data.length = 0
            this.dayoption.series[1].data.length = 0
            this.dayoption.series[2].data.length = 0
            this.dayoption.series[3].data.length = 0
            this.dayoption.series[4].data.length = 0
            //添加水印
            this.dayoption = handelWatermark(this.dayoption)
            this.maDayData.forEach(item => {
                let year = item.date.split("T")[0]
                let hour = item.date.split("T")[1].split(".")[0]
                let time = `${year} ${hour}`
                this.dayoption.xAxis.data.push(time)
                this.dayoption.series[0].data.push([time, Number(item.ma200.toFixed(2))])
                this.dayoption.series[1].data.push([time, Number(item.ma365.toFixed(2))])
                this.dayoption.series[2].data.push([time, Number(item.ma730.toFixed(2))])
                this.dayoption.series[3].data.push([time, Number(item.ma730x5.toFixed(2))])
                this.dayoption.series[4].data.push([time, Number(item.price.toFixed(2))])

            })
            this.dayinChart()


        },
        //父级时间
        handelSonTime(start, end) {
            this.timeParams.start = start;
            this.timeParams.end = end;
            this.fetchMaData(this.timeParams.req, this.radius, this.timeParams.start, this.timeParams.end, this.sma)
            // if (this.radius =="BTC") {
            //   //  this.handelSonEthPrice()
            // }else{
            //     this.handelSonBtcPrice("BTC",true)
            // }
        },

        //点击对数/线性按钮切换
        handelLineSwitch() {
            this.option = handelLineType(this.option)
            this.dayoption = handelLineType(this.dayoption)
            this.switch3 = handelSwitchs(this.option, this.switch3)
            this.myChart.setOption(this.option);
            this.myChartday.setOption(this.dayoption);
        },
        //父级点击BTC价格按钮
        handelSonBtcPrice(radius, flag) {
            //父级BTC默认是true 在ETH页面btcFlag 取反才能正常点击父级就渲染
            // if (this.radius == "ETH") {
            //     this.btcFlag = !flag
            // }else{
            //     this.btcFlag = flag
            // }
            this.btcFlag = flag
            fetchBtcPrice("BTC", this.option.series[2], this.start, this.end, this.inChart, this, this.btcFlag)

        },
        //父级点击ETH价格按钮
        handelSonEthPrice(radius, flag) {
            //父级BTC默认是true 在ETH页面btcFlag 取反才能正常点击父级就渲染          
            // if (this.radius== "ETH") {
            //     this.ethFlag = !flag;
            // } else {
            //     this.ethFlag = flag;
            // }
            this.ethFlag = flag;
            this.$addStorageEvent(1, "ethFlag", JSON.stringify(this.ethFlag));
            fetchEthPrice("ETH", this.option.series[2], this.start, this.end, this.inChart, this, this.ethFlag)
        },
        //父级选择Sma
        handelSonSma(smaDataList) {

            this.sma = smaDataList
            this.fetchMaData(this.timeParams.req, this.radius, this.timeParams.start, this.timeParams.end, this.sma)
            this.$addStorageEvent(1, "sma", this.sma);

            // this.fatherSmaData = smaDataList
            // handelSmaData(smaDataList, this.option.series[2], this.inChart,this.start, this.end,)

        },



    },
    //进入组件激活
    activated() {
        console.log("激活");
        // this.timer = setInterval(() => {
        //     this.fetchMaData(this.timeParams.req)
        //     this.fetchMaDayData(this.dayParams.req)
        // }, 60000)
    },
    //组件退出时触发
    deactivated() {
        console.log("离开");
        //离开页面清除定时器
        clearInterval(this.timer);
    },
    beforeDestroy() {
        if (this.lengthTimer) {
            clearTimeout(this.lengthTimer)
        }
    }


}