
import * as echarts from "echarts";
import { $addStorageEvent } from '../../util/processingData'
import {ethPrice2}from '../../api/apiPost'
import { getBTCFees, getBTCVolume, getEaVolume2, } from '../../api/realTimeData'
import { chartsWidth,emptyData,dataLength, handelProfitrate, handelLineType, handelSwitchs, handelSmaData, getDateArray, handelWatermark, fetchBtcPrice, fetchEthPrice } from "../../util/processingData"
export default {
    data() {
        return {
            lengthTimer:null,
            volumeLoading: 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,
                    },
                    data:[]
                },
                yAxis: [
                    {
                        position: "left",
                        type: "value",
                        axisLabel: {
                            formatter: (value) => {
                                let data
                                if (value >= 1000000000) {
                                    data = `${value / 1000000000}B`
                                } else if (value >= 1000000) {
                                    data = `${value / 1000000}M`
                                } else {
                                    data = `${value / 1000}K`
                                }
                                return data
                            }
                        }
                    },
                    {
                        type: "value",
                        position: "right",
                        // type: "log",
                        // splitNumber: "5",
                        show: true,
                    },
                    {
                        type: "value",
                        position: "right",
                        // type: "log",
                        // splitNumber: "5",
                        show: false,
                    },
                    {
                        type: "value",
                        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: "Transaction Volume",
                        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",
                        },
                        emphasis: {
                            focus: 'series',


                        },
                        yAxisIndex: 0,
                        data: [],
                    },
                    {
                        name: "Transaction Fee",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#8b3349",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#8b3349",
                            width: "1",
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        yAxisIndex: 1,
                        data: [],
                    },
                    {
                        name: "Transaction Volume (Entity-adjusted)",
                        type: "line",
                        smooth: false, //线条是否圆滑
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#39a271",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#39a271",
                            width: "1",
                        },
                        emphasis: {
                            focus: 'series',
                        },
                        yAxisIndex: 0,
                        data: [],
                    },
                    {
                        name: "Price[BTC]",
                        type: "line",
                        smooth: false,
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        // areaStyle: {},
                        itemStyle: {
                            color: "#000",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            //线条样式
                            color: "#000",
                            width: "1",
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        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",
                    //     },
                    //     emphasis: {
                    //         focus: 'series'
                    //     },
                    //     yAxisIndex: 3,
                    //     data: [],
                    // },


                ],
            },
            params: {
                req: "BTCVolume",
                radius: "btc",
                sma: "",

            },
            feesParams: {
                req: "BTCFees",
                radius: "btc"
            },
            eaVolume: {
                req: "eaVolume",
                radius: "btc"
            },
            volumeData: [],
            feesData: [],
            times: {
                start: "",
                end: ""

            },
            eaVolumeData: [],
            switch3: "",
            btcFlag: true,
            ethFlag: false,
            fatherSmaData: [],
            start: "",
            end: "",
            zoomStart: 0,
            zoomEnd: 0,
            sma: "",
            dataSelection: [
                {
                  value: "1d",
                  label: "home.day1",
                  disabled:false,
                  authority:"guest",
                  grade:1,
                },
                {
                  value: "realTime",
                  label: "home.realTimeData",
                  disabled:false,
                  authority:"vip",
                  grade:4,
                },
              ],
              realTimeData:"",

        }
    },
    mounted() {

        this.fetchVolume(this.params.req, this.params.radius)
        this.fetchFees(this.feesParams.req, this.feesParams.radius)
        this.fetchEaVolume(this.eaVolume.req, this.eaVolume.radius)
        $addStorageEvent(1, "zoomStart", this.zoomStart);
        $addStorageEvent(1, "zoomEnd", this.zoomEnd);
        this.switch3 = handelSwitchs(this.option, this.switch3)
        this.ethFlag = JSON.parse(localStorage.getItem("ethFlag"));
        this.btcFlag = JSON.parse(localStorage.getItem("btcFlag"));
        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: {
        handleSelect(activeValue){
            if (activeValue == `1d`) {
                this.realTimeData =false
                this.fetchVolume(this.params.req, this.params.radius)
                this.fetchFees(this.feesParams.req, this.feesParams.radius)
                this.fetchEaVolume(this.eaVolume.req, this.eaVolume.radius)
            }else{
                this.fetchBTCFees()
                this.fetchBTCVolume()
                this.fetchEaVolume2()
                this.realTimeData =true
            }
        },
        inChart() {
            if (this.myChart == null) {
                this.myChart = echarts.init(document.getElementById("volumeBox"));
            }

            this.myChart.setOption(this.option);
            chartsWidth("volumeBox", this);
            window.addEventListener("resize", () => {
                if (this.myChart) this.myChart.resize();;
            });
        },
          //请求交易费实时数据
        async fetchBTCFees(){
            this.volumeLoading = true
            const { data } = await getBTCFees()
            let BTCFeesData = data.data
              //空数据处理
              let noData = emptyData(data.data, this.option.series, this.inChart, this)
              if (noData) {
                  this.volumeLoading = false
                  return
              }
              let Fees=[]
              let price=[]
              let xAxisData=[]
              BTCFeesData.forEach(item=>{
                item.date= `${item.date.split(`T`)[0]} ${item.date.split(`T`)[1].split(`.`)[0]}`
                Fees.push(item.value.toFixed(2))
                price.push(item.price.toFixed(2))
                xAxisData.push(item.date)
              })
               
              this.option.xAxis.type = 'category'
              //添加水印
              this.option=handelWatermark(this.option)
              this.option.xAxis.data = xAxisData
              this.option.series[1].data = Fees
              this.option.series[3].data = price

              this.myChart.clear();
              this.inChart()
              this.volumeLoading = false
    

        },
        async fetchBTCVolume(){
          
            const { data } = await getBTCVolume()
            let BTCVolumeData = data.data
            let Volume=[]
            BTCVolumeData.forEach(item=>{
                item.date= `${item.date.split(`T`)[0]} ${item.date.split(`T`)[1].split(`.`)[0]}`
                Volume.push(item.value.toFixed(2))
            })

            this.option.series[0].data = Volume
            this.inChart()
        },
        async fetchEaVolume2(){
            let  { data } = await getEaVolume2()
            let EaVolumeData = data.data
            let EaVolume=[]
            EaVolumeData.forEach(item=>{
                item.date= `${item.date.split(`T`)[0]} ${item.date.split(`T`)[1].split(`.`)[0]}`
                EaVolume.push(item.value.toFixed(2))
            })

            this.option.series[2].data = EaVolume
            this.inChart()
        },


        //请求交易量数据渲染
        async fetchVolume(req, radius, start, end, sma) {
            this.volumeLoading = true
            const { data } = await this.$API.getVolume(req, radius, start, end, sma)
            this.volumeData = data.data
            //空数据处理
            let noData = emptyData(data.data, this.option.series, this.inChart, this)
            if (noData) {
                this.volumeLoading = false
                return
            }
            this.option.xAxis.type="time"
            //添加水印
            handelWatermark(this.option, 750, 300)
            this.start = this.volumeData[0].date.split("T")[0]
            this.end = this.volumeData[this.volumeData.length - 1].date.split("T")[0]
            //根据渲染的数据时间渲染对应的价格线和移动平均线
            this.$nextTick(() => {
                //移动平均线没值 才渲染正常价格数据 
                if (this.start && !this.fatherSmaData[0]) {
                    this.handelSonBtcPrice("BTC", true)
                }
                if (this.ethFlag) {
                    this.$addStorageEvent(1, "ethFlag", JSON.stringify(this.ethFlag));
                    this.handelSonEthPrice("ETH", this.ethFlag)
                }



                //点击时间 移动平均线有值 就渲染查询移动平均线
                if (this.fatherSmaData[0] && this.start) {
                    this.handelSonSma(this.fatherSmaData, this.start, this.end)

                }
            })
            let volumeValueList = []
            this.volumeData.forEach(item => {

                // this.option.xAxis.data.push(time)
                volumeValueList.push(Number(item.value.toFixed(2)))
                // this.option.series[0].data.push([time, Number(item.value.toFixed(2))])
            })
            this.option.series[0].data = handelProfitrate(this.volumeData, volumeValueList)

            if (this.zoomStart) {
                this.option.dataZoom[0].start = this.zoomStart
                this.option.dataZoom[0].end = this.zoomEnd
            } else {
                this.option.dataZoom[0].start = 10
                this.option.dataZoom[0].end = 100
            }




            this.inChart()

         


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

                });


            })

            this.volumeLoading = false

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

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

            }, 10000)



        },
        //请求交易费数据渲染
        async fetchFees(req, radius, start, end, sma) {
            const { data } = await this.$API.getVolume(req, radius, start, end, sma)
            this.feesData = data.data
            this.option = handelWatermark(this.option, 650, 300)


            let feesValueList = []
            this.feesData.forEach(item => {

                feesValueList.push(Number(item.value.toFixed(2)))
            })
            this.option.series[1].data = handelProfitrate(this.feesData, feesValueList)

            this.inChart()


        },
        //请求交易量(找零消除)数据渲染
        async fetchEaVolume(req, radius, start, end, sma) {
            const { data } = await this.$API.getVolume(req, radius, start, end, sma)

            this.eaVolumeData = data.data

            let eaValueList = []
            this.eaVolumeData.forEach(item => {

                eaValueList.push(Number(item.value.toFixed(2)))
            })
            this.option.series[2].data = handelProfitrate(this.eaVolumeData, eaValueList)
            this.inChart()

        },
        //父级时间
        handelSonTime(start, end) {
            this.times.start = start;
            this.times.end = end;
            this.fetchVolume(this.params.req, this.params.radius, this.times.start, this.times.end, this.sma)
            this.fetchFees(this.feesParams.req, this.feesParams.radius, this.times.start, this.times.end, this.sma)
            this.fetchEaVolume(this.eaVolume.req, this.eaVolume.radius, this.times.start, this.times.end, this.sma)
            // this.handelSonEthPrice("ETH",false)
        },
        //点击对数/线性按钮切换
        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[3], this.start, this.end, this.inChart, this, this.btcFlag)


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


        },
        //父级选择Sma
        handelSonSma(smaNUm) {
            this.sma = smaNUm
            this.fetchVolume(this.params.req, this.params.radius, this.times.start, this.times.end, this.sma)
            this.fetchFees(this.feesParams.req, this.feesParams.radius, this.times.start, this.times.end, this.sma)
            this.fetchEaVolume(this.eaVolume.req, this.eaVolume.radius, this.times.start, this.times.end, this.sma)
            this.$addStorageEvent(1, "sma", this.sma);
            this.realTimeData =false
            // this.fatherSmaData = smaDataList
            // handelSmaData(smaDataList, this.option.series[3], this.inChart, this.start, this.end)

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