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


export default {
    data() {
        return {
            fundingRateLoading: false,
            num: 0,
            option: {
                xAxis: {
                    type: 'category',
                    data: []
                },

                yAxis: {
                    type: 'value'
                },
                tooltip: {
                    trigger: "axis",
                    //解决tooltip显示不全问题1 
                    confine: true,
                    formatter: function (params) {

                        var res = params[0].name;
                        let value = params[0].value + ""
                        if (value.length > 4) {
                            value = value.slice(0, 6)
                        } else {
                            value = value
                        }
                        // console.log(value,value.length,565);
                        res += `</br>${params[0].marker} <span style="font-weight: bold"> ${params[0].seriesName}</span>\u00A0\u00A0\u00A0\u00A0 ${value}%
                        `;

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

                },
                dataZoom: [
                    {
                        type: "inside",
                        start: 80,
                        end: 100,
                        maxSpan: 100,
                        minSpan: 5,
                        animation: false,
                    },
                    {
                        start: 0,
                        end: 20,
                        showDetail: false,
                    },
                ],
                series: [
                    {
                        name: 'funding rate',
                        type: 'bar',
                        data: [],
                        itemStyle: {
                            normal: {
                                // 使用函数返回颜色值
                                color: function (params) {
                                    var val = params.value;
                                    if (val > 0) {
                                        // 正数柱状图染成红色
                                        return 'green';
                                    } else if (val < 0) {
                                        // 负数柱状图染成绿色
                                        return 'red';
                                    }
                                    // 0 值不染色
                                    return '';
                                }
                            }
                        },
                        z: 1
                    },

                    {
                        name: 'fundingRate',
                        type: 'line',
                        smooth: false,
                        symbol: "circle",
                        showSymbol: false,
                        symbolSize: 5,
                        data: [],
                        itemStyle: {
                            color: "#FF8C00",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            // 线条样式
                            color: '#FF8C00',
                            width: 2
                        },
                        yAxixIndex: 1,
                        z: 2
                    }
                ]
            },
            params: {

                symbol: "ETHUSDT",
                start: "",
                end: "",
                sma: "",

            },
            symbolList: [{
                value: "BTCUSDT",
                label: "BTCUSDT",
            },
            {
                value: "ETHUSDT",
                label: "ETHUSDT",
            },
            ],
            priceTime: {
                start: "2022-08-25",
                end: "2022-09-20",
            },
            time: "",
            switch3: "",
            oldY: null,
            btcFlag: null,
            ethFlag: null,
            fatherSmaData: [],
            start: "",
            end: "",
            zoomStart: 0,
            zoomEnd: 0,

        }
    },
    mounted() {
        //默认渲染当前时间一个月的数据
        // this.params.start=getDate("day", -30);

        // this.params.end =  getDate()
        this.fetchFundingRate(this.params)
        //禁用时间框
        // this.$addStorageEvent(1, "timeDisable", true);
        // this.switch3 = handelSwitchs(this.option, this.switch3)
        this.oldY = this.option.yAxis
        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("fundingRateBox"));
            }

            this.option = handelZoom(this.myChart, this.option, this, this.zoomStart, this.zoomEnd)
            this.myChart.setOption(this.option);
            chartsWidth("fundingRateBox", this);
            window.addEventListener("resize", () => {
                if (this.myChart) this.myChart.resize();
            });
        },
        //请求数据
        async fetchFundingRate(params) {

            this.fundingRateLoading = true

            const data = await getFundingRate(params)
            //  //添加水印
            this.option = handelWatermark(this.option)
            let fundingRate = data.data.data

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



            this.option.xAxis.data.length = 0

            this.option.series[0].data.length = 0
            fundingRate.forEach((item, index) => {

                let time = `${item.date.split("T")[0]} ${item.date.split("T")[1].split(`.`)[0]}`
                this.option.xAxis.data.push(time)
                this.option.series[0].data.push(Number(item.value * 100))
                this.option.series[1].data.push(Number(item.value * 100))
            })

            this.inChart()

            this.fundingRateLoading = false
        },
        //时间戳转换
        filterTime(time) {
            const date = new Date(time)
            const Y = date.getFullYear()
            const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
            const D = date.getDate()
            return `${Y}-${M}-${D}`
        },
        getData(n) {
            n = new Date(n)
            return n.toLocaleDateString().replace(/\//g, "-") + " " + n.toTimeString().substr(0, 8)
        },
        //初始化option
        onOption() {
            this.option = {
                // legend: {
                //     // data: ['bar', 'bar2', 'bar3', 'bar4'],
                //     // left: '10%'
                // },
                // brush: {
                //     toolbox: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
                //     xAxisIndex: 0
                // },
                // toolbox: {
                //     feature: {
                //         magicType: {
                //             type: ['stack']
                //         },
                //         dataView: {}
                //     }
                // },
                dataZoom: [
                    {
                        type: "inside",
                        start: 0,
                        end: 100,
                        maxSpan: 100,
                        minSpan: 5,
                        animation: false,
                    },
                    {
                        start: 0,
                        end: 20,
                        showDetail: false,
                    },
                ],
                tooltip: {
                    //解决tooltip显示不全问题1 
                    confine: true,
                    // formatter: function (params) {
                    //     console.log(params,33);
                    //     var res = params.name;
                    //     let value = params.value + ""
                    //     if (value.length > 4) {
                    //         value = value.slice(0, 6)
                    //     } else {
                    //         value = value
                    //     }
                    //     // console.log(value,value.length,565);
                    //     res += `</br>${params.marker} <span style="font-weight: bold"> ${params.seriesName}</span>\u00A0\u00A0\u00A0\u00A0 ${value}%
                    //     `;

                    //     // for (let i = 0; i <= params.length - 1; i++) {
                    //     //     res += `</br>${params[0].marker} <span style="font-weight: bold"> ${params[0].seriesName}</span> ${params[0].value}`;
                    //     // }
                    //     return res;
                    // },
                },
                xAxis: {
                    data: [],
                    // type:"time",
                    // name: 'X Axis',
                    axisLine: { onZero: true },
                    splitLine: { show: false },
                    splitArea: { show: false }
                },
                // grid: {
                //     top: "5%",
                //     // right: "10%",
                //     // height: "77%",
                // },
                yAxis: [
                    {

                        axisLabel: {
                            formatter: (value, index) => {
                                // if(this.num < value){
                                //     this.num = value
                                //     return value + 0.1
                                // }else{
                                //     return value
                                // }


                                return `${value}%`
                            }
                        },
                        // max:this.num
                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        min: "dataMin",
                        max: "dataMax",
                        show: false,
                    },
                ],
                grid: {
                    // bottom: 100
                },
                series: [
                    {
                        name: 'fundingRate',
                        type: 'bar',
                        stack: 'one',
                        emphasis: "",
                        itemStyle: {//颜色设置
                            normal: {
                                color: function (params) { //根据数值大小设置相关颜色
                                    if (params.value > 0) {
                                        return 'green'
                                    } else {
                                        return 'red'
                                    }
                                }
                            }
                        },

                        data: [],
                        z: 1
                    },
                    {
                        name: "fundingRate",
                        type: "line",
                        smooth: false,
                        symbol: "circle",
                        showSymbol: false,
                        symbolSize: 5,
                        // areaStyle: {},
                        itemStyle: {
                            color: "#f7931a",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        yAxisIndex: 1,
                        lineStyle: {
                            //线条样式
                            color: "#f7931a",
                            width: "1",
                        },
                        data: [],
                        z: 2
                    },

                ]
            }
        },
        //父级时间
        handelSonTime(start, end) {
            // let dateStart = new Date(start);
            // let dateEnd = new Date(end);
            // this.params.start = dateStart.getTime()
            // this.params.end = dateEnd.getTime()
            this.params.start = start
            this.params.end = end
            this.fetchFundingRate(this.params)
            this.params.start = "";
            this.params.end = "";
        },
        //选择Symbol
        handelSymbol(val) {

            this.fetchFundingRate(this.params)
        },
        //父级选择Sma
        handelSonSma(smaDataList) {
            this.params.sma = smaDataList
            this.fetchFundingRate(this.params)
            this.$addStorageEvent(1, "sma", smaDataList);


        },

    }

}