const _Http = getApp().globalData.http,
    currency = require("../../../utils/currency"),
    CNY = (value, symbol = "￥", precision = 2) => currency(value, {
        symbol,
        precision
    }).format(),
    dividend = wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000;


import * as echarts from '../../ec-canvas/echarts';
Component({
    properties: {
        idname: {
            type: [String || Number]
        },
        tips: {
            type: String
        }
    },
    options: {
        addGlobalClass: true
    },
    lifetimes: {
        attached: function () {
            getApp().globalData.Language.getLanguagePackage(this)
        }
    },
    data: {
        dateTypes: ["全部", "本年"],
        "content": {
            pageNumber: 1,
            pageTotal: 1,
            dataid: wx.getStorageSync('userMsg').userid,
            username: wx.getStorageSync('userMsg').name,
            dateType: "本年",
            type: 0,
            where: {
                begdate: "",
                enddate: "",
                isleave: "1",
                feestype: "",
                type: ""
            }
        },
        filterShow: false,
        list: []
    },
    methods: {
        async getList(init = false) {
            if (!this.data.list.length) _Http.basic({
                "classname": "sysmanage.develop.optiontype.optiontype",
                "method": "optiontypeselect",
                "content": {
                    "pageNumber": 1,
                    "pageSize": 1000,
                    "typename": "feestype",
                    "parameter": {}
                }
            }).then(res => {
                console.log("费用类型", res)
                if (res.code == 1) {
                    this.setData({
                        filtratelist: [{
                            label: "费用类型",
                            index: null,
                            showName: "name", //显示字段
                            valueKey: "feestype", //返回Key
                            selectKey: "value", //传参 代表选着字段 不传参返回整个选择对象
                            value: "", //选中值
                            list: res.data.map(v => {
                                return {
                                    name: v.value + '-' + getApp().globalData.Language.getMapText(v.remarks),
                                    value: v.value + '-' + v.remarks
                                }
                            })
                        }]
                    })
                }
            })
            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;
            }
            if (content.pageNumber > content.pageTotal) return;

            _Http.basic({
                id: this.data.idname,
                content
            }).then(res => {
                console.log("费用分析", res)
                this.selectComponent('#ListBox').automaticSetHei();
                this.selectComponent('#ListBox').RefreshToComplete();
                if (res.code != '1') return wx.showToast({
                    title: res.data,
                    icon: "none"
                })
                res.data = res.data.map(v => {
                    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()
                try {
                    res.data[0].ratio = res.data[0].ratio.filter(v => v.ratio)
                } catch (error) {

                }

                if (init) this.initChart(res.data[0].ratio, CNY(res.data[0].ratio[0].total / dividend));
            })
        },
        initChart(data, total) {
            const getMapText = getApp().globalData.Language.getMapText;
            let countDown = null,
                that = this;

            function changeUnwriteoffamounttype(params) {
                if (countDown) return;
                countDown = setTimeout(() => {
                    let data = that.data.list[0].ratio.find(v => getApp().globalData.Language.getMapText(v[nameKey]) == params.name)
                    clearTimeout(countDown)
                    countDown = null;
                    switch (that.data.idname) {
                        case "2024062614062202":
                            if (data.text != that.data.content.where.feestype) {
                                that.setData({
                                    "content.where.feestype": data.text || "",
                                    "content.pageNumber": 1,
                                });
                                let showText = getApp().globalData.Language.getMapText(data.text)
                                let Filtrate = that.selectComponent('#Filtrate');
                                Filtrate.setData({
                                    showText
                                })
                            }
                            break;
                        default:
                            if (data.type != that.data.content.where.type) {
                                that.setData({
                                    "content.where.type": data.type || "",
                                    "content.pageNumber": 1,
                                });
                            }
                            break;
                    }
                    that.getList()
                }, 200)
            };

            let nameKey = {
                2024062614062202: "text",
                2024062915153702: "type",
                2024062615133802: "type",
                2024062915152702: "type",
            } [this.data.idname]

            let option = {
                tooltip: {
                    trigger: 'item',
                    confine: true, // Ensure tooltip stays within chart boundaries
                    formatter: function (params) {
                        changeUnwriteoffamounttype(params)
                        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[nameKey]),
                            value: (v.ratio * 100).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)
        },
        clickOpen() {
            this.setData({
                filterShow: true
            })
        },
        /* 处理筛选 */
        handleFilter({
            detail
        }) {
            if (detail.name == "confirm") {
                this.setData({
                    "content.where.feestype": detail.feestype
                })
                this.selectComponent('#Filtrate').setData({
                    showText: getApp().globalData.Language.getMapText(detail.feestype)
                })
                this.getList(true)
            } else if (detail.name == 'reset') {
                this.setData({
                    "content.where.feestype": ""
                })
                this.selectComponent('#Filtrate').setData({
                    showText: getApp().globalData.Language.getMapText("全部")
                })
                this.getList(true)
            }
        },
    }
})