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

export default {
    data() {
        return {
            USTreasuriesYieldsLoading: false,
            dataZoomStart: 1,
            dataZoomEnd: 99,
            option: {
                graphic:[
                    {
                        type: 'group',
                        // rotation: Math.PI / 2,
                        bounding: 'raw',
                        right: "50%",
                        top: "40%",
                        // z: 10,
                        // rotation: 6,
                        children: [
                          {
                            type: 'text',
                            left: 'center',
                            top: 'center',
                  
                            silent: true,//不影响鼠标事件
                  
                            style: {
                              fill: `rgba(0,0,0,0.1)`,
                              text: `coinbus.cc`,
                              font: 'bold 80px sans-serif',
                  
                            }
                          }
                        ]
                      }

                ],
                
                tooltip: {
                    trigger: "axis",
                    //解决tooltip显示不全问题1 
                    confine: true,
                    formatter: (params) => {


                        var res = params[0].axisValueLabel;

                        for (let i = 0; i < params.length; i++) {

                            res += `</br>${params[i].marker} ${params[i].seriesName}-${this.params.limit.toUpperCase()}&nbsp&nbsp&nbsp&nbsp <span style="font-weight: bold">${params[i].value}%</span>`


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

                        }


                        return res;
                    },
                    axisPointer:{
                        label: {
                            show: false,
                            // precision: 0, //坐标轴保留的位数
                          },                    
                          type: "cross",
                    }
                },
                legend: {

                    show: false,
                    right: "100",
                    selectable: true
                    //处理legengd过长
                    // formatter: function (name) {

                    //     return echarts.format.truncateText(name, 100, '14px Microsoft Yahei', '…');
                    // },
                    // tooltip: {
                    //     show: true
                    // }
                },
                xAxis: {
                    // type: "time",
                    boundaryGap: false,
                    //   axisLabel: {
                    //     formatter: `{yyyy}-{MM}-{dd}`,
                    //   },
                    data: []
                },
                yAxis: [
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        axisLabel: {
                            formatter: (value) => {
                                let data
                                if (value >= 1000000000) {
                                  data = `${(value / 1000000000).toFixed(2)}B`
                                } else if (value >= 1000000) {
                                  data = `${(value / 1000000).toFixed(2)}M`
                                } else if (value >= 1000) {
                                  data = `${(value / 1000).toFixed(2)}K`
                                } else if (value <= -1000000000) {
                                  data = `${(value / 1000000000).toFixed(2)}B`
                                } else if (value <= -1000000) {
                                  data = `${(value / 1000000).toFixed(2)}M`
                                } else if (value <= -1000) {
                                  data = `${(value / 1000).toFixed(2)}K`
                                } else {
                                  data = value                      
                      
                                }                    
                      
                                return data
                              }
                        },
                        min: "dataMin",
                        max: "dataMax",
                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        show: true,
                        min: "dataMin",
                        max: "dataMax",
                        position: "right",
                        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;
                            },
                        },
                    },
                    {
                        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,
                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        min: "dataMin",
                        max: "dataMax",
                        show: false,
                    },
                    {
                        type: "value",
                        // boundaryGap: [0, "100%"],
                        min: "dataMin",
                        max: "dataMax",
                        show: false,
                    },
                ],
                dataZoom: [
                    {
                        type: "slider",
                        start: 0,
                        end: 100,
                    },
                    {
                        type: "inside",
                        start: 0,
                        end: 100,
                    },
                ],
                series: [
                    {
                        name: "TreasuriesYields",
                        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: [],
                    },




                ],
            },
            switch3: "",
            oldY: null,
            btcFlag: null,
            ethFlag: null,
            fatherSmaData: [],
            start: "",
            end: "",
            params: {
                start: "",
                end: "",
                limit: "1m",

            },
            dataS: [{

            }],
            zoomStart: 0,
            zoomEnd: 0,


            //K线总的数据
            totalData: [],
            timeIntervalList: [
                {
                    value: "1m",
                    label: "home.month1",
                },
                {
                    value: "3m",
                    label: "home.month3",
                },
                {
                    value: "6m",
                    label: "home.month6",
                },
                {
                    value: "1y",
                    label: "home.year1",
                },
                {
                    value: "2y",
                    label: "home.year2",
                },
                {
                    value: "5y",
                    label: "home.year5",
                },
                {
                    value: "10y",
                    label: "home.year10",
                },
                {
                    value: "20y",
                    label: "home.year20",
                },
                {
                    value: "30y",
                    label: "home.year30",
                },
            ],
            dragAndDrop: false,
            USTData: [],
            flagInterval: false,//判断是否点击改变了时间间隔 改变间隔option数据清空不拼接
            startX: "",
            loadingText: "",
            draggingText: "",
            draggingFlags: "",

        }
    },
    mounted() {

        //禁用时间框
        this.$addStorageEvent(1, "timeDisable", true);
        //获取当前时间请求K线图
        let nowTime = new Date()

        // end 拿时间之前的1000条数据  start 拿时间之后的1000条数据
        this.params.end = nowTime.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }).replace(/[/|年|月]/g, '-').replace(/[日|时]/g, '').replace(/分/g, ':')

        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.fetchKline(this.params)




    },
    methods: {
        // echarts鼠标事件
        handelMouse(flag) {
            // console.log("看if打开覅",flag);
            // let mousePress
            // mousePress = flag

            // if (mousePress) {

            //     if ((this.dataZoomStart <10  || this.dataZoomEnd > 98) && this.option.series[0].data[0]) {
            //         Array(500).fill(1).forEach(item => {
            //             this.option.series[0].data.unshift(null)
            //             this.option.xAxis.data.unshift('')
            //             this.option.series[0].data.push(null)
            //             this.option.xAxis.data.push('')

            //         })

            //     }

            //     // this.dataZoomStart = this.dataZoomStart === 0 ? 25 : this.dataZoomStart
            //     // this.dataZoomEnd = this.dataZoomEnd = 100 ? 75 : this.dataZoomEnd
            // }



            // this.dragAndDrop = flag

            // this.inCharts()
        },

        //初始化图表
        inCharts() {
            if (this.myChart == null) {
                this.myChart = echarts.init(document.getElementById("USTreasuriesYieldsBox"));
            }
            // this.option.dataZoom[0].start = this.dataZoomStart
            // this.option.dataZoom[0].end = this.dataZoomEnd
            this.option = handelZoom(
                this.myChart,
                this.option,
                this,
                this.zoomStart,
                this.zoomEnd
            );

            this.myChart.setOption(this.option);

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


        },

        //请求数据 防抖Debounce函数
        fetchKline: Debounce(async function (params) {
            let { data } = await getUSTreasuriesYields(params)

            // if (!data.data[0]) {//无数据         
            //     this.$message({
            //         type: 'warning',
            //         message: this.$t(`home.NoData`)
            //     });
            //     this.option.xAxis.data.length = 0
            //     this.option.series[0].data.length = 0
            //     this.inCharts()

            // }

            //空数据处理
            let noData = emptyData(data.data, this.option.series, this.inCharts, this)
            if (noData) {

                return
            }

            //添加水印
            // this.option = handelWatermark(this.option)
            // //减掉开头空白数据     

            // if (!this.USTData[0] === null) {
            //     console.log(this.USTData[0],"减掉了开头");
            //     this.USTData = this.USTData.splice(0, 499)

            // }
            // //  减掉结尾空白数据
            // if (this.USTData[this.length - 1]) {
            //     console.log(this.USTData[this.length - 1],"减掉了结尾");
            //     this.USTData = this.USTData.splice(this.length - 500, 500)
            // }
            if (this.flagInterval) {
                this.USTData = data.data
            } else {

                this.USTData = [...data.data, ...this.USTData]


            }

            // console.log("拼接数据", this.USTData);           
            this.flagInterval = false//确定是否拼接数据
            this.USTData.forEach(item => {

                if (item.date.includes("T")) {
                    item.date = item.date.split(`T`)[0]
                }

            })
            //排序
            this.USTData = this.dateSort(this.USTData)

            //去重
            this.USTData = this.removal(this.USTData)


            this.params.start = await this.USTData[0].date
            this.params.end = await this.USTData[this.USTData.length - 1].date
            this.option.series[0].data.length = 0
            this.option.xAxis.data.length = 0
            this.USTData.forEach(item => {
                this.option.series[0].data.push(item.value)
                this.option.xAxis.data.push(item.date)
            })

            //判断是否是初始数据 ，是 则不处理，不是 则判断是否有空数据未处理，有则 处理空数据
            //    console.log(this.option.series[0].data[0]===null,"基督教地点");
            if (!this.option.series[0].data[0] === null) {
                // console.log(this.option.series[0].data[0],"基督教地点");
                this.option.series[0].data = this.option.series[0].data.slice(500, this.option.series[0].data.length - 500)

                this.option.xAxis.data = this.option.xAxis.data.slice(500, this.option.xAxis.data.length - 500)

            }
            //限制滚动最大范围
            if (!this.option.dataZoom) return
   
            if (this.option.xAxis.type == "time") {
              this.option.dataZoom[0].minValueSpan = 3600 * 24 * 1000 * 7
            } else {
              this.option.dataZoom[0].minValueSpan = 6
            }
          
            this.inCharts()
            // 添加鼠标事件监听器
            this.myChart.getZr().on('mousedown', (params) => {
                // 记录鼠标按下时的坐标
                this.startX = params.offsetX;
            });

            this.myChart.getZr().on('mouseup', (params) => {
                // console.log(params.target.type, "params.target");
                if (params.target && params.target.type) {//拖动滚动条未到两边区域时不触发请求
                    return
                }
                // 获取鼠标松开时的坐标
                const endX = params.offsetX;
                // 获取提示文字的元素
                this.loadingText = document.getElementById('loadingText');
                // 判断拖拽方向
                if (endX > this.startX) {// 左边              
                    this.draggingFlags = "left"
                    console.log("左边",);
                    Array(500).fill(1).forEach(item => {
                        this.option.series[0].data.unshift(null)
                        this.option.xAxis.data.unshift('')
                        this.option.series[0].data.push(null)
                        this.option.xAxis.data.push('')

                    })
                    this.params.start = ""
                    this.params.end = this.USTData[0].date
                    this.draggingText = this.$t(`home.loading`) + this.params.end + this.$t(`home.ago`)
                    this.loadingText.style.display = 'block';
                    this.fetchKline(this.params)

                } else if (endX < this.startX) {
                    // 右边

                    this.draggingFlags = "right"
                    Array(500).fill(1).forEach(item => {
                        this.option.series[0].data.unshift(null)
                        this.option.xAxis.data.unshift('')
                        this.option.series[0].data.push(null)
                        this.option.xAxis.data.push('')
                    })
                    this.loadingText.style.display = 'block';
                    this.params.end = ""
                    this.params.start = this.USTData[this.USTData.length - 1].date
                    this.draggingText = this.$t(`home.loading`) + this.params.start + this.$t(`home.after`)
                    this.fetchKline(this.params)
                }
            });







            if (this.loadingText) {
                this.loadingText.style.display = 'none';
            }

            setTimeout(() => {
                //监听echarts 图表滚动
                this.myChart.on("dataZoom",  (e)=> {
                    if (!e || (!e.start && !e.batch?.[0]?.start)) {
                        return;
                    }
                    this.zoomStart = e.start || e.batch[0].start;
                    this.zoomEnd = e.end|| e.batch[0].end;
                    this.$addStorageEvent(1, "zoomStart", this.zoomStart);
                    this.$addStorageEvent(1, "zoomEnd", this.zoomEnd);
                });
            });


        }, 1000),

        //接收Home传的时间handelParmesTime
        handelSonTime(start, end) {
            this.params.start = start;
            this.params.end = end;
            this.fetchUSTreasuriesYields(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[5], this.start, this.end, this.inCharts, this, this.btcFlag)

        },
        //父级点击ETH价格按钮
        handelSonEthPrice(radius, flag) {
            this.ethFlag = flag
            fetchEthPrice("ETH", this.option.series[6], this.start, this.end, this.inCharts, this, this.ethFlag)
        },
        //父级选择Sma
        handelSonSma(smaDataList) {
            this.params.sma = smaDataList
            this.fetchUSTreasuriesYields(this.params)
            this.$addStorageEvent(1, "sma", smaDataList);
            // this.fatherSmaData = smaDataList
            // handelSmaData(smaDataList, this.option.series[5], this.inCharts,this.start, this.end,)

        },
        //下拉选择
        handelChang() {
            this.flagInterval = true
            this.fetchKline(this.KlineParams)

        },

        //处理时间栏导航
        handelTimeList(event) {
            if (!event.target.title) return;
            this.KlineParams.interval = event.target.title;
            this.flagInterval = true
            this.fetchKline(this.KlineParams)

        },
        //处理弹窗的导航点击
        handelPopupList(event) {
            if (!event.target.title) return;
            this.KlineParams.interval = event.target.title;
            this.flagInterval = true
            this.fetchKline(this.KlineParams)
        },
        //处理高亮时间显示
        handelHighlight(data) {
            if (data) {
                return this.intervalList.find(item => item.value == data).label
            }
        },
        activeInterval(interval) {
            if (interval) {
                return this.timeIntervalList.find(item => item.value == interval).label
            }
        },
        handelTimeInterval(limit) {
            this.flagInterval = true//选择时间不拼接之前的数据
            this.params.start = "" //清空尾部时间
            this.params.limit = limit
            this.fetchKline(this.params)
        },
        //根据时间排序
        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;
        },
        //去重
        removal(str1) {

            // 定义 Set 和比较函数
            let uniqueArray = Array.from(
                new Set(str1.map(obj => JSON.stringify(obj)))
            ).map(str => JSON.parse(str));
            return uniqueArray


        },





    }
}