
/**
    生成 echarts 配置
    param: option {
        data                              : 处理 rawData 后得到，见 splitData
        option  [optional, default = null]: 初始 option，可以通过 myChart.getOption() 得到，留空则使用默认配置
        name    [optional, default = ''  ]: 股票名称
        cciRange[optional, default = 20  ]: CCI 范围
        fly     [optional, default = []  ]: 空中加油数据，画线用
    }
**/
const upColor = '#EF5350', downColor = '#26A69A', middleColor = '#778899', upLimitColor = '#FFAC00', downLimitColor = '#00CAFF';
let generateOption = (option) => {
    if (!option.data) {
        layer.alert('generateOption: data 不能为空！', {icon: 2});
        return;
    }
    let defaultOption = option.option ? option.option : {
        animation: false,
        legend: [{
            bottom: 0,
            height: '10%',
            left: 'center',
            data: ['', '股东顶', '交易顶', '能量', '锚点能量', '能量比', '合力', 'MA5', 'MA10', 'MA20', 'MA30'],
            type: 'scroll',
            textStyle: {
                padding: [1, 0, 0, 0]
            }
        }],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            triggerOn: 'click|mousemove',
            borderWidth: 1,
            borderColor: '#ccc',
            backgroundColor:'rgba(255,255,255,0.8)',
            padding: 10,
            textStyle: {
                color: '#000'
            },
            /*position: function (pos, params, el, elRect, size) {
                var obj = {top: 10};
                obj[ ['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                el.innerHtml = '';
                return obj;
            },*/
            formatter: (d) => {
                if (option.tooltipCallback && typeof option.tooltipCallback === 'function') {
                    option.tooltipCallback(d);
                }
                let html = [];
                d.filter(o => o.componentSubType != 'candlestick').forEach((s) => {
                    let value = s.value;
                    if (s.value == undefined) return true;
                    if (value.__proto__.constructor.name === 'Array') {
                        value = value[1];
                    }
                    if ((value + '').indexOf('.') != -1 && (value + '').split('.')[1].length > 3) {
                        value = value.toFixed(3);
                    }
                    html.push(s.marker);
                    html.push(`<b>${s.seriesName}:</b><span>${value}</span><br/>`)
                });
                return html.join('');
            },
            /*extraCssText: 'display: none'*/
        },
        axisPointer: {
            link: {xAxisIndex: 'all'},
            label: {
                backgroundColor: '#777'
            }
        },
        toolbox: [{
            feature: {
                dataZoom: {
                    yAxisIndex: false
                },
                brush: {
                    type: ['lineX', 'clear']
                },
                myAnchor: {
                    show: true,
                    title: '选择最新最大量锚点至今',
                    onclick: () => {},
                    icon: 'path://M489.898667 960.981333c-25.770667 0-45.482667-20.394667-45.482667-47.018666V316.885333c0-26.624 19.712-46.976 45.482667-46.976 25.770667 0 45.482667 20.352 45.482666 46.976v597.077334c0 25.045333-19.712 47.018667-45.482666 47.018666z M489.898667 981.333333C271.573333 981.333333 83.626667 819.925333 42.666667 598.954667c-3.029333-14.08 1.536-28.16 9.088-39.168a44.8 44.8 0 0 1 34.858666-17.237334h162.218667c25.813333 0 45.482667 20.394667 45.482667 47.018667 0 26.624-19.669333 47.018667-45.482667 47.018667h-101.546667c50.005333 148.864 186.453333 250.709333 342.613334 250.709333 156.16 0 292.608-101.845333 342.613333-250.709333h-103.082667c-25.770667 0-45.482667-20.394667-45.482666-47.018667 0-26.624 19.712-47.018667 45.482666-47.018667h162.218667c13.653333 0 25.813333 6.272 34.901333 17.237334 9.088 10.965333 12.117333 25.088 9.088 39.168C896.213333 819.925333 709.76 981.333333 489.898667 981.333333zM489.898667 346.666667c-81.877333 0-147.029333-68.949333-147.029334-151.978667C342.869333 110.037333 409.557333 42.666667 489.898667 42.666667c81.877333 0 147.072 68.949333 147.072 152.021333 0 84.608-65.194667 151.978667-147.072 151.978667z m0-209.962667c-30.293333 0-56.064 26.624-56.064 57.984 0 31.317333 25.770667 57.984 56.064 57.984 30.293333 0 56.106667-26.666667 56.106666-58.026667 0-31.317333-24.277333-57.941333-56.106666-57.941333z'
                }
            }
        }],
        brush: {
            xAxisIndex: 'all',
            brushLink: 'all',
            outOfBrush: {
                opacity: 0.2
            }
        },
        visualMap: [{
            // 成交量
            show: false,
            seriesIndex: 1,
            dimension: 2,
            pieces: [{
                value: -2,
                color: downLimitColor
            },{
                value: 2,
                color: upLimitColor
            },{
                value: -1,
                color: downColor
            }, {
                value: 0,
                color: middleColor
            }, {
                value: 1,
                color: upColor
            }]
        }],
        grid: [
            {
                left: '5%',
                right: '5%',
                height: '35%'
            },
            {
                left: '5%',
                right: '5%',
                top: '50%',
                height: '10%'
            },
            {
                left: '5%',
                right: '5%',
                top: '63%',
                height: '10%'
            },
            {
                left: '5%',
                right: '5%',
                top: '76%',
                height: '10%'
            }
        ],
        xAxis: [
            {
                type: 'category',
                gridIndex: 0,
                scale: true,
                boundaryGap: false,
                //axisLine: {onZero: false},
                //splitLine: {show: false},
                //splitNumber: 20,
                min: 'dataMin',
                max: 'dataMax'/*,
                axisPointer: {
                    z: 100
                }*/
            },
            {
                type: 'category',
                gridIndex: 1,
                scale: true,
                boundaryGap: false,
                axisLine: {onZero: false},
                axisTick: {show: false},
                splitLine: {show: false},
                axisLabel: {show: false},
                splitNumber: 20,
                min: 'dataMin',
                max: 'dataMax'
            },
            {
                type: 'category',
                gridIndex: 2,
                scale: true,
                boundaryGap: false,
                axisLine: {onZero: false},
                axisTick: {show: false},
                splitLine: {show: false},
                axisLabel: {show: false},
                splitNumber: 20,
                min: 'dataMin',
                max: 'dataMax'
            },
            {
                type: 'category',
                gridIndex: 3,
                scale: true,
                boundaryGap: false,
                axisLine: {onZero: false},
                axisTick: {show: false},
                splitLine: {show: false},
                axisLabel: {show: false},
                splitNumber: 20,
                min: 'dataMin',
                max: 'dataMax'
            }
        ],
        yAxis: [
            {
                scale: true,
                splitArea: {
                    show: false // 背景图是否有奇偶颜色分隔
                },
                axisTick: {
                    inside: true
                }
            },
            {
                scale: true,
                gridIndex: 1,
                splitNumber: 2,
                axisLabel: {show: false},
                axisLine: {show: false},
                axisTick: {show: false},
                splitLine: {show: false},
                axisTick: {
                    inside: true
                }
            },
            {
                scale: true,
                gridIndex: 1,
                splitNumber: 2,
                axisTick: {
                    inside: true
                }
            },
            {
                scale: true,
                gridIndex: 2,
                splitNumber: 2,
                axisTick: {
                    inside: true
                }
            },
            {
                scale: true,
                gridIndex: 2,
                splitNumber: 2,
                axisTick: {
                    inside: true
                }
            },
            {
                scale: true,
                gridIndex: 3,
                splitNumber: 2,
                axisTick: {
                    inside: true
                }
            }
        ],
        dataZoom: [
            {
                type: 'inside',
                xAxisIndex: [0, 1, 2, 3],
                start: 98,
                end: 100
            },
            {
                show: true,
                xAxisIndex: [0, 1, 2, 3],
                type: 'slider',
                top: '89%',
                start: 98,
                end: 100
            }
        ],
        series: [
            {
                name: '',
                type: 'candlestick',
                itemStyle: {
                    color: upColor,
                    color0: downColor,
                    borderColor: undefined,
                    borderColor0: undefined
                },
                markLine: {
                    symbol: ['none', 'none'],
                    itemStyle: {
                      normal: {
                        lineStyle: {
                          type: 'solid',
                          color: 'red',
                        }
                      }
                    },
                    data: []
                },
                markArea: {
                    data: undefined
                }
            },
            {
                name: 'Volume',
                type: 'bar',
                xAxisIndex: 1,
                yAxisIndex: 1
            },
            {
                name: 'MA5',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA10',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA20',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA30',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'CCI',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 0.7
                },
                markLine: {
                    symbol: ['none', 'none'],
                    data: [
                        {
                            name: 'min line on close',
                            yAxis: -100
                        },
                        {
                            name: 'max line on close',
                            yAxis: 100
                        }
                    ]
                },
                markArea: {
                    itemStyle: {
                        color: 'rgba(251, 219, 55, 0.2)'
                    },
                    data: [ [
                        {
                            yAxis: -100
                        },
                        {
                            yAxis: 100
                        }
                    ]]
                },
                xAxisIndex: 3,
                yAxisIndex: 5
            },
            {
                name: '股东顶',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 1
                }
            },
            {
                name: '合力',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 1
                },
                xAxisIndex: 1,
                yAxisIndex: 2
            },
            {
                name: '能量',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 1
                },
                xAxisIndex: 2,
                yAxisIndex: 3
            },
            {
                name: '锚点能量',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 1
                },
                xAxisIndex: 2,
                yAxisIndex: 3
            },
            {
                name: '能量比',
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: 1
                },
                xAxisIndex: 2,
                yAxisIndex: 4
            }
        ]
    }
    if (option.data) {
        let _data = convertData(option.data);
        defaultOption.xAxis.forEach((i) => {
            i.data = _data.categoryData;
        });
        defaultOption.toolbox[0].feature.myAnchor.onclick = () => {
            if (_data.latestMaxVolIndex != -1) {
                myChart.dispatchAction({
                    type: 'brush',
                    areas: [{
                            xAxisIndex: 0,
                            brushType: 'lineX',
                            coordRange: [
                                _data.latestMaxVolIndex, option.data.stockValueExList.length - 1
                            ]}]
                });
            }
        }
        defaultOption.series[0].data = _data.values;
        defaultOption.series[1].data = _data.volumes;
        defaultOption.series[2].data = calculateMA(5, option.data.stockValueExList);
        defaultOption.series[3].data = calculateMA(10, option.data.stockValueExList);
        defaultOption.series[4].data = calculateMA(20, option.data.stockValueExList);
        defaultOption.series[5].data = calculateMA(30, option.data.stockValueExList);
        defaultOption.series[6].data = calculateCCI(option.cciRange?parseInt(option.cciRange):20, option.data.stockValueExList);
        defaultOption.series[7].data = _data.holderTops;
        defaultOption.series[8].data = _data.powers;
        defaultOption.series[9].data = _data.energys;
        defaultOption.series[10].data = _data.anchorEnergys;
        defaultOption.series[11].data = _data.energyRatios;
        let originalSeriesLength = 12; // 是上面所有 series 个数和
        
        // 调整数据缩放，解决数据量过小时的显示问题
        defaultOption.dataZoom[0].end = defaultOption.dataZoom[1].end = 100;
        defaultOption.dataZoom[0].start = defaultOption.dataZoom[1].start = 98;
        let start = defaultOption.dataZoom[0].start,
            end = defaultOption.dataZoom[0].end;
        if (_data.values.length * (end - start) / 100 < 100) {
            defaultOption.dataZoom[0].start = defaultOption.dataZoom[1].start =
                Math.max(0, 1 - 50 / _data.values.length) * 100;
        }
        
        // 调整自定义画盘参数
        if (defaultOption.series.length > originalSeriesLength) {
            defaultOption.series = defaultOption.series.slice(0, originalSeriesLength);
        }
        _data.customAnchors.forEach((col) => {
            defaultOption.series.push({
                name: col.title,
                type: 'line',
                symbol: 'none',
                smooth: false,
                lineStyle: {
                    opacity: .5
                },
                data: col.data
            });
            if (defaultOption.legend[0].data.indexOf(col.title) == -1)
                defaultOption.legend[0].data.push(col.title);
        });
    }
    if (option.name) {
        defaultOption.legend[0].data[0] = option.name;
        defaultOption.series[0].name = option.name;
    }
    if (option.fly) {
        let mainMarkLineData = [], cciMarkLineData = [];
        option.fly.forEach((i) => {
            mainMarkLineData.push(
                [{coord: [i.comp, i.compMinPrice]}, {coord: [i.categoryData, i.minPirce]}]
            );
            cciMarkLineData.push(
                [{coord: [i.comp, i.compCCI]}, {coord: [i.categoryData, i.cci]}]
            );
        });
        defaultOption.series[0].markLine.data = mainMarkLineData;
        defaultOption.series[6].markLine.data =
            defaultOption.series[6].markLine.data.slice(0, 2).concat(cciMarkLineData);
    }
    return defaultOption;
}


// 调整大小
let resize = () => {
    let windowHeight = window.innerHeight,
    main = document.querySelector('.main'),
    nav = document.querySelector('.nav')
    cardHeaderHeight = main.querySelector('.layui-card-header').offsetHeight,
    echartDiv = document.getElementById('stock-chart'),
    details = document.getElementById('stock-info-large');
    
    let height = windowHeight - cardHeaderHeight - nav.clientHeight - details.clientHeight - 64;
    echartDiv.style.height = height + 'px';
    myChart.resize();
};
window.addEventListener('load', () => {resize();});
window.addEventListener('resize', () => {resize();})