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: {
        mode: {
            type: String
        }
    },
    options: {
        addGlobalClass: true
    },
    lifetimes: {
        attached: function () {
            getApp().globalData.Language.getLanguagePackage(this)
            this.setData({
                siteid: wx.getStorageSync('userMsg').siteid,
                "content.dataid": wx.getStorageSync('userMsg').userid,
                "content.username": wx.getStorageSync('userMsg').name,
            })
        }
    },
    data: {
        "content": {
            dateType: "",
            pageNumber: 1,
            pageTotal: 1,
            enddate: new Date().toISOString().split('T')[0],
            where: {}
        },
        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;
            if (init) {
                content.pageNumber = 1;
                content.pageTotal = 1;
            }
            if (content.pageNumber > content.pageTotal) return;
            const dividend = wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000,
                getMapText = getApp().globalData.Language.getMapText;
            let ids = {
                '已下单未出货分析': 2025040113445202,
                '近12月延期出货情况分析': 20231012163804,
                '未出货已延期情况分析': 2024120513564702
            }
            console.log(this.properties.mode, ids[this.properties.mode])
            _Http.basic({
                "id": ids[this.properties.mode],
                content
            }).then(res => {
                this.selectComponent('#ListBox').automaticSetHei();
                this.selectComponent('#ListBox').RefreshToComplete();
                console.log(this.properties.mode, res)
                if (res.code != '1') return wx.showToast({
                    title: res.data,
                    icon: "none"
                })

                res.data = res.data.map(v => {
                    v.marketprice = CNY(v.marketprice)
                    v.amount = CNY(v.amount)
                    v.invoiceamount = CNY(v.invoiceamount)
                    v.uninvoiceamount = CNY(v.uninvoiceamount)
                    v.writeoffamount = CNY(v.writeoffamount)
                    v.unwriteoffamount = CNY(v.unwriteoffamount)
                    v.returnamount = CNY(v.returnamount)
                    v.price = CNY(v.price)
                    v.logisticsamount = CNY(v.logisticsamount)
                    v.expanded = false;
                    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
                })
                const modifiedData = res.data[0].trend.map(v => {
                    if (v.key === '一季以上') {
                        v.key = getMapText('一季') +
                            '\n' + getMapText('以上');
                    }
                    return v;
                });
                this.initChart(modifiedData, getMapText);
            })
        },
        changeExpanded(e) {
            const {
                index
            } = e.currentTarget.dataset;
            this.setData({
                [`list[${index}].expanded`]: !this.data.list[index].expanded
            })
        },
        initChart(data, getMapText) {
            let countDown = null,
                that = this;

            function changeUnwriteoffamounttype(type) {
                if (countDown) return;
                countDown = setTimeout(() => {
                    clearTimeout(countDown)
                    countDown = null;
                    console.log(type, that.data.content.dateType)
                    if (type != that.data.content.dateType) {
                        that.setData({
                            "content.dateType": type,
                            "content.pageNumber": 1
                        })
                    }
                    that.getList()
                }, 200)
            };

            let option = {
                tooltip: {
                    formatter: function (params) {
                        changeUnwriteoffamounttype(['一周', '一月', '一季', '一季以上'][params.data.sequence - 1]);
                    },
                },
                xAxis: {
                    max: 'dataMax'
                },
                yAxis: {
                    type: 'category',
                    data: data.map(v => getMapText(v.key)),
                    inverse: true,
                    animationDuration: 300,
                    animationDurationUpdate: 300
                },
                series: [{
                    name: getMapText('订单行数'),
                    type: 'bar',
                    data: data,
                    label: {
                        show: true,
                        position: 'right',
                        valueAnimation: true
                    },
                    itemStyle: {
                        color: '#6395FA' // Set the color to #6395FA
                    }
                }],
                legend: {
                    show: true,
                    left: 'left', // Position the legend in the top-left corner
                    top: 'top'
                },
                grid: {
                    top: 40, // Adjust the top margin to reduce the space between series and legend
                    left: '10%',
                    right: '10%',
                    bottom: '10%'
                },
                animationDuration: 0,
                animationDurationUpdate: 3000,
                animationEasing: 'linear',
                animationEasingUpdate: 'linear'
            };
            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.enddate": detail
            })
            this.getList(true)
        },
    }
})