const _Http = getApp().globalData.http,
    currency = require("../../../utils/currency"),
    CNY = (value, symbol = "￥", precision = 2) => currency(value, {
        symbol,
        precision
    }).format();

Component({
    options: {
        addGlobalClass: true
    },
    lifetimes: {
        attached: function () {
            getApp().globalData.Language.getLanguagePackage(this)
            this.setData({
                "content.dataid": wx.getStorageSync('userMsg').userid,
                "content.username": wx.getStorageSync('userMsg').name,
            })
        }
    },
    data: {
        dateTypes: ["本年", "本季", "本月"],
        "content": {
            pageNumber: 1,
            pageTotal: 1,
            dateType: "本年",
            type: 0,
            where: {
                begdate: "",
                enddate: "",
                isleave: "1",
            }
        },
    },
    methods: {
        async getList(init = false) {
            if (init.detail != undefined) init = init.detail;
            let content = this.data.content
            const {
                dataid,
                type,
                username,
                isleave
            } = getCurrentPages()[getCurrentPages().length - 1].data;
            if (content.dataid != dataid || content.type != type || isleave != isleave) init = true
            content.dataid = dataid;
            content.type = type;
            content.username = username;
            content.where.isleave = isleave;
            if (init) {
                content.pageNumber = 1;
                content.pageTotal = 1;
                content.where.customerstype = "";
            }
            if (content.pageNumber > content.pageTotal) return;
            _Http.basic({
                "id": 2024062610330602,
                content
            }).then(res => {
                this.selectComponent('#ListBox').automaticSetHei();
                this.selectComponent('#ListBox').RefreshToComplete();
                console.log('业务员排行列表', res)
                if (res.code != '1') return wx.showToast({
                    title: res.data,
                    icon: "none"
                })
                res.data = res.data.map(v => {
                    const colors = ['#F56C6C', '#EF8E51', '#FFC148', '#999999'];
                    v.color = colors[v.rowindex - 1] || colors[3];
                    v.amount = CNY(v.amount)
                    return v
                })
                this.setData({
                    list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
                    "content.pageNumber": res.pageNumber + 1,
                    "content.pageSize": res.pageSize,
                })
                this.selectComponent("#TimeRange").onCancel()
            })
        },
        initChart(data, total) {
            const getMapText = getApp().globalData.Language.getMapText;
            let countDown = null,
                that = this;

            function changeUnwriteoffamounttype(index) {
                if (countDown) return;
                countDown = setTimeout(() => {
                    clearTimeout(countDown)
                    countDown = null;
                    if (data[index].key != that.data.content.where.customerstype) that.setData({
                        "content.where.customerstype": data[index].key || "",
                        "content.pageNumber": 1,
                    });
                    that.getList()

                }, 200)
            };


            let option = {
                tooltip: {
                    trigger: 'item',
                    confine: true, // Ensure tooltip stays within chart boundaries
                    formatter: function (params) {
                        changeUnwriteoffamounttype(params.dataIndex)
                        return `${getMapText(params.name)}: ${params.value} (${params.percent}%)`;
                    },
                },
                legend: {
                    type: 'scroll', // Enable scrollable legend
                    bottom: '5%', // Moved legend to the bottom
                    left: 'center',
                    pageIconColor: '#333', // Customize page icon color
                    pageTextStyle: {
                        color: '#333' // Customize page text style
                    }
                },
                series: [{
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['50%', '42%'], // Adjusted to align with the new legend position
                    endAngle: 360,
                    data: data.map(v => {
                        return {
                            name: getMapText(v.key),
                            value: (v.ratio).toFixed(2),
                        }
                    }),
                    label: {
                        normal: {
                            show: true,
                            position: 'outside',
                            formatter: '{b}: {c} ({d}%)',
                            textStyle: {
                                fontSize: 12,
                                color: '#333'
                            }
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: 14,
                                fontWeight: 'bold'
                            }
                        },
                        rich: {
                            total: {
                                fontSize: 20,
                                fontWeight: 'bold',
                                color: '#333'
                            },
                            desc: {
                                fontSize: 12,
                                color: '#999'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: true,
                            length: 10,
                            length2: 10
                        }
                    }
                }]
            };
            option.graphic = {
                type: 'text',
                left: 'center',
                top: '35%', // Adjusted to align with the new series position
                style: {
                    text: `${getMapText('客户总数')}\n\n${total}`,
                    textAlign: 'center',
                    fill: '#333',
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            };
            this.chartComponent = this.selectComponent('#mychart');
            this.chartComponent.init((canvas, width, height, dpr) => {
                const chart = echarts.init(canvas, null, {
                    width,
                    height,
                    devicePixelRatio: dpr
                });
                chart.setOption(option);
                return chart;
            });
        },
        changeDate({
            detail
        }) {
            this.setData({
                "content.dateType": detail.dateType,
                "content.where.begdate": detail.begdate || "",
                "content.where.enddate": detail.enddate || ""
            })
            this.getList(true)
        }
    }
})