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({
                "content.dataid": wx.getStorageSync('userMsg').userid,
                "content.username": wx.getStorageSync('userMsg').name,
            })
        }
    },
    data: {
        "content": {
            enddate: new Date().toISOString().split('T')[0],
            unwriteoffamounttype: "订单",
            where: {}
        },
        pages: {
            pageNumber: 1,
            pageTotal: 1,
            pageSize: 20
        },
        list: [],
        total: 0
    },
    methods: {
        async getList(init = false) {
            if (init.detail != undefined) init = init.detail;
            let content = this.data.content,
                pages = this.data.pages;

            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) {
                pages.pageNumber = 1;
                pages.pageTotal = 1;
            }
            if (pages.pageNumber <= pages.pageTotal) _Http.basic({
                "id": 20231017084504,
                content: Object.assign(content, pages)
            }).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.zerotothree = CNY(v.zerotothree)
                    v.threetosix = CNY(v.threetosix)
                    v.sixtotwelve = CNY(v.sixtotwelve)
                    v.twelveup = CNY(v.twelveup)
                    v.total = CNY(v.total)
                    return v
                })
                pages.pageNumber++;
                pages.pageTotal = res.pageTotal;
                this.setData({
                    list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
                    pages,
                    total: res.total
                })
            })
            if (init) _Http.basic({
                "id": 20231016211904,
                content
            }).then(res => {
                console.log("回款分析图表", res)
                if (res.code != '1') return wx.showToast({
                    title: res.data,
                    icon: "none"
                })
                this.initChart(res.data)
            })
        },
        toDetail(e) {
            let content = this.data.content;
            content.sys_enterpriseid = e.currentTarget.dataset.item.sys_enterpriseid;
            content.enterprisename = e.currentTarget.dataset.item.enterprisename;
            wx.navigateTo({
                url: '/salesPanel/FinancialCollectionAnalysis/detail?content=' + JSON.stringify(content)
            })
        },
        initChart(data) {
            let dividend = wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000,
                list = [{
                    name: "0-3月未回款金额(万元)",
                    color: "#5B8FF9"
                }, {
                    name: "3-6月未回款金额(万元)",
                    color: "#5AD8A6"
                }, {
                    name: "6-12月未回款金额(万元)",
                    color: "#5D7092"
                }, {
                    name: "12月以上未回款金额(万元)",
                    color: "#F6BD16"
                }];

            let series = list.map(item => ({
                name: getApp().globalData.Language.getMapText(item.name),
                type: 'bar',
                label: {
                    show: true
                },
                emphasis: {
                    focus: 'series'
                },
                itemStyle: {
                    color: item.color
                },
                data: ['开票', '出货', '订单'].map(type => {
                    let filtered = data.filter(d => d.type === type && d.key.includes(item.name.split('(')[0]));
                    return filtered.length ? (filtered[0].value / dividend).toFixed(2) : 0;
                })
            }));
            let option = {
                tooltip: {
                    trigger: 'axis',
                    confine: true, // Ensure tooltip stays within the chart area
                    formatter: function (params) {
                        let tooltipText = '';
                        changeUnwriteoffamounttype(['开票', '出货', '订单'][params[0].dataIndex])
                        params.forEach((item, index) => {
                            tooltipText += `${index==0?item.axisValue+'\n':''}${item.marker}${item.seriesName}: ${item.value}\n`;
                        });
                        return tooltipText;
                    },
                    textStyle: {
                        fontSize: 10,
                    }
                },
                legend: {
                    data: list.map(item => getApp().globalData.Language.getMapText(item.name))
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value'
                },
                yAxis: {
                    type: 'category',
                    data: ['开票', '出货', '订单'].map(v => getApp().globalData.Language.getMapText(v)),
                    inverse: false // Disable automatic sorting
                },
                series
            };
            let countDown = null,
                that = this;

            function changeUnwriteoffamounttype(type) {
                if (countDown) return;
                countDown = setTimeout(() => {
                    clearTimeout(countDown)
                    countDown = null;
                    if (type != that.data.content.unwriteoffamounttype) {
                        that.setData({
                            "content.unwriteoffamounttype": type,
                            "pages.pageNumber": 1
                        })
                    }
                    that.getList()
                }, 200)
            };
            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)
        },
        showExplain(e) {
            const {
                name
            } = e.currentTarget.dataset;
            getApp().globalData.Language.modeBoxPrompts(getApp().globalData.Language.getMapText('统计到当前查询时间为止的') + name + "(" + getApp().globalData.Language.getMapText('审核状态') + ")")
        },
    }
})