import _ from 'lodash-es';
import { arrayExecItem, arrayPush } from '../../libs/array-extend.js';
import { $echarts } from '../../index.js';
import echartsStyle from '../../libs/echarts-style.js';
import * as $switch from '../../extend/pie-annular.js';

export default ({ dom, param, opt }) => {
    const { $color } = echartsStyle()

    /**
     * 对外参数
     */
    const $data = param.data;
    const $param = {
        ...param,
        radius: param.radius || [40, 60],
        center: param.center || ['center', 120],
    };

    /**
     * 导出配置项
     */
    let option = {
        tooltip: Object.assign(
            {
                trigger: 'item',
                formatter: (param) => {
                    let res = '';
                    if (param.name.indexOf('border') === -1) {
                        let item = _.filter($data, (o) => o.name === param.name);
                        if (item.length > 0) res = `${item[0].name} : ${item[0].value}`;
                    }
                    return res;
                },
            },
            $tooltip
        ),
        legend: {
            icon: 'circle',
            bottom: 20,
            right: 'center',
            width: '90%',
            itemWidth: 5,
            itemHeight: 5,
            itemGap: 15,
            textStyle: {
                color: '#fff',
                fontSize: 12,
            },
        },
        series: [
            {
                type: 'pie',
                center: $param.center,
                radius: $param.radius,
                label: {
                    show: false,
                },
                data: [],
            },
        ],
    };

    /**
     * 数据转换百分比
     */
    let total = _.sumBy($data, (o) => o.value);

    let percentData = arrayExecItem($data, (o) => (o.value = _.round((o.value / total) * 100, 2)));

    Object.assign(option.legend, {
        data: percentData.map((item) => item.name),
    });

    /**
     * 基础饼图
     */
    const baseFn = (item, index) => ({ name: item.name, value: item.value, itemStyle: { color: $color.theme[index] } });

    arrayPush(percentData, option.series[0].data, baseFn);

    /**
     * 插拔式开关（整块可移除，或者移除其中一项，也不会有任何影响）
     */
    $switch.handleColor($data, $param, option); // 颜色
    $switch.handleTotal($data, $param, option, total); // 是否展示总数
    $switch.handleTransparent($data, $param, $color, option, percentData); // 高亮半透明
    $switch.handleGradient($data, $param, option); // 渐变色
    $switch.handleSplitLine($data, $param, option, percentData); // 是否使用分割线
    $switch.handleLegend($data, $param, option, percentData); // 图例格式化

    /**
     * 渲染
     */
    let extensOption = $echarts.extens(opt, option);

    let echarts = $echarts.render(dom, extensOption);

    $switch.handleSplitLineCallback($data, $param, option, echarts, percentData); // 插拔式开关(是否使用分割线)
};
