import _ from 'lodash-es';
import { arrayExecItem, arrayPush, arrayStringWidth } from '../libs/array-extend.js';

/**
 * 插拔式开关（颜色）
 */
export const handleColor = ($data, $param, option) => {
    const { color } = $param;

    if (color) {
        const fn = (item, index) => {
            item.itemStyle.color = color[index];

            return item;
        };

        option.series[0].data = arrayExecItem(option.series[0].data, fn);
    }
};

/**
 * 插拔式开关（渐变色）
 */
export const handleGradient = ($data, $param, option) => {
    const { gradient } = $param;

    if (gradient) {
        const fn = (item, index, emphasis) => {
            let itemStyle = emphasis ? item.itemStyle.emphasis : item.itemStyle;

            itemStyle.opacity = emphasis ? 0.5 : 1;
            itemStyle.color = {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                    {
                        offset: 0,
                        color: gradient.start[index], // 0% 处的颜色
                    },
                    {
                        offset: 1,
                        color: gradient.end[index], // 100% 处的颜色
                    },
                ],
            };

            return item;
        };

        option.series[0].data = arrayExecItem(option.series[0].data, fn);
        option.series[2].data = arrayExecItem(option.series[2].data, fn, true);
    }
};

/**
 * 插拔式开关（是否展示总数）
 */
export const handleTotal = ($data, $param, option, total) => {
    const { isTotal, radius, center } = $param;

    if (isTotal) {
        option.series.push({
            type: 'pie',
            center: center,
            radius: radius,
            label: {
                show: true,
                position: 'center',
                color: '#fff',
                formatter: (param) => `{name|${param.name}}\n{value|${param.value}}`,
                rich: {
                    name: {
                        fontFamily: 'sans-serif',
                        fontSize: 14,
                        lineHeight: 21,
                    },
                    value: {
                        fontFamily: 'unidreamLED',
                        fontSize: 22,
                        lineHeight: 33,
                    },
                },
            },
            itemStyle: {
                normal: {
                    color: 'rgba(255, 255, 255, 0)',
                },
            },
            data: [
                {
                    name: '总数',
                    value: total,
                },
            ],
        });
    }
};

/**
 * 插拔式开关（高亮半透明）
 * 没有返回值，直接向option.series添加一个新的饼图
 */
export const handleTransparent = ($data, $param, $color, option, percentData) => {
    const { isTransparent, radius, center } = $param;

    if (isTransparent) {
        const series = {
            type: 'pie',
            center: center,
            radius: radius,
            label: {
                show: false,
            },
            emphasis: {
                scaleSize: 15,
            },
            data: [],
        };

        const seriesItem = (item, index) => ({
            name: item.name,
            value: item.value,
            itemStyle: {
                color: 'rgba(0, 0, 0, 0)',
                emphasis: {
                    color: $color.theme[index].replace(/(\d+)(\))/g, `${0.5}$2`),
                },
            },
        });

        arrayPush(percentData, series.data, seriesItem);

        option.series.push(series);
    }
};

/**
 * 插拔式开关（是否使用分割线）
 */
export const handleSplitLine = ($data, $param, option, percentData) => {
    const { isSplitLine, splitColor } = $param;

    if (isSplitLine) {
        if ($data.length > 1) {
            percentData.map((item, index) => {
                let border = {
                    name: 'border' + index,
                    value: 100 / 200,
                    itemStyle: {
                        color: splitColor ? splitColor : 'rgba(0, 0, 0, 1)',
                    },
                    emphasis: {
                        scaleSize: false,
                    },
                };

                index++;

                option.series[0].data.splice(index * 2 - 1, 0, border);
                option.series[2].data.splice(index * 2 - 1, 0, border);
            });
        }
    }
};

/**
 * 插拔式开关（图例格式化）
 */
export const handleLegend = ($data, $param, option, percentData) => {
    const { isLegendPercent } = $param;

    if (isLegendPercent) {
        Object.assign(option.legend, {
            formatter: (name) => {
                return `{name|${name} ${_.find(percentData, (o) => o.name === name).value}%} `;
            },
        });

        const names = percentData.map((item) => `${item.name} ${item.value}% `);

        Object.assign(option.legend.textStyle, {
            rich: {
                name: {
                    width: arrayStringWidth(names, 12),
                },
            },
        });
    }
};

/**
 * 插拔式开关（分割线回调）
 */
export const handleSplitLineCallback = ($data, $param, option, echarts, percentData) => {
    const { isSplitLine } = $param;

    if (isSplitLine) {
        echarts.on('legendselectchanged', (e) => {
            const nameArray = percentData.map((item) => item.name);

            const obj = {};

            const openArray = [];

            for (const key in e.selected) {
                if (key.indexOf('border') === -1) {
                    const nameIndex = nameArray.indexOf(key);

                    obj['border' + nameIndex] = e.selected[key];

                    if (e.selected[key]) openArray.push(key);
                }
            }

            for (const key in obj) {
                echarts.dispatchAction({
                    type: obj[key] && openArray.length !== 1 ? 'legendSelect' : 'legendUnSelect',
                    name: key,
                });
            }

            let max = 0;

            $data.map((item) => {
                if (openArray.includes(item.name)) {
                    max += item.value;
                }
            });

            option.series[1].data[0].value = max;

            let percentMax = 0;

            percentData.map((item) => {
                if (openArray.includes(item.name)) {
                    percentMax += item.value;
                }
            });

            const fn = (item, index) => {
                if (item.name.indexOf('border') > -1) {
                    item.value = percentMax / 200;
                }

                return item;
            };

            option.series[0].data = arrayExecItem(option.series[0].data, fn);
            option.series[2].data = arrayExecItem(option.series[2].data, fn);

            echarts.setOption(option);
        });
    }
};
