/**
 *  自定义控件书写模板
 */
var vehicleExpenseMobChart;
(function (KDApi, $) {
    // 构造函数，变量名随意，与最后一句代码的KDApi.register的第二个参数一致即可
    function VehicleExpense(model) {
        this._setModel(model)
    }

    // 原型中封装生命周期函数，固定格式
    var isUpdate = false;
    VehicleExpense.prototype = {
        _setModel: function (model) {
            this.model = model
        },
        init: function (props) {
            isUpdate = false;
            setHtml(this.model, props, isUpdate)
        },
        update: function (props) {
            isUpdate = true;
            setHtml(this.model, props, isUpdate)
        },
        destoryed: function () {
        }
    }

    var setHtml = function (model, props, isUpdate) {
        // 获取自定义控制属性 根据属性获取对应的自定义控件
        var config = props.configItems;
        var parentId;
        if (config) {
            parentId = config[0].value;
        }
        if (!isUpdate) {
            KDApi.templateFilePath('./html/container_vehicleexpense.html', model, {}).then(
                function (result) {
                    model.dom.innerHTML = result;
                    var data = props.data;
                    if (!data) {
                        var chartSelector = `#${parentId} #container_trip_vehicleexpense`;
                        var emptySelector = `#${parentId} .kd-cq-empty-vehicleexpense`;
                        var chartDom = document.querySelector(chartSelector);
                        var emptyDom = document.querySelector(emptySelector);
                        var noDataDom = document.createElement("span");
                        noDataDom.className='kd-cq-empty-description';
                        noDataDom.setAttribute("style","margin-top:8px;color:#666");
                        noDataDom.textContent=KDApi.getLangMsg(model, 'VehicleExpense_No_Data');
                        emptyDom.setAttribute("style", "display:block;text-align:center;mix-blend-mode:multiply;");
                        emptyDom.appendChild(noDataDom);
                        emptyDom.setAttribute("style", "display:block;text-align:center");
                        chartDom.setAttribute("style", "display:none");
                        return;
                    }
                }
            )

        }

        if (isUpdate && props.data && Object.keys(props.data).length > 0) {
            KDApi.loadFile("./js/echarts.min.vehicleexpense.js", model, function () {
                if (echarts) {
                    vehicleExpenseMobChart = echarts;
                }
                KDApi.loadFile("./js/echarts-liquidfill.js", model, function () {
                    if (echarts) {
                        echarts = undefined;
                    }
                    KDApi.templateFilePath('./html/container_vehicleexpense.html', model, {}).then(
                        function (result) {
                            model.dom.innerHTML = result;
                            loadData(model, props, vehicleExpenseMobChart);
                        }
                    )


                })
            })
        } else {
            KDApi.templateFilePath('./html/container_vehicleexpense.html', model, {}).then(
                function (result) {
                    model.dom.innerHTML = result;
                    var data = props.data;
                    if (!data) {
                        var chartSelector = `#${parentId} #container_trip_vehicleexpense`;
                        var emptySelector = `#${parentId} .kd-cq-empty-vehicleexpense`;
                        var chartDom = document.querySelector(chartSelector);
                        var emptyDom = document.querySelector(emptySelector);
                        var noDataDom = document.createElement("span");
                                                noDataDom.className='kd-cq-empty-description';
                                                noDataDom.setAttribute("style","margin-top:8px;color:#666");
                                                noDataDom.textContent=KDApi.getLangMsg(model, 'VehicleExpense_No_Data');
                                                emptyDom.setAttribute("style", "display:block;text-align:center;mix-blend-mode:multiply;");
                                                emptyDom.appendChild(noDataDom);
                        emptyDom.setAttribute("style", "display:block;text-align:center");
                        chartDom.setAttribute("style", "display:none");
                        return;
                    }
                }
            )
        }
    }

    function formatNumber(num) {
        if (num == null) {
            return num;
        }
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    var loadData = function (model, props, vehicleExpenseMobChart) {
        var config = props.configItems;
        var parentId;
        if (config) {
            parentId = config[0].value;
        }
        var option = {};
        var chartSelector = `#${parentId} #container_trip_vehicleexpense`;
        var emptySelector = `#${parentId} .kd-cq-empty-vehicleexpense`;
        var chartDom = document.querySelector(chartSelector);
        var myChart = vehicleExpenseMobChart.init(chartDom);
        if (props == null || props.data == null) {
            var emptyDom = document.querySelector(emptySelector);
            var noDataDom = document.createElement("span");
                                    noDataDom.className='kd-cq-empty-description';
                                    noDataDom.setAttribute("style","margin-top:8px;color:#666");
                                    noDataDom.textContent=KDApi.getLangMsg(model, 'VehicleExpense_No_Data');
                                    emptyDom.setAttribute("style", "display:block;text-align:center;mix-blend-mode:multiply;");
                                    emptyDom.appendChild(noDataDom);
            emptyDom.setAttribute("style", "display:block;text-align:center");
            chartDom.setAttribute("style", "display:none");
            return;
        }

        var clientWidth = chartDom.clientWidth;
        var clientHeight = chartDom.clientHeight;
        var centerX = clientWidth * 0.22;
        var centerY = clientHeight * 0.5;
        var min = Math.min(clientWidth, clientHeight) / 2;
        var radius = min * 0.7 * 1.15;

        var amount = props.data.centerText;
        var data = props.data.seriesData;
        if (data && data.length == 0 || JSON.stringify(data) == '{}') {
            var emptyDom = document.querySelector(emptySelector);
            var noDataDom = document.createElement("span");
                                    noDataDom.className='kd-cq-empty-description';
                                    noDataDom.setAttribute("style","margin-top:8px;color:#666");
                                    noDataDom.textContent=KDApi.getLangMsg(model, 'VehicleExpense_No_Data');
                                    emptyDom.setAttribute("style", "display:block;text-align:center;mix-blend-mode:multiply;");
                                    emptyDom.appendChild(noDataDom);
            emptyDom.setAttribute("style", "display:block;text-align:center");
            chartDom.setAttribute("style", "display:none");
            return;
        } else {
            var emptyDom = document.querySelector(emptySelector);
            emptyDom.setAttribute("style", "display:none");
            chartDom.setAttribute("style", "display:block;height:200px;width:100%");

        }
        var amountArr = [];
        data.map(item => {
            amountArr.push(item.name);
        });
        const maxAmountLength = Math.max(...amountArr.map(item => item.length));
        const fontSize = 10; // 字体大小，单位 px
        const extractSize = 10;
        // 动态计算每部分的宽度
        const nameWidth = maxAmountLength * fontSize * 0.6 + extractSize;
        const amountWidth = 8 * fontSize * 0.6 + extractSize;
        const percentWidth = 4 * fontSize * 0.6 + extractSize;
        const legendWidth = clientWidth * 0.45;
        option = {
            legend: {
                orient: 'vertical',
                type: 'scroll',
                show: true,
                right: '1%',
                itemGap: 15,
                itemWidth: 15,
                top: 'middle',
                height: 200,
                width: legendWidth,
                textStyle: {//文字颜色
                    fontSize: 10,
                    color: '#212121',
                    padding: [0, 3],//文字与图形之间的左右间距

                    rich: {
                        name: {
                            align: 'left',
                            width: nameWidth, // 固定名称宽度
                            fontSize: fontSize,
                            padding: [0, 5, 0, 0], // 右侧留白避免覆盖
                        },
                        value: {
                            align: 'right',
                            width: amountWidth, // 固定金额宽度
                            fontSize: fontSize,
                            padding: [0, 10, 0, 5] // 两侧留白
                        },
                        percent: {
                            align: 'right',
                            width: percentWidth, // 固定百分比宽度
                            fontSize: fontSize,

                        }
                    }
                },
                formatter: function (name) {	// 添加
                    var total = 0
                    var target = 0;
                    for (var i = 0; i < data.length; i++) {
                        total += data[i].value
                        if (data[i].name === name) {
                            target = data[i].value
                        }
                    }
                    var p = ((target / total) * 100).toFixed(2);
                    var newValue = formatNumber(target.toFixed(2));
                    return "{name|" + name + "}" + "{value|" + newValue + "}" + "{percent|" + p + "%}";
                }
            },


            tooltip: {
                show: true,
                formatter: "{b}<br/>{c} ({d}%)",
                trigger: "item"
            },
            // 使用 graphic 绘制光晕效果
            /* graphic: {
                 elements: [{
                     type: 'circle',
                     left: centerX - radius,
                     top: centerY - radius,
                     shape: {
                         r: radius  // 光晕半径，要比饼图半径略大
                     },
                     style: {
                         fill: 'none',
                         stroke: new vehicleExpenseMobChart.graphic.LinearGradient(
                             0, 0, 1, 1,  // 渐变方向
                             [
                                 {offset: 0, color: 'rgba(246, 249, 255, 0)'},
                                 {offset: 1, color: 'rgba(255, 255, 255, 0.8)'}  // 外部透明
                             ]
                         ),
                         lineWidth: 10,  // 光晕的宽度
                         shadowBlur: 25,  // 阴影模糊半径
                         shadowColor: 'rgba(0, 0, 0, 0.5)'  // 阴影颜色
                     }
                 }]
             },*/
            series: [

                {
                    type: 'liquidFill',
                    radius: '45%', // 水球的半径
                    center: ['22%', '50%'], // 水球的位置
                    data: [0.2, 0.33], // 水的填充比例
                    color: ['rgba(195,208,252,0.8)', 'rgba(237,246,255,0.0)'],
                    width:'50%',
                    backgroundStyle: {
                        borderWidth: 0,
                        color: 'rgba(219,231,253,0.2)' // 水球的背景
                    },
                    label: {
                        normal: {
                            formatter: function (param) {

                                return amount;
                            }, // 水球中显示的文本
                            textStyle: {
                                fontSize: 15
                            }
                        }
                    },
                    outline: {
                        borderDistance: 0,
                        itemStyle: {
                            borderWidth: 0
                        }
                    },
                    waveAnimation: true // 启用波浪动画
                },
                {
                    type: 'pie',
                    radius: ['60%', '70%'], // 饼图的内外半径
                    data: props.data.seriesData,
                    center: [
                        "22%",
                        "50%"
                    ],
                    label: {
                        show: false
                    },
                    labelLine: {
                        show: false
                    },

                }
            ]
        };

        option && myChart.setOption(option);
        // 创建 ResizeObserver
        const resizeObserver = new ResizeObserver(() => {
            console.log('容器大小发生变化');
            var clientWidth = chartDom.clientWidth;
            var clientHeight = chartDom.clientHeight;
            var centerX = clientWidth * 0.22;
            var centerY = clientHeight * 0.5;
            var min = Math.min(clientWidth, clientHeight) / 2;
            var radius = min * 0.7 * 1.15;
            var currentOption = myChart.getOption();
            /* currentOption.graphic = {
                 elements: [{
                     type: 'circle',
                     left: centerX - radius,
                     top: centerY - radius,
                     shape: {
                         r: radius  // 光晕半径，要比饼图半径略大
                     },
                     style: {
                         fill: 'none',
                         stroke: new vehicleExpenseMobChart.graphic.LinearGradient(
                             0, 0, 1, 1,  // 渐变方向
                             [
                                 {offset: 0, color: 'rgba(246, 249, 255, 0)'},
                                 {offset: 1, color: 'rgba(255, 255, 255, 0.8)'}  // 外部透明
                             ]
                         ),
                         lineWidth: 10,  // 光晕的宽度
                         shadowBlur: 25,  // 阴影模糊半径
                         shadowColor: 'rgba(0, 0, 0, 0.5)'  // 阴影颜色
                     }
                 }]
             };*/

            myChart.setOption(currentOption, true);
            console.log("vehicle resizing")
            myChart.resize();

        });

// 监听容器
        resizeObserver.observe(chartDom);


    };


    // 你只需知道第一个参数是你接下来要新增控件方案时填的方案id，第二个参数是上面声明的构造函数
    KDApi.register('kingdee-fi-vehicleexpense-mob', VehicleExpense,{isMulLang: true})
})(window.KDApi) // 这里的jQuery不是必须要传进去的，可移除，要用到的时候才传，PC端系统默认会有jQuery对象，版本是1.12.4