import * as echarts from "echarts";
import { handelBtcPrice,emptyData,dataLength, chartsWidth, handelLineType, handelZoom, handelSwitchs, getDateArray, handelWatermark, fetchBtcPrice, fetchEthPrice } from "../../util/processingData"
import axios from "axios";
export default {
    data() {
        return {
            lengthTimer:null,
            mvrvLoading: false,
            params: {
                req: "mvrv",
                radius: "BTC",
                start: "",
                end: ""
            },
            option: {
                tooltip: {
                    trigger: "axis",
                    //解决tooltip显示不全问题1 
                    confine: true,
                    formatter: function (params) {
                        const date = new Date(params[0].value[0]);
                        const year = date.getFullYear();
                        const month = date.getMonth() + 1;
                        const day = date.getDate();
                        let time =  `${year}-${month}-${day}`;
                        var res =time                       

                        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[1]}</span>`

                        }
                        return res;
                    }

                    // position: function (point, params, dom, rect, size) {
                    //     console.log(size,5656);
                    //     // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
                    //     // 提示框位置
                    //     var x = 0; // x坐标位置
                    //     var y = 0; // y坐标位置

                    //     // 当前鼠标位置
                    //     var pointX = point[0];
                    //     var pointY = point[1];

                    //     // 外层div大小
                    //     // var viewWidth = size.viewSize[0];
                    //     // var viewHeight = size.viewSize[1];

                    //     // 提示框大小
                    //     var boxWidth = size.contentSize[0];
                    //     var boxHeight = size.contentSize[1];

                    //     // boxWidth > pointX 说明鼠标左边放不下提示框
                    //     if (boxWidth > pointX) {
                    //       x = 5;
                    //     } else {
                    //       // 左边放的下

                    //       x = pointX- boxWidth;
                    //     }



                    //     // boxHeight > pointY 说明鼠标上边放不下提示框
                    //     if (boxHeight > pointY) {
                    //       y = 5;
                    //     } else {
                    //       // 上边放得下
                    //       y = pointY - boxHeight;
                    //     }

                    //     return [x, y];
                    //   },
                },
                legend: {
                    right: "100",
                    // data:[`sopr`,'asopr','easopr','lthsopr','sthsopr',],
                    // selected:{
                    //     'asopr': false,
                    //     'easopr': false,
                    //     'lthsopr': false,
                    //     'sthsopr': false,                      
                    // }
                },
                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 {
                                    value = e;
                                }
                                return value;
                            },
                        },
                        min: "dataMin",
                        max: "dataMax",

                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        show: true,
                        position: "right",
                        min: "dataMin",
                        max: "dataMax",

                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        show: false,
                        position: "right",
                        min: "dataMin",
                        max: "dataMax",

                    },

                ],
                dataZoom: [
                    {
                        type: "inside",
                        start: 0,
                        end: 100,
                    },
                    {
                        start: 0,
                        end: 100,
                    },
                ],
                series: [
                    {
                        name: "MVRV ratio",
                        type: "line",
                        smooth: false,
                        symbol: "circle",
                        showSymbol: false,
                        symbolSize: 5,
                        // areaStyle: {},
                        itemStyle: {
                            color: "#f7931a",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#f7931a",
                            width: "1",
                        },
                        data: [],
                        markArea: {
                            silent: true,
                            data: [
                                [
                                    {
                                        yAxis: "min",
                                        itemStyle: {
                                            color: "#e5f7f0",
                                        },
                                    },
                                    {
                                        yAxis: "1",
                                    },
                                ],
                                [
                                    {
                                        yAxis: "5.55",
                                        itemStyle: {
                                            color: "#fde7e7",
                                        },
                                    },
                                    {
                                        yAxis: "3.7",
                                    },
                                ],

                                //  如果有多种颜色，就继续在这里写区间数组，复制上面的下来改颜色
                            ],
                        }
                    },
                    {
                        name: "Price[BTC]",
                        type: "line",
                        smooth: false,
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        // areaStyle: {},
                        itemStyle: {
                            color: "#888888",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#888888",
                            width: "1",
                        },
                        yAxisIndex: 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: "0",
                                //     yAxis: 0,
                                // },
                                //  {
                                //   name: "$40W",
                                //   yAxis: 400000,
                                // },
                                {
                                    name: "$70W",
                                    yAxis: 700000,
                                },
                                {
                                    name: "$40W",
                                    yAxis: 400000,
                                },

                                {
                                    name: "$10W",
                                    yAxis: 100000,
                                },
                                {
                                    name: "$100W",
                                    yAxis: 1000000,
                                    // position: ['100%', '50'],
                                },
                                {
                                    name: "$120W",
                                    yAxis: 1200000,
                                },

                                {
                                    name: "$140W",
                                    yAxis: 1400000,
                                },
                            ],
                        },
                    },
                    // {
                    //     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: 2,
                    //     data: [],
                    // },


                ],
            },
            switch3: "",
            btcFlag: null,
            ethFlag: null,
            fatherSmaData: [],
            startData: [],
            endData: [],
            start: "",
            end: "",
            zoomStart: 0,
            zoomEnd: 0,
            sma: "",
            zoomStart: 0,
            zoomEnd: 0,


        }
    },
    mounted() {
        this.switch3 = handelSwitchs(this.option, this.switch3)


        this.fetchMvrv(this.params.req, this.params.radius)

        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: {
        //初始化图表
        inCharts() {
            if (this.myChart == null) {
                this.myChart = echarts.init(document.getElementById("mvrvBox"));
            }
            this.option = handelZoom(this.myChart, this.option, this, this.zoomStart, this.zoomEnd)

            this.myChart.setOption(this.option);
            chartsWidth("mvrvBox", this);
            window.addEventListener("resize", () => {
                if (this.myChart) this.myChart.resize();
            });
        },

        async fetchMvrv(req, radius, start, end, sma) {
            this.mvrvLoading = true
            const { data } = await this.$API.getCsupply(req, radius, start, end, sma)
            this.mvrvData = data.data
            //空数据处理
            let noData = emptyData(data.data, this.option.series, this.inCharts, this)
            if (noData) {
                this.mvrvLoading = false
                return
            }
            this.start = this.mvrvData[0].time.split("T")[0]
            this.end = this.mvrvData[this.mvrvData.length - 1].time.split("T")[0]
            this.option = handelWatermark(this.option, 750, 300)
            //根据渲染的数据时间渲染对应的价格线和移动平均线
            this.$nextTick(() => {
                //移动平均线没值 才渲染正常价格数据 
                if (this.start && !this.fatherSmaData[0]) {
                    this.handelSonBtcPrice("BTC", true)
                }
                //点击时间 移动平均线有值 就渲染查询移动平均线
                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)
                }
            })


            // const { BTCUSDT_list, BTCUSD_list } = await this.getData()
            // // console.log(BTCUSDT_list,BTCUSD_list,"几点搜房价都是放假");
            // this.option.series[0].data = BTCUSD_list
            // this.option.series[1].data = BTCUSDT_list


            //没有查询到数据
            if (!this.mvrvData) {
                this.option.series[0].data.length = 0
                this.mvrvLoading = false

            } else {
                let time = ""
                let MvrvValueList = []
                this.mvrvData.forEach(item => {
                    time = item.time.split("T")[0]
                    MvrvValueList.push(Number(item.value.toFixed(2)))

                })
                this.option.series[0].data = handelBtcPrice(this.mvrvData, MvrvValueList)
            }




            this.inCharts()

            setTimeout(() => {

                this.mvrvLoading = false
            }, 0);

             //判定页面条数是否一致
             if (this.lengthTimer) {
                clearTimeout(this.lengthTimer)
            }
            this.lengthTimer = setTimeout(() => {

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

            }, 10000)

        },

        //接收Home传的时间handelParmesTime
        handelSonTime(start, end) {
            this.params.start = start;
            this.params.end = end;
            this.fetchMvrv(this.params.req, this.params.radius, this.params.start, this.params.end, this.sma)
        },
        //点击对数/线性按钮切换
        handelLineSwitch() {

            this.option = handelLineType(this.option)
            this.switch3 = handelSwitchs(this.option, this.switch3)
            this.myChart.setOption(this.option);

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

        },
        //父级点击ETH价格按钮
        handelSonEthPrice(radius, flag) {
            this.ethFlag = flag
            this.$addStorageEvent(1, "ethFlag", JSON.stringify(this.ethFlag));
            fetchEthPrice("ETH", this.option.series[2], this.start, this.end, this.inCharts, this, this.ethFlag)


        },
        //选择Sma
        handelSonSma(smaDataList) {


            this.sma = smaDataList

            this.fetchMvrv(this.params.req, this.params.radius, this.params.start, this.params.end, this.sma)

            this.$addStorageEvent(1, "sma", this.sma);

            // this.fatherSmaData = smaDataList      
            // console.log(this.zoomStart, this.zoomEnd, "你的经典复刻能否");
            // handelSmaData(smaDataList,this.option.series[1],this.inCharts,this.start, this.end,this.zoomStart,this.zoomEnd)

        },



        async getData() {
            const data = await axios.get("http://10.168.2.199:7001/netData")
            const result = data.data
            const BTCUSDT = result.U_data.split("\n")
            const BTCUSD = result.D_data.split("\n")
            let BTCUSDT_list = []
            let BTCUSD_list = []
            for (let item of BTCUSDT) {
                if (item !== "") {
                    BTCUSDT_list.push([Number(item.split(" ")[1]), Number(item.split(" ")[0])])
                }
            }
            for (let item of BTCUSD) {
                if (item !== "") {
                    BTCUSD_list.push([Number(item.split(" ")[1]), Number(item.split(" ")[0])])
                }

            }
            return { BTCUSDT_list, BTCUSD_list }
        }









    },
    beforeDestroy() {
        if (this.lengthTimer) {
            clearTimeout(this.lengthTimer)
        }
    }
}