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

export default {
    data() {
        return {
            volumeProfileLoading: false,
            dataZoomStart: 25,
            dataZoomEnd: 75,
            option: {

                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        animation: false,
                        type: "cross",
                        lineStyle: {
                            color: "#376df4",
                            width: 2,
                            opacity: 0,
                        },

                        crossStyle: {
                            //十字轴横线
                            opacity: "0",
                        },
                    },

                    //   formatter: (params) => {
                    //     var res
                    //     // console.log(params,);
                    //     if (params[0].axisIndex !== 1) {            
                    //       res = params[0].axisValueLabel;
                    //       // this.indicators05 = params[4].data
                    //       // this.indicators10 = params[5].data
                    //       // this.indicators20 = params[6].data
                    //       res += `</br>${params[0].marker} <span style="font-weight: bold">open</span>\u00A0\u00A0\u00A0\u00A0 ${params[0].data[1]} 
                    //       </br>${params[0].marker} <span style="font-weight: bold">close</span>\u00A0\u00A0\u00A0\u00A0 ${params[0].data[2]} 
                    //       </br>${params[0].marker} <span style="font-weight: bold">lowest</span>\u00A0\u00A0\u00A0\u00A0 ${params[0].data[3]} 
                    //       </br>${params[0].marker} <span style="font-weight: bold">highest</span>\u00A0\u00A0\u00A0\u00A0 ${params[0].data[4]} 
                    //       </br>${params[1].marker} <span style="font-weight: bold"> ${params[1].seriesName}</span>\u00A0\u00A0\u00A0\u00A0 ${params[1].value}
                    //       </br>${params[2].marker} <span style="font-weight: bold"> ${params[2].seriesName}</span>\u00A0\u00A0\u00A0\u00A0 ${params[2].value}%
                    //       </br>${params[3].marker} <span style="font-weight: bold"> ${params[3].seriesName}</span>\u00A0\u00A0\u00A0\u00A0 ${params[3].value}亿股`;

                    //     }


                    //     return res;
                    //   },
                },
                grid: [
                    {
                        // left: 0,
                        top: "5%",
                        right: "10%",
                        height: "70%",
                        // borderWidth: 10,
                        // containLabel: true,
                    },
                    {
                        // left: 0,
                        top: "80%",
                        right: "10%",
                        height: "20%",
                        // containLabel:true
                    },
                ],
                xAxis: [{
                    // type: "time",
                    data: [],
                    axisLine: { lineStyle: { color: "#8392A5" } },
                    //   显示在第一个grid坐标上
                    gridIndex: 0,
                    position: "bottom",
                    boundaryGap: false // 坐标轴不留空白

                },
                {
                    //是否显示X轴
                    show: false,
                    //显示在第一个grid坐标上
                    gridIndex: 1,
                    // 网格线
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: "rgba(225,225,225)",
                            width: 1,
                            type: "solid",
                        },
                    },
                    // 数据
                    data: [],
                    boundaryGap: false // 横轴两端的空白区域也可以被拖动
                },
                {
                    // type: "time",
                    position: "top",
                    type: 'value',
                    inverse: true,//反向坐标轴 让数据显示在右边
                    axisLine: { lineStyle: { color: "#8392A5" } },
                    //   显示在第一个grid坐标上
                    // gridIndex: 0,
                },
                ],
                yAxis: [
                    {
                        //显示在第一个grid坐标上
                        gridIndex: 0,
                        scale: true,
                        axisLine: { lineStyle: { color: "#8392A5" } },
                        splitLine: { show: false },
                    },
                    {
                        //显示在第二个grid坐标上
                        gridIndex: 1,
                        position: "right",
                        type: "value",
                        show: true,
                    },
                    {
                        //显示在第一个grid坐标上 横柱状图的X坐标
                        // gridIndex: 0,
                        position: "right",
                        // type: "value",
                        show: true,
                        data: []
                    },


                ],
                dataZoom: [
                    {

                        type: "inside",
                        xAxisIndex: [0, 1],
                        start: 25,
                        end: 75,
                        maxSpan: 100,
                        minSpan: 20,

                    },
                    {
                        type: "inside",
                        xAxisIndex: [0, 1],
                        maxSpan: 100,
                        minSpan: 20,
                        start: 0,
                        end: 100,



                    },
                    {
                        type: "inside",//slider
                        yAxisIndex: [2],
                        start: 0,
                        end: 100,
                        maxSpan: 100,
                        minSpan: 50,

                        // showDetail: false,
                    },


                ],


                series: [
                    {
                        type: "candlestick",
                        name: "Day",
                        symbol: "none",
                        data: [],
                        itemStyle: {
                            color: "#FD1050",
                            color0: "#0CF49B",
                            borderColor: "#FD1050",
                            borderColor0: "#0CF49B",
                        },
                    },

                    {
                        type: "bar",
                        name: "成交量",
                        xAxisIndex: 1,
                        yAxisIndex: 1,
                        data: [],
                        barCategoryGap: "30%",
                        itemStyle: {
                            symbol: "none",
                            color: "",
                        },
                    },
                    {
                        name: "交易量",
                        type: "bar",
                        stack: "total",
                        // stack: "1",
                        label: {
                            show: true,
                            fontSize: 10,
                            color: "#000",
                        },
                        emphasis: {
                            focus: "series",
                        },
                        // 
                        itemStyle: {
                            color: "#fac958",
                        },
                        data: [],
                        xAxisIndex: 2,
                        yAxisIndex: 2,
                    },

                ],

            },

            switch3: "",
            oldY: null,
            btcFlag: null,
            ethFlag: null,
            fatherSmaData: [],
            start: "",
            end: "",
            params: {
                start: "",
                end: "",
                sma: " ",
                count: 50,

            },
            dataS: [{

            }],
            zoomStart: 0,
            zoomEnd: 0,
            KlineParams: {
                start: "",
                end: "",
                symbol: "ETHUSDT",
                interval: "1h"
            },
            symbolValueList: [
                {
                    value: "BTCUSDT",
                    label: "BTCUSDT",
                },
                {
                    value: "ETHUSDT",
                    label: "ETHUSDT",
                },

            ],
            //K线总的数据
            totalData: [],
            intervalList: [{
                value: "1m",//1分钟
                label: "bian.oneMinutes",
            },
            {
                value: "3m",//3分钟
                label: "bian.minutes3",
            }, {
                value: "5m",
                label: "bian.minutes5",
            }, {
                value: "15m",
                label: "bian.minutes15",
            }, {
                value: "30m",
                label: "bian.minutes30",
            }, {
                value: "1h",
                label: "bian.hours1",
            }, {
                value: "2h",
                label: "bian.hours2",
            }, {
                value: "4h",
                label: "bian.hours4",
            }, {
                value: "6h",
                label: "bian.hours6",
            }, {
                value: "8h",
                label: "bian.hours8",
            }, {
                value: "12h",
                label: "bian.hours12",
            },
            {
                value: "1d",
                label: "bian.day",
            },
            {
                value: "3d",
                label: "bian.day3",
            },
            {
                value: "1w",
                label: "bian.weekly",
            },
            {
                value: "1M",
                label: "bian.month",
            },
            ],
            dragAndDrop: false,
            KData: [],
            flagInterval: false,//判断是否点击改变了时间间隔 改变间隔option数据清空不拼接



        }
    },
    mounted() {

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

        // end 拿时间之前的1000条数据  start 拿时间之后的1000条数据
        this.KlineParams.end = nowTime.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }).replace(/[/|年|月]/g, '-').replace(/[日|时]/g, '').replace(/分/g, ':')
        // console.log(this.KlineParams,"结果集覅");
        this.fetchKline(this.KlineParams)

    },
    methods: {
        // echarts鼠标事件
        handelMouse(flag) {
            // console.log("看if打开覅",flag);
            let mousePress
            mousePress = flag
            // setTimeout(() => {
            //     mousePress = flag
            //     console.log(mousePress,"2miao");
            // }, 2000);
            if (mousePress) {
                if ((this.dataZoomStart === 0 || this.dataZoomEnd === 100) && this.option.series[0].data[0][0]) {
                    Array(500).fill(1).forEach(item => {
                        this.option.series[0].data.unshift([null, null, null, null])
                        this.option.series[1].data.unshift(null)
                        this.option.xAxis[0].data.unshift('')
                        this.option.xAxis[1].data.unshift('')
                        this.option.series[0].data.push([null, null, null, null])
                        this.option.series[1].data.push(null)
                        this.option.xAxis[0].data.push('')
                        this.option.xAxis[1].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("volumeProfileBox"));
            }
            this.option.dataZoom[0].start = this.dataZoomStart
            this.option.dataZoom[0].end = this.dataZoomEnd

            // 处理柱状图颜色
            let barColor
            if (this.option.series[0].data[0]) {
                let arr = this.option.series[0].data.map((item) => {
                    return [item[0], item[1]];
                });
                this.option.series[1].itemStyle.color = function (params) {

                    if (
                        arr[params.dataIndex] &&
                        Number(arr[params.dataIndex][1] || 0) >=
                        Number(arr[params.dataIndex][0])
                    ) {
                        // console.log( Number(arr[params.dataIndex][1] || 0) >=
                        // Number(arr[params.dataIndex][0]),Number(arr[params.dataIndex][1]),"哈哈哈哈哈哈");
                        barColor = "#f64e56";
                    } else {
                        barColor = "#54ea92";
                    }

                    return barColor;

                };
            }




            this.myChart.setOption(this.option);
            chartsWidth("volumeProfileBox", this);

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


        },
        //请求柱状图
        async fetchVolumeProfile(params) {
            this.volumeProfileLoading = true
            const list = await getVolumeProfile(params)
            let barData = list.data.data
            
            //空数据处理
            let noData = emptyData(barData, this.option.series, this.inCharts, this)
            if (noData) {
                this.volumeProfileLoading = false
                return
            }

            this.option.yAxis[2].data = []
            this.option.series[2].data = []
            barData.forEach(item => {
                this.option.yAxis[2].data.push(item.price)
                this.option.series[2].data.push(item.volume)
            })


            this.inCharts()
            this.volumeProfileLoading = false
        },
        //请求K线图 防抖Debounce函数
        fetchKline: Debounce(async function (kParams) {
            let { data } = await getKLine(kParams)
            // if (!data.data[0]) {//无数据         
            //     this.$message({
            //         type: 'warning',
            //         message: this.$t(`home.NoData`)
            //     });
            //     this.option.series.forEach(item => {//清空数据重新渲染
            //         item.data.length = 0
            //     })
            //     this.inCharts()

            // }

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

            //减掉开头空白数据
            if (this.KData[0] && this.KData[0][0]) {
                this.KData = this.KData.splice(0, 499)

            }
            //减掉结尾空白数据
            if (this.KData[this.length - 1] && !this.KData[this.length - 1][0]) {
                this.KData = this.KData.splice(this.length - 500, 500)
            }
            if (this.flagInterval) {
                this.KData = data.data
            } else {
                this.KData = [...data.data, ...this.KData]
            }

            this.flagInterval = false//确定是否拼接数据


            //判断是否是初始数据 ，是 则不处理，不是 则判断是否有空数据未处理，有则 处理空数据
            if (this.option.series[0].data[0] && !this.option.series[0].data[0][0]) {
                this.option.series[0].data = this.option.series[0].data.slice(500, this.option.series[0].data.length - 500)
                this.option.series[1].data = this.option.series[1].data.slice(500, this.option.series[1].data.length - 500)

                this.option.xAxis[0].data = this.option.xAxis[0].data.slice(500, this.option.xAxis[0].data.length - 500)
                this.option.xAxis[1].data = this.option.xAxis[1].data.slice(500, this.option.xAxis[1].data.length - 500)

            }


            this.KData.forEach(item => {
                if (item.openTime.includes("T")) {
                    item.openTime = `${item.openTime.split(`T`)[0]} ${item.openTime.split(`T`)[1].split(`.`)[0]}`
                }

            })
            this.params.start = await this.KData[0].openTime
            this.params.end = await this.KData[this.KData.length - 1].openTime
            this.fetchVolumeProfile(this.params)//柱状图 根军K线图的开始结束时间进行渲染
            this.option = handelWatermark(this.option)
            this.option.xAxis[0].data = []
            this.option.xAxis[1].data = []
            this.option.series[0].data = []
            this.option.series[1].data = []
            this.KData.forEach(item => {
                this.option.xAxis[0].data.push(item.openTime)
                this.option.xAxis[1].data.push(item.openTime)
                this.option.series[0].data.push([
                    item.openPrice,
                    item.closePrice,
                    item.lowPrice,
                    item.highPrice]

                )
                this.option.series[1].data.push(item.volume)
            });


            // console.log("执行了嘛");
            // 处理柱状图颜色
            // let barColor
            // if (this.option.series[0].data[0]) {
            //     let arr = this.option.series[0].data.map((item) => {
            //         return [item[0], item[1]];
            //     });
            //     console.log(arr,"哦福利费");
            //     this.option.series[1].itemStyle.color = function (params) {                  

            //         if (
            //             arr[params.dataIndex]&&
            //             Number(arr[params.dataIndex][1] || 0) >=
            //             Number(arr[params.dataIndex][0])
            //         ) {
            //             // console.log( Number(arr[params.dataIndex][1] || 0) >=
            //             // Number(arr[params.dataIndex][0]),Number(arr[params.dataIndex][1]),"哈哈哈哈哈哈");
            //             barColor = "#f64e56";
            //         } else {
            //             barColor = "#54ea92";
            //         }

            //         return barColor;

            //     };
            // }          


            this.inCharts()




            // 监听滚动到数据完结在发起请求
            this.myChart.on("dataZoom", (e) => {
                let { start, end } = e.batch[0]
                this.dataZoomStart = start
                this.dataZoomEnd = end
                if (this.dragAndDrop) {//鼠标按下判断当前图表滚动范围是否拖拽 拖拽便重新发起请求
                    if (start <= 26) {
                        this.KlineParams.start = ""
                        this.KlineParams.end = this.KData[0].openTime

                    } else if (end >= 74) {
                        this.KlineParams.end = ""
                        this.KlineParams.start = this.KData[this.KData.length - 1].openTime
                    }

                    this.fetchKline(this.KlineParams)

                } else {

                    if (!this.option.series[0].data[0][0]) {
                        this.option.series[0].data = this.option.series[0].data.slice(500, this.option.series[0].data.length - 500)
                        this.option.series[1].data = this.option.series[1].data.slice(500, this.option.series[1].data.length - 500)
                        this.option.xAxis[0].data = this.option.xAxis[0].data.slice(500, this.option.xAxis[0].data.length - 500)
                        this.option.xAxis[1].data = this.option.xAxis[1].data.slice(500, this.option.xAxis[1].data.length - 500)
                    }
                }
                this.inCharts()
            });





        }, 1000),

        //接收Home传的时间handelParmesTime
        handelSonTime(start, end) {
            this.params.start = start;
            this.params.end = end;
            this.fetchVolumeProfile(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.fetchVolumeProfile(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
            }
        }


    }
}