import * as echarts from "echarts";
import { minLine } from "../../util/echarts"
import { handelWatermark,chartsWidth } from "../../util/processingData"

export default {
    data() {
        return {
            allData: [],
            imgSrc: "",
            option: { ...minLine },
            dayData: [],
            activeNames: "",
            coinmarketallLoading: false,

            lst: [ // 假数据
                {
                    id: 1,
                    price: {
                        name: '项目一',
                        resData: [
                            { name: '订购费用', value: 12 },
                            { name: '饲养费用', value: 18 },
                            { name: '实验费用', value: 8 },
                            { name: '其他费用', value: 10 },
                        ]
                    }
                }, {
                    id: 2,
                    price: {
                        name: '项目二',
                        resData: [
                            { name: '订购费用', value: 18 },
                            { name: '饲养费用', value: 10 },
                            { name: '实验费用', value: 20 },
                            { name: '其他费用', value: 9 },
                        ]
                    }
                }

            ],
            seriesData: [],
            list: [],
            chartDom: [],
            type: "",
            params: {
                start: "",
                end: ""
            },
            bigLine: {
                tooltip: {
                    trigger: 'axis',
                    //解决tooltip显示不全问题1 
                    confine: true,
                },
                grid: {
                    top: 1,
                    bottom: 20,
                    left: 50,
                    right: 5,
                },

                xAxis: {
                    // type: 'time',
                    boundaryGap: false,
                    data: []
                },
                yAxis: {
                    // type:"value",
                    show: true,
                    scale: true,
                    position: 'left',
                    axisLine: { show: false },
                    axisTick: { show: false },
                    splitLine: { show: false },
                    axisLabel: { inside: false, interval: 0 }
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },

                ],
                series: [
                    {
                        name: '币价',
                        type: 'line',
                        smooth: false,
                        symbol: "circle",
                        symbolSize: 5,
                        showSymbol: false,
                        itemStyle: {
                            color: "#ffa3a8",
                            borderColor: "rgba(221,220,107,0.1)",
                            borderWidth: 12,
                        },
                        lineStyle: {
                            color: "#ffa3a8",
                            width: 1,
                        },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1,
                                    [
                                        { offset: 0, color: 'red' },
                                        { offset: 0.5, color: 'pink' },
                                        { offset: 1, color: '#ddd' }
                                    ]
                                )
                            }
                        },

                        data: []
                    }
                ]

            },
            timeData: [],
            ids: "",
            chartLoading: false
        }
    },
    // watch: {
    //     //监听手风琴展开时间选择框启用
    //     type(val) {
    //         //日期选择框禁用
    //         if (!val) {
    //             this.$addStorageEvent(1, "timeDisable", true);
    //         } else {
    //             this.$addStorageEvent(1, "timeDisable", false);

    //         }
    //     }
    // },
    mounted() {
        //进页面默认禁用时间框
        this.$addStorageEvent(1, "timeDisable", true);
      
        this.fetchCoinmarketall()
    },
    methods: {
        //初始化图表
        inCharts() {
            this.myChart = echarts.init(document.getElementById("echartsBox"));

            this.myChart.setOption(this.option);
            chartsWidth("echartsBox", this);
            window.addEventListener("resize", () => {
                if (this.myChart) this.myChart.resize();
            });
        },
        //请求数据
        async fetchCoinmarketall() {
            this.coinmarketallLoading = true
            const { data } = await this.$API.getCoinmarketall()
            this.allData = data.data
            //空数据处理
            if (data.data.length===0) {
                this.$message({
                    message: this.$t(`home.NoData`),
                    type: 'warning'
                  });
              
                this.coinmarketallLoading = false
                return
            }
            this.allData.forEach(item => {
                let year = item.time.split("T")[0]
                let hours = item.time.split("T")[1].split(".")[0]
                item.time = `${year} ${hours}`
                item.value = Number(item.value).toFixed(2)
                let name = item.param.toLowerCase()

                if (this.handelTrading().indexOf(name) == -1) {
                    item.src = `https://studio.glassnode.com/images/crypto-icons/${name}.png`
                } else {
                    item.src = ""
                }

            })


            this.allData.forEach(item => {
                this.list.push([item.list, item.param])
                this.chartDom.push({ params: item.param })
            })
            //处理数据格式
            this.seriesData = this.handelLIst(this.list)

            // 小折线图
            this.$nextTick(() => {
                var minChart = document.getElementsByClassName("chart");
                for (var i = 0; i < this.allData.length; i++) { // 通过for循环，在相同class的dom内绘制元素
                    let myMinChart = echarts.init(minChart[i]);
                    this.handelMinChart(myMinChart, i)
                }
            })
            this.coinmarketallLoading = false
        },
        //处理小折线图渲染
        handelMinChart(charts, i) {
            let minOption = {
                xAxis: {
                    boundaryGap: false,
                    show: false,
                    axisLine: { onZero: false },
                    axisTick: { show: false },
                    axisLabel: { show: false, interval: 0 },
                    data: this.seriesData[i].map(item => item[0]),

                },
                yAxis: {
                    type: "value",
                    show: false,
                    scale: true,
                    min: "dataMin",
                    max: "dataMax",
                    position: 'right',
                    axisLine: { show: false },
                    axisTick: { show: false },
                    splitLine: { show: false },
                    axisLabel: { inside: false, interval: 0 }
                },
                dataZoom: [
                    {
                        type: "inside",
                        start: 0,
                        end: 100,
                    },
                ],
                grid: {
                    top: 1,
                    bottom: 3,
                    left: 3,
                    right: 3,
                },
                series: [
                    {
                        name: 'Fake Data',
                        type: 'line',
                        showSymbol: false,
                        lineStyle: {
                            color: "#d84d65"
                        },
                        data: this.seriesData[i].map(item => item[1])
                    }
                ]
            }

            charts.setOption(minOption, true)
        },
        //请求选择时间数据
        async fetchCoinmarket(coin, start, end) {
            this.chartLoading = true
            const { data } = await this.$API.getCoinmarket(coin, start, end)
            this.timeData = data.data
            // let ids = `echarts${id}`
            this.bigEchart = echarts.init(document.getElementById(this.ids))
            this.bigLine.xAxis.data.length = 0
            this.bigLine.series[0].data.length = 0
            this.timeData.forEach(item => {
                let year = item.time.split("T")[0];
                let hours = item.time.split("T")[1].split(".")[0];
                let date = `${year} ${hours}`;
                this.bigLine.xAxis.data.push(date)
                this.bigLine.series[0].data.push(Number(item.value).toFixed(2))
            })

            this.bigEchart.setOption(this.bigLine, true)

            this.chartLoading = false
            // console.log(data, "lishi");
        },
        //点击每一行
        handelChang(a,b) {
            // console.log(a, this.activeNames,b, 899);

        },

        //大折线图渲染
        handelClick(currency, id, index) {
            console.log(currency, id, index,5445);
            if (currency !== this.type) {
                this.type = currency
                this.ids = `echarts${id}`
                this.bigEchart = echarts.init(document.getElementById(this.ids))
                this.bigLine = {
                    tooltip: {
                        trigger: 'axis',
                        //解决tooltip显示不全问题1 
                        confine: true,
                    },
                    // grid: {
                    //     top: 1,
                    //     bottom: 20,
                    //     left: 50,
                    //     right: 5,
                    // },

                    xAxis: {
                        // type: 'time',
                        boundaryGap: false,
                        data: this.seriesData[index].map(item => item[0]),
                        axisLabel: {
                            formatter: (value) => {
                                let time = value.split(" ")[1]


                                return `${time.split(`:`)[0]}:${time.split(`:`)[1]}`
                            }
                        }
                    },
                    yAxis: {
                        // type:"value",
                        show: true,
                        scale: true,
                        position: 'left',
                        axisLine: { show: false },
                        axisTick: { show: false },
                        splitLine: { show: false },
                        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 {
                                    data = value
                                }
                                return data
                            }
                        }
                    },
                    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,//不影响鼠标事件
                                    // z: 100,
                                    style: {
                                        fill: `rgba(0,0,0,0.1)`,
                                        text: `coinbus.cc`,
                                        font: 'bold 80px sans-serif',

                                    }
                                }
                            ]
                        }
                    ],
                    dataZoom: [
                        {
                            type: 'inside',
                            start: 0,
                            end: 100
                        },

                    ],
                    series: [
                        {
                            name: 'currency',
                            type: 'line',
                            smooth: false,
                            symbol: "circle",
                            symbolSize: 5,
                            showSymbol: false,
                            itemStyle: {
                                color: "#ffa3a8",
                                borderColor: "rgba(221,220,107,0.1)",
                                borderWidth: 12,
                            },
                            lineStyle: {
                                color: "#ffa3a8",
                                width: 1,
                            },
                            areaStyle: {
                                normal: {
                                    color: new echarts.graphic.LinearGradient(
                                        0, 0, 0, 1,
                                        [
                                            { offset: 0, color: 'red' },
                                            { offset: 0.5, color: 'pink' },
                                            { offset: 1, color: '#ddd' }
                                        ]
                                    )
                                }
                            },

                            data: this.seriesData[index].map(item => item[1])
                        }
                    ]

                }
                this.bigEchart.setOption(this.bigLine, true)
                chartsWidth(this.ids, this);

              
                // echart.setOption(this.bigLine);
                //  当窗口或者大小发生改变时执行resize，重新绘制图表
                window.addEventListener("resize", () => {
                    this.bigEchart.resize();
                });

            } else {
                this.type = ''
                // echart.dispose()
            }

        },
       
        //处理没有图片的交易对
        handelTrading() {

            let str = "AVAX,NEAR,FLOW,HBAR,CHZ,EGLD,AXS,XEC,HNT,USTC,USDD,FTM,KLAY,USDN,RUNE,CAKE,MINA,KAVA,FEI,XDC,TWT,GMT,1INCH,CELO,GALA,AR,GT,CVX,ROSE"
            str = str.toLowerCase()
            let arr = str.split(",")
            return arr
        },

        //加载失败图表不显示
        imageLoad(event) {
            var img = event.srcElement
            img.onerror = null
            img.outerHTML = ''
        },
        //循环渲染下拉折线图
        handelDropDownChart(seriesData) {
            let roseCharts = document.getElementsByClassName('DropDownChart');

            for (let i = 0; i < roseCharts.length; i++) { // 通过for循环，在相同class的dom内绘制元素
                let myChart = echarts.init(roseCharts[i]);
                var option = {
                    tooltip: {
                        trigger: "axis",
                        position: function (pt) {
                            return [pt[0], "10%"];
                        },
                    },
                    legend: {},
                    xAxis: {
                        // type: "time",
                        // data: xData[i],
                        // boundaryGap: false,
                        // axisLabel: {
                        //     formatter: `{yyyy}-{MM}-{dd}`,
                        // },
                    },
                    yAxis: [
                        {
                            type: "value",
                            // boundaryGap: [0, "100%"],
                            // axisLabel: {
                            //     formatter: function (e) {

                            //         let value;
                            //         if (e > 1000000) {
                            //             value = e / 100000;
                            //         } else if (e > 100000) {
                            //             value = e / 1000;
                            //         } else {
                            //             value = e / 100;
                            //         }
                            //         return value;
                            //     },
                            // },
                        },
                        {
                            type: "value",
                            // boundaryGap: [0, "100%"],
                            show: false,
                        },
                    ],
                    dataZoom: [
                        {
                            type: "inside",
                            start: 0,
                            end: 100,
                        },
                        {
                            start: 0,
                            end: 100,
                        },
                    ],
                    series: [
                        {
                            name: "1",
                            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: seriesData[i],
                        },

                    ],

                }
                myChart.setOption(option)

            }

        },

        //处理折线图数据格式
        handelLIst(data) {
            let sumArr = []
            let arr = []
            data.forEach(item => {
                item[0].forEach(item => {
                    // Number(item.price).toFixed(2)
                    // 
                    let price = Number(parseInt(item.price * 10000) / 10000)
                    let year = item.date.split("T")[0]
                    let hours = item.date.split("T")[1].split(".")[0]
                    let time = `${year} ${hours} `
                    arr.push([time, Number(price), item.coinSymbol])
                })
            })
            // sumArr.push(arr)


            let newArr = []
            let a = []
            for (const i of arr) {
                if (a.indexOf(i[2]) === -1) {
                    newArr.push([[i[0], i[1]]])
                    a.push(i[2])
                } else {
                    newArr[a.indexOf(i[2])].push([i[0], i[1]])
                }
            }

            newArr.forEach(item => {
                item.sort((a, b) => {

                    return a[0] > b[0] ? 1 : -1
                })
            })


            return newArr

        },

        handelSonTime(start, end) {
            this.fetchCoinmarket(this.type, start, end)
        },

    }
}