/**
 * Created by JianJia.Zhou<jianjia.zhou> on 2022/10/3.
 */
let AnalyzeChart = (function () {
    const version = "0.0.1";

    let chartInstance = '';

    let AnalyzeChart = function (selector, options) {
        return new AnalyzeChart.fn.init(selector, options);
    };

    AnalyzeChart.fn = AnalyzeChart.prototype = {
        AnalyzeChart: version,
        options: {btnName: '', searchBtn: '', url: '', yAxisName: '',nameSuffix: '',formName:''},
        constructor: AnalyzeChart,
        init: function (selector, options) {
            this.options = options
            chartInstance = echarts.init(selector)
            this.buttonEvent()
            this.menuClick()
        },
        menuClick(){
            $(".nav-link").unbind().bind('click',function (){
                window.location.href = $(this).attr('href')
            })
        },
        buttonEvent() {
            let _this = this
            $(`${_this.options.btnName}`).bind("click", function () {
                $(this).toggleClass('btn-primary').toggleClass('btn-default')
                _this.render()
            })
            $('.datepicker').datetimepicker({
                locale: 'zh-CN',
                format: 'YYYY-MM-DD',
            });
            $(`${_this.options.searchBtn}`).bind('click', function () {
                _this.render()
            })
        },
        render() {
            let data = this.getLegend();
            let categoryData = data.categoryData;
            let legendData = data.legendData;
            let option = this.chartOptions(legendData);
            chartInstance.setOption(option, true);
            this.query(legendData, categoryData)
        },
        query(legendData, categoryData) {
            chartInstance.showLoading()
            this.getData().then(res => {
                let {data} = res
                let series = [];
                legendData.forEach((item, index) => {
                    let temp = {
                        name: item.name,
                        type: item.type,
                        data: data[categoryData[index]]
                    };
                    series.push(temp);
                });

                chartInstance.setOption({
                    xAxis: [{
                        data: data.dates,
                        axisPointer: {
                            type: 'shadow'
                        },
                        splitLine: {
                            show: true
                        }
                    }],
                    series: series
                });
                chartInstance.hideLoading();
            });
        },
        getLegend() {
            let categoryData = [];
            let legendData = [];
            let _this = this
            $(`${_this.options.btnName}.btn-primary`).each(function () {
                let id = $(this).data("id");
                let name = $(this).text();
                let names = {name: `[${name}]${_this.options.nameSuffix}`, type: 'line', barMaxWidth: 30, average: false};
                categoryData.push(`analyze_${id}`);
                legendData.push(names);
            });
            return {legendData, categoryData}
        },
        chartOptions(legends) {
            let seriesData = [];
            let legendSelected = {};
            let colors = ["#0095F3", "#95E04A", "#605EEB", "#4ACDBB", "#FFD480"];
            for (let item of legends) {
                let series = {
                    name: item.name,
                    type: item.type !== undefined ? item.type : 'line',
                    barWidth: item.barWidth !== undefined ? item.barWidth : '',
                    yAxisIndex: item.yAxisIndex !== undefined ? item.yAxisIndex : 0,
                    smooth: true,
                    data: [],
                };
                legendSelected[item.name] = item.show !== undefined ? item.show : true;
                if (item.average) {
                    series['markLine'] = {
                        data: [
                            {type: 'average', name: '平均值'}
                        ]
                    }
                }
                seriesData.push(series);
            }
            return {
                animation: true,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                },
                toolbox: {
                    feature: {
                        // dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                /*legend: {
                    type :'scroll',
                    left:50,
                    right:50,
                    height:500,
                    data: legend_data,
                    selected:legend_selected,
                },*/
                grid: {
                    left: '4%',
                    right: '4%',
                    containLabel: true
                },
                dataZoom: [{
                    type: 'slider',
                    show: true,
                    xAxisIndex: 0,
                    yAxisIndex: 1,
                    start: 0,
                    end: 100,
                }, {
                    type: 'inside',
                    xAxisIndex: 0,
                    yAxisIndex: 1,
                    start: 0,
                    end: 100
                }],
                xAxis: {
                    type: 'category',
                    data: [],
                    //boundaryGap: false
                },
                yAxis: [
                    {
                        name: this.options.yAxisName,
                        type: 'value',
                        axisLabel: {
                            formatter: '{value} '
                        }
                    }
                ],
                series: seriesData,
                //color: colors
            };
        },
        getData() {
            let productIds = [];
            let _this = this
            $(`${this.options.btnName}.btn-primary`).each((index, obj) => {
                productIds.push($(obj).data('id'))
            })
            let startAt = $(`${_this.options.formName}  #filter-column-name-start`).val();
            let endAt = $(`${_this.options.formName} #filter-column-name-end`).val();
            let name = $(`${_this.options.formName}  .filter-column-name`).val();
            let data = {
                productIds,
                startAt,
                endAt,
                name
            }
            return $.post({
                url: this.options.url,
                data
            })
        },
    }
    AnalyzeChart.fn.init.prototype = AnalyzeChart.fn;

    return AnalyzeChart;
})()
