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

import * as echarts from '../ec-canvas/echarts';
Component({
    properties: {},
    options: {
        addGlobalClass: true,
    },
    lifetimes: {
        attached: function () {
            getApp().globalData.Language.getLanguagePackage(this)
            this.setData({
                auth: JSON.stringify(wx.getStorageSync('auth')),
                userMsg: JSON.stringify(wx.getStorageSync('userMsg')),
                site: JSON.stringify(wx.getStorageSync('siteP')),
                templetList: JSON.stringify(wx.getStorageSync('templetList')),
                languagecode: wx.getStorageSync('languagecode'),
                "content.dataid": wx.getStorageSync('userMsg').userid,
                "content.username": wx.getStorageSync('userMsg').name,
            })
            _Http.basic({
                "classname": "sysmanage.develop.optiontype.optiontype",
                "method": "optiontypeselect",
                "content": {
                    "pageNumber": 1,
                    "pageSize": 1000,
                    "typename": "ordertype",
                    "parameter": {}
                },
            }).then(res => {
                console.log("订单类型", res)
                if (res.code != '1') return;
                res.data.unshift({
                    remarks: '全部',
                    value: ""
                })
                this.setData({
                    types: res.data
                })
            })

            _Http.basic({
                "classname": "sysmanage.develop.optiontype.optiontype",
                "method": "optiontypeselect",
                "content": {
                    "pageNumber": 1,
                    "pageSize": 1000,
                    "typename": "tradefield",
                },
            }).then(res => {
                console.log("领域", res)
                if (res.code != '1') return;
                res.data.unshift({
                    remarks: '全部',
                    value: "",
                    color: "#3874F6"
                })
                this.setData({
                    tradefields: res.data
                })
            })

            _Http.basic({
                "id": "20220922085103",
                "version": 1,
                "content": {
                    pageSize: 1000,
                    "where": {
                        "condition": ""
                    }
                }
            }).then(res => {
                console.log("获取品牌", res)
                if (res.code != '1') return;
                res.data = res.data.map(v => {
                    return {
                        remarks: v.brandname,
                        value: v.sa_brandid,
                    }
                })
                res.data.unshift({
                    remarks: '全部',
                    value: "",
                    color: "#3874F6"
                })
                this.setData({
                    brands: res.data
                })

            })
        }
    },
    data: {
        dateTypes: ["全部", "本年", "本月"],
        "content": {
            pageNumber: 1,
            pageTotal: 1,
            dateType: "本年",
            dataType: "金额",
            type: 0,
            itemclass: "一级类别",
            where: {
                begdate: "",
                enddate: "",
                isleave: "1",
                type: "",
                tradefield: "",
                sa_brandid: ""
            }
        },
        itemclassList: [{
            remarks: '一级类别',
            value: "一级类别",
            color: "#3874F6"
        }, {
            remarks: '二级类别',
            value: "二级类别",
        }],
        total: 0
    },
    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;
            const dividend = wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000,
                getMapText = getApp().globalData.Language.getMapText;
            if (init) {
                content.pageNumber = 1;
                content.pageTotal = 1;
            }
            console.log(content)
            if (content.pageNumber > content.pageTotal) return;
            console.log(2)
            _Http.basic({
                "id": 20240524160004,
                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 => {
                    v.amount = CNY(v.amount)
                    v.returnamount = CNY(v.returnamount)
                    v.itemclassamount = CNY(v.itemclassamount)
                    return v
                })
                this.setData({
                    list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
                    "content.pageNumber": res.pageNumber + 1,
                    "content.pageTotal": res.pageTotal,
                    "content.pageSize": res.pageSize,
                    total: res.total,
                })
                try {
                    this.selectComponent("#TimeRange").onCancel()
                } catch (error) {

                }
                try {
                    this.selectAllComponents("#Filtrate").forEach(v => v.onCancel())
                } catch (error) {


                }
                if (init) this.initChart(res.data[0].ratio.filter(v => v.ratio), content.dataType == '金额' ? CNY(res.data[0].ratio[0].total / dividend) : res.data[0].ratio[0].total, getMapText);
            })
        },
        initChart(data, total, getMapText) {
            let countDown = null,
                that = this;

            function changeUnwriteoffamounttype(params) {
                if (countDown) return;
                countDown = setTimeout(() => {
                    clearTimeout(countDown)
                    countDown = null;
                    if (params.itemclassid != that.data.content.where.itemclassid) {
                        that.setData({
                            "content.where.itemclassid": params.itemclassid,
                            "content.pageNumber": 1,
                            itemclassfullname: params.itemclassfullname
                        })
                    }
                    that.getList()
                }, 200)
            };
            let option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        if (params.value - 0) changeUnwriteoffamounttype(data[params.dataIndex]);
                        return `${params.marker}${params.name}: ${params.value}%`;
                    },
                },
                legend: {
                    bottom: '5%', // Moved legend to the bottom
                    left: 'center',
                    type: 'scroll', // Enable scrolling for the legend
                    pageIconColor: '#333', // Customize the color of the page icons
                    pageTextStyle: {
                        color: '#333' // Customize the text color of the page indicator
                    }
                },
                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.itemclassfullname),
                            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)
        },
        changeType(e) {
            const {
                name
            } = e.currentTarget.dataset;
            if (name == this.data.content.dataType) return;
            this.setData({
                "content.dataType": name
            })
            this.getList(true)
        },
        changeType2({
            detail
        }) {
            this.setData({
                "content.where.type": detail,
            })
            this.getList(true)
        },
        changeTradefield({
            detail
        }) {
            this.setData({
                "content.where.tradefield": detail,
            })
            this.getList(true)
        },
        changeItemclass({
            detail
        }) {
            this.setData({
                "content.itemclass": detail,
            })
            this.getList(true)
        },
        changeSa_brandid({
            detail
        }) {
            this.setData({
                "content.where.sa_brandid": detail,
            })
            this.getList(true)
        },
    }
})