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],
            where: {}
        },
        accounts: [],
        accountno: "",
    },
    methods: {
        async getList(init = false) {
            let accounts = []
            if (!this.data.accounts.length) accounts = await _Http.basic({
                "id": 20221008134803,
                "content": {
                    "isExport": 0,
                    "pageNumber": 1,
                    "pageSize": 100,
                    "where": {
                        "condition": ""
                    }
                },
            })
            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;
            let dividend = wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000;

            try {
                content.accountno = accounts.data[0].accountno
                this.setData({
                    accounts: accounts.data.map(v => {
                        if (Math.abs(v.balance) > dividend) {
                            v.balance = CNY(v.balance / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000))
                            v.conversion = true;
                        } else {
                            v.balance = CNY(v.balance)
                            v.conversion = false;
                        }
                        v.remarks = v.accountname
                        v.value = v.accountno
                        return v
                    }),
                    content
                })
            } catch (error) {

            }
            _Http.basic({
                "id": 20231019151704,
                content
            }).then(res => {
                console.log("客户余额", res)
                this.selectComponent("#Filtrate").onCancel();
                if (res.code != '1') return wx.showToast({
                    title: res.data,
                    icon: "none"
                })
                this.setData({
                    accounts: res.data.accountclass.map(v => {
                        if (Math.abs(v.balance) > dividend) {
                            v.balance = CNY(v.balance / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000))
                            v.conversion = true;
                        } else {
                            v.balance = CNY(v.balance)
                            v.conversion = false;
                        }
                        v.remarks = v.accountname
                        v.value = v.accountno
                        return v
                    })
                })
                console.log("accounts", accounts)
                this.initChart(res.data)
            })
        },
        initChart(data) {
            const dividend = wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000,
                colors = ['#6CD2A1', '#5F9DFC', '#ECB937'],
                getMapText = getApp().globalData.Language.getMapText;
            const option = {
                color: colors,
                tooltip: {
                    trigger: 'axis',
                    confine: true, // Ensure tooltip stays within the chart area
                    formatter: function (params) {
                        let tooltipText = '';
                        params.forEach((item, index) => {
                            tooltipText += `${index==0?item.axisValue+'\n':''}${item.marker}${item.seriesName}: ${item.value}${item.seriesName == getMapText('同比增长率') ? '%' : ''}\n`;
                        });
                        return tooltipText;
                    },
                    textStyle: {
                        fontSize: 10, // Reduced font size
                        lineHeight: 14 // Adjusted line height for smaller tooltip height
                    }
                },
                legend: {
                    data: [`${getMapText('去年同期金额')}(${getMapText('万元')})`, `${getMapText('本期金额')}(${getMapText('万元')})`, `${getMapText('同比增长率')}`],
                    textStyle: {
                        fontSize: 10 // Reduced font size for legend
                    }
                },
                xAxis: [{
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: data.tbzzl.map(v => v.date),
                    axisLabel: {
                        interval: 0,
                        rotate: 45,
                        fontSize: 10 // Reduced font size for x-axis labels
                    }
                }],
                yAxis: [{
                        type: 'value',
                        name: '',
                        position: 'right',
                        offset: 80,
                        alignTicks: true,
                        axisLine: {
                            show: true,
                        },
                        axisLabel: {
                            formatter: '{value}',
                            fontSize: 10 // Reduced font size for y-axis labels
                        }
                    },
                    {
                        type: 'value',
                        name: '',
                        position: 'left',
                        alignTicks: true,
                        axisLine: {
                            show: false,
                        },
                        axisLabel: {
                            formatter: '{value}',
                            rotate: 45,
                            fontSize: 10 // Reduced font size for y-axis labels
                        }
                    },
                    {
                        type: 'value',
                        name: '',
                        position: 'right',
                        alignTicks: true,
                        offset: 80,
                        axisLine: {
                            show: false,
                            lineStyle: {
                                color: colors[1]
                            }
                        },
                        axisLabel: {
                            formatter: '{value}',
                            fontSize: 10 // Reduced font size for y-axis labels
                        }
                    },

                ],
                series: [{
                        name: `${getMapText('去年同期金额')}(${getMapText('万元')})`,
                        type: 'bar',
                        data: data.balance.filter(v => v.name == '去年同期金额').map(v => (v.value / dividend).toFixed(2)),
                        smooth: true
                    },
                    {
                        name: `${getMapText('本期金额')}(${getMapText('万元')})`,
                        type: 'bar',
                        yAxisIndex: 1,
                        data: data.balance.filter(v => v.name == '本年金额').map(v => (v.value / dividend).toFixed(2)),
                        smooth: true
                    },
                    {
                        name: getMapText('同比增长率'),
                        type: 'line',
                        yAxisIndex: 2,
                        data: data.tbzzl.map(v => (v.value * 100).toFixed(2)),
                        smooth: true
                    }
                ]
            };
            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)
        },
        changeType({
            detail
        }) {
            this.setData({
                "content.accountno": detail
            })
            this.getList(true)
        },
        changeType1(e) {
            let {
                item
            } = e.currentTarget.dataset;
            this.changeType({
                detail: item.accountno
            })
        },
        toDetail() {
            let content = this.data.content;
            wx.navigateTo({
                url: '/salesPanel/customerBlance/detail?content=' + JSON.stringify(content)
            })
        },
        showExplain(e) {
            const {
                name
            } = e.currentTarget.dataset;
            getApp().globalData.Language.modeBoxPrompts(getApp().globalData.Language.getMapText('统计到当前查询时间为止的客户') + getApp().globalData.Language.getMapText(name) + getApp().globalData.Language.getMapText('总余额'))
        },
    }
})