const _Http = getApp().globalData.http,
    currency = require("../../utils/currency"),
    CNY = (value, symbol = "", precision = 2) => currency(value, {
        symbol,
        precision
    }).format(),
    conversion = n => {
        const integer = (n + '').split(".")[0] + '',
            length = integer.length,
            regexp = /(?:\.0*|(\.\d+?)0+)$/
        if (length <= 4) {
            const index = 4 - length;
            return { //元
                show: CNY(n, "￥", index).replace(regexp, '$1'),
                value: CNY(n, '￥')
            }
        } else if (length <= 8) {
            return { //万-千万

                show: CNY(currency(n).divide(wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).replace(regexp, '$1') + getApp().globalData.Language.getMapText('万元'),
                value: CNY(n)
            }
        } else {
            return { //亿
                show: CNY(currency(n).divide(100000000)).replace(regexp, '$1') + getApp().globalData.Language.getMapText('亿'),
                value: CNY(n)
            }
        }
    };
import * as echarts from '../ec-canvas/echarts';

Page({
    data: {
        showFiltrate: false,
        pageMsg: {
            pageNumber: 1,
            pageSize: 20,
            pageTotal: 1,
            total: 0,
            signdate_due: ""
        },
        "where": {
            "begindate": "",
            "enddate": "",
            "sa_saleareaid": ""
        },
        dateTypes: ["全部", "近一年", "近九个月", "近六个月", "近三个月"],
        content: {
            nocache: true,
            type: 0,
            dateType: '全部',
            where: {
                begdate: "",
                enddate: "",
                tradefield: "",
                isleave: 1
            }
        },
        filtratelist: [],
        firstTwelveMonths: {
            dealaccuracyrate: '0%',
            totaldealamount: 0,
            totaldeviationamount: 0,
            totalsignamount_due: 0
        },
        projectPhases: [],
        stagename: ['全部'],
        projectPhasesShow: false,
        chartDataUnfinish: 1,
        ComingYearUnfinish: 1
    },
    onLoad(options) {
        _Http.basic({
            "id": 20221223141802,
            "content": {
                "pageNumber": 1,
                "pageSize": 9999,
                "where": {
                    "condition": ""
                }
            }
        }, false).then(res => {
            console.log("获取领域", res)
            let filtratelist = this.data.filtratelist
            if (res.code == '1') {
                filtratelist.splice(filtratelist.length - 2, 0, {
                    label: "领域",
                    index: null,
                    showName: "tradefield", //显示字段
                    valueKey: "tradefield", //返回Key
                    selectKey: "tradefield", //传参 代表选着字段 不传参返回整个选择对象
                    value: "", //选中值
                    list: res.data
                })
                this.setData({
                    filtratelist
                })
            }
        })
        getApp().globalData.Language.getLanguagePackage(this, '销售漏斗');
        _Http.basic({
            "id": 20221128143604,
            "content": {
                "pageNumber": 1,
                "pageSize": 99,
                "where": {
                    "condition": "",
                    "allprojecttype": "",
                    "projecttype": ""
                }
            }
        }).then(res => {
            if (res.code == 1) {
                try {
                    if (!this.data.isHY) {
                        this.setData({
                            "sa_projstagemagid": res.data[0].sa_projstagemagid
                        })
                    }
                } catch (error) {

                }
                let list = res.data;
                list.unshift({
                    stagename: '全部'
                })
                this.setData({
                    projectPhases: [{
                        label: "项目阶段",
                        index: [0],
                        type: "checkbox",
                        interrupt: true,
                        showName: "stagename", //显示字段
                        valueKey: "stagename", //返回Key
                        selectKey: "stagename", //传参 代表选着字段 不传参返回整个选择对象
                        value: ['全部'], //选中值
                        list
                    }],
                    stagename: ['全部']
                })
            }
        })
        this.setData({
            isHY: ['HY', "YOSTEST1"].includes(wx.getStorageSync('userMsg').siteid),
            "content.dataid": wx.getStorageSync('userMsg').userid,
            username: wx.getStorageSync('userMsg').name,
        })
        this.setComingYear()

        this.setChartData();
        let organization = this.selectComponent("#organization")
        organization.setData({
            isleave: 1
        })
        organization.initDepAndUser()
    },
    openFiltrate() {
        this.setData({
            showFiltrate: true
        })
    },
    handleFilter({
        detail
    }) {
        if (detail.name == "close") return;
        if (detail.name == 'reset') {
            this.selectComponent("#organization").setData({
                isleave: 1
            })
            this.selectComponent("#organization").initDepAndUser()
            this.setData({
                'content.dataid': wx.getStorageSync('userMsg').userid,
                'content.type': 0,
                'content.where.isleave': 1,
                'content.where.tradefield': "",
                username: wx.getStorageSync('userMsg').name,
            })
        } else {
            let active = this.selectComponent("#organization").data.result,
                isleave = this.selectComponent("#organization").data.isleave;
            let type = active.userid ? 0 : 1,
                dataid = type == 0 ? active.userid : active.sa_saleareaid;
            this.setData({
                'content.dataid': dataid,
                'content.type': type,
                'content.where.tradefield': detail.tradefield,
                'content.where.isleave': isleave,
                username: active.name,
            })
        }
        this.setChartData();
        this.setComingYear();
    },
    setChartData() {
        this.setData({
            statistics: []
        })
        let content = JSON.parse(JSON.stringify(this.data.content));
        content.where.unfinish = this.data.chartDataUnfinish;
        content.dateType = {
            "全部": 99,
            "近一年": 1,
            "近九个月": 2,
            "近六个月": 3,
            "近三个月": 4,
        } [content.dateType] || 0;
        _Http.basic({
            "id": 20230630151504,
            content
        }).then(res => {
            console.log("漏斗数据", res)
            if (res.code != '1') return wx.showToast({
                title: res.msg,
                icon: "none"
            })
            if (res.data.length) res.data.pop();
            let full = Math.max(...res.data.map(v => v.wide));
            let statistics = res.data.map((v, i) => {
                v.action = getApp().globalData.Language.getMapText(v.stagename)
                v.zhl = i == 0 ? '' : getApp().globalData.Language.getMapText('转换率') + `:${(v.zhl * 100).toFixed(2)}%`
                v.percent = v.wide / full;
                v.totalinvestment = conversion(v.totalinvestment).value
                v.budgetary = conversion(v.budgetary).value
                v.signamount_due = conversion(v.signamount_due).value
                if (i == 0) {
                    v.totaldealamount = CNY(v.totaldealamount, '￥')
                    v.totalsignamount_due = CNY(v.totalsignamount_due, '￥')
                }
                return v
            })
            this.setData({
                statistics
            });
            try {
                this.selectComponent("#TimeRange").onCancel()
            } catch (error) {

            }
            let damRiver = null,
                that = this;

            function updateList(params) {
                clearTimeout(damRiver);
                damRiver = setTimeout(() => {
                    that.setData({
                        "sa_projstagemagid": params.sa_projstagemagid,
                        stagename: [params.stagename],
                        showIndex: params.rowindex - 1
                    })
                    that.getList(true);
                }, 200);
            }
            let option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        let data = statistics[params.dataIndex];
                        if (!that.data.isHY) {
                            updateList(data);
                        }
                        let tooltipText = params.name + '\n';
                        tooltipText += `${getApp().globalData.Language.getMapText('项目总数')}: ${data.projectqty}\n${data.zhl}`;
                        return tooltipText;
                    }
                },
                legend: {
                    data: statistics.map(v => getApp().globalData.Language.getMapText(v.stagename))
                },
                series: [{
                    name: getApp().globalData.Language.getMapText('项目阶段'),
                    type: 'funnel',
                    left: '10%',
                    top: 60,
                    bottom: 0, // Adjusted to remove remaining space at the bottom
                    width: '80%',
                    min: 0,
                    max: full,
                    minSize: '0%',
                    maxSize: '100%',
                    sort: 'descending',
                    gap: 2,
                    labelLine: {
                        length: 10,
                        lineStyle: {
                            width: 1,
                            type: 'solid'
                        }
                    },
                    itemStyle: {
                        borderColor: '#fff',
                        borderWidth: 1
                    },
                    emphasis: {
                        label: {
                            fontSize: 20
                        }
                    },
                    data: statistics.map(v => {
                        return {
                            value: v.wide,
                            name: getApp().globalData.Language.getMapText(v.stagename),
                            label: {
                                show: true,
                                position: 'inside',
                                formatter: `{b}${(v.zhl?':':'')+v.zhl}`
                            }
                        }
                    })
                }]
            };
            this.chartComponent = this.selectComponent('#funnel');
            this.chartComponent.init((canvas, width, height, dpr) => {
                const chart = echarts.init(canvas, null, {
                    width,
                    height,
                    devicePixelRatio: dpr
                });
                chart.setOption(option);
                return chart;
            });
            if (!this.data.isHY) {
                this.setData({
                    sa_projstagemagid: res.data[0].sa_projstagemagid,
                    showIndex: 0
                })
                this.getList(true)
            }
        })
    },
    onCheckboxChange(e) {
        this.setData({
            chartDataUnfinish: this.data.chartDataUnfinish == 0 ? 1 : 0
        })
        this.setChartData()
        if (!this.data.isHY) this.setComingYear();
    },
    onCheckboxChange1(e) {
        this.setData({
            ComingYearUnfinish: this.data.ComingYearUnfinish == 0 ? 1 : 0
        })
        this.setComingYear()
    },
    changeDate({
        detail
    }) {
        this.setData({
            "content.dateType": detail.dateType,
            "content.where.begdate": detail.begdate || "",
            "content.where.enddate": detail.enddate || ""
        })
        this.setChartData()
        if (!this.data.isHY) this.setComingYear();
    },
    setComingYear() {
        let pageMsg = this.data.pageMsg;
        let content = Object.assign(JSON.parse(JSON.stringify(this.data.content)), this.data.pageMsg)
        if (this.data.isHY) {
            content.where.unfinish = this.data.ComingYearUnfinish;
            delete content.dateType;
            content.where.begdate = '';
            content.where.enddate = '';
        } else {
            content.where.unfinish = this.data.chartDataUnfinish;
        }
        pageMsg.signdate_due = '';
        content.pageNumber = 1;
        content.stagename = this.data.stagename[0] == '全部' || this.data.stagename[0] == getApp().globalData.Language.getMapText("全部") ? [] : this.data.stagename;
        _Http.basic({
            "id": 20241028162104,
            content
        }).then(res => {
            console.log("前12个月总数据", res)
            if (res.code != '1') return wx.showToast({
                title: res.msg,
                icon: "none"
            })
            let arr = []

            if (res.data[0].extradata.array) {
                const array = res.data[0].extradata.array;
                arr = [array.map(v => {
                    return {
                        name: getApp().globalData.Language.getMapText('预计签约金额'),
                        value: (v.signamount_due / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).toFixed(0) - 0,
                        date: v.signdate_due
                    }
                }), array.map(v => {
                    return {
                        name: getApp().globalData.Language.getMapText('预计成交金额'),
                        value: (v.dealamount_due / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).toFixed(0) - 0,
                        date: v.signdate_due
                    }
                })];
            }
            try {
                if (res.data[0].extradata) {
                    let data = res.data[0].extradata
                    this.setData({
                        firstTwelveMonths: {
                            "dealTotalCount": data.dealTotalCount, //成交项目数
                            "failTotalCount": data.failTotalCount, //失败项目数
                            "dealRate": (data.dealRate * 100).toFixed(2) + '%', //项目成交率
                            "positiveCount": data.positiveCount, //预计成交正偏差项目数合计
                            "positiveOffsetAmount": CNY(((data.positiveOffsetAmount || 0) / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).toFixed(2), ''), //预计成交正偏差金额合计
                            "negativeCount": data.negativeCount, //预计成交负偏差项目数合计
                            "negativeOffsetAmount": CNY(((data.negativeOffsetAmount || 0) / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).toFixed(2), ''), //预计成交负偏差金额合计
                            "offsetCount": data.offsetCount, //预计成交准确项目数
                            "rightRate": (data.rightRate * 100).toFixed(2) + '%', //预测额成交准确率
                            "dealAmount": CNY(((data.dealAmount || 0) / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).toFixed(2), ''), //项目成交金额合计
                            "signAmount": CNY(((data.signAmount || 0) / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).toFixed(2), ''), //预计签约金额合计
                            "sumdealamount_due": CNY(((data.sumdealamount_due || 0) / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).toFixed(2), '￥'), //预计项目成交金额合计
                            "sumsignamount_due": CNY(((data.sumsignamount_due || 0) / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000)).toFixed(2), '￥'), //预计预计签约金额合计
                        },
                    })
                }
            } catch (error) {}
            if (this.data.isHY) {
                res.data = res.data.map(v => {
                    v.progress = v.stage / v.totalstage * 100;
                    v.signamount_due = CNY(v.signamount_due, "￥")
                    v.dealamount = CNY(v.dealamount, "￥")
                    return v
                })
                pageMsg.pageNumber = res.pageNumber + 1
                pageMsg.pageSize = res.pageSize
                pageMsg.pageTotal = res.pageTotal
                pageMsg.total = res.total
                pageMsg.sumsignamount_due = CNY(res.data[0].extradata.sumsignamount_due / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000).toFixed(2), "￥")
                pageMsg.sumdealamount_due = CNY(res.data[0].extradata.sumdealamount_due / (wx.getStorageSync('languagecode') == 'ZH' ? 10000 : 1000).toFixed(2), "￥")
                this.setData({
                    pageMsg,
                    list: res.data
                })
                let option = {
                    color: ['#3875F9', '#F29B3A'], // Custom colors for the bars
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                        formatter: function (params) {
                            updateList(params);
                            let tooltipText = params[0].name + '\n';
                            params.forEach(item => {
                                tooltipText += `${item.seriesName}: ${item.value}\n`;
                            });
                            return tooltipText;
                        }
                    },
                    grid: {
                        left: '15%', // Adjusted to leave more space for Y-axis labels
                        right: '10%',
                        bottom: '15%', // Adjusted to leave space for rotated X-axis labels
                        top: '16%' // Increased top margin to reduce the height of the main chart area
                    },
                    legend: {
                        data: ['预计签约金额(万元)', '预计成交金额(万元)'].map(v => getApp().globalData.Language.getMapText(v))
                    },
                    xAxis: [{
                        type: 'category',
                        data: arr[0].map(v => v.date),
                        axisPointer: {
                            type: 'shadow'
                        },
                        axisLabel: {
                            rotate: 45, // Rotate X-axis labels by 45 degrees
                            align: 'right' // Align labels to the right for better readability
                        }
                    }],
                    yAxis: [{
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}',
                            rotate: 45, // Rotate X-axis labels by 45 degrees
                        }
                    }],
                    series: [{
                            name: getApp().globalData.Language.getMapText('预计签约金额(万元)'),
                            type: 'bar',
                            tooltip: {
                                valueFormatter: function (value) {
                                    return value;
                                }
                            },
                            data: arr[0].map(v => v.value)
                        },
                        {
                            name: getApp().globalData.Language.getMapText('预计成交金额(万元)'),
                            type: 'bar',
                            tooltip: {
                                valueFormatter: function (value) {
                                    return value;
                                }
                            },
                            data: arr[1].map(v => v.value)
                        }
                    ]
                };
                this.chartComponent = this.selectComponent('#barGraph');
                this.chartComponent.init((canvas, width, height, dpr) => {
                    const chart = echarts.init(canvas, null, {
                        width,
                        height,
                        devicePixelRatio: dpr
                    });
                    chart.setOption(option);
                    return chart;
                });
            }
            let damRiver = null,
                that = this;

            function updateList(params) {
                clearTimeout(damRiver);
                damRiver = setTimeout(() => {
                    that.setData({
                        "pageMsg.signdate_due": params[0].name,
                        "pageMsg.sumsignamount_due": CNY(params[0].value, "￥"),
                        "pageMsg.sumdealamount_due": CNY(params[1].value, "￥"),
                    })
                    that.getList(true)
                }, 200);
            }
        })
    },
    getList(init = false) {
        if (init.detail != undefined) init = init.detail;
        let pageMsg = this.data.pageMsg;
        if (init) {
            pageMsg.pageNumber = 1;
            pageMsg.pageTotal = 1;
        }
        if (pageMsg.pageNumber > pageMsg.pageTotal) return;
        let content = Object.assign(JSON.parse(JSON.stringify(this.data.content)), pageMsg)
        content.stagename = this.data.stagename[0] == '全部' || this.data.stagename[0] == getApp().globalData.Language.getMapText("全部") ? [] : this.data.stagename;
        if (this.data.isHY) {
            content.where.unfinish = this.data.ComingYearUnfinish;
            delete content.dateType
        } else {
            content.where.unfinish = this.data.chartDataUnfinish;
            content.sa_projstagemagid = this.data.sa_projstagemagid;
            content.dateType = {
                "全部": 99,
                "近一年": 1,
                "近九个月": 2,
                "近六个月": 3,
                "近三个月": 4
            } [content.dateType] || 0;
        }
        _Http.basic({
            "id": this.data.isHY ? 20241028162104 : 20230719085004,
            content
        }).then(res => {
            console.log("获取项目列表", res)
            this.setData({
                list: res.data
            })
            pageMsg.pageNumber = res.pageNumber + 1
            pageMsg.pageSize = res.pageSize
            pageMsg.pageTotal = res.pageTotal
            pageMsg.total = res.total
            try {
                res.data = res.data.map(v => {
                    v.progress = v.stage / v.totalstage * 100;
                    v.signamount_due = CNY(v.signamount_due, "￥")
                    v.dealamount = CNY(v.dealamount, "￥")
                    return v
                })
            } catch (error) {

            }
            this.setData({
                list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
                pageMsg
            })
        })
    },
    openProjectPhases() {
        this.setData({
            projectPhasesShow: true
        })
    },
    phasesInterrupt({
        detail
    }) {
        if (detail.item.stagename == '全部') {
            detail.list[0].index = [0];
            detail.list[0].value = ['全部'];
        } else {
            if (detail.list[0].index.length) {
                detail.list[0].index = detail.list[0].index.filter(v => v);
                detail.list[0].value = detail.list[0].index.filter(v => v != '全部');
            } else {
                detail.list[0].index = [0];
                detail.list[0].value = ['全部'];
            }
        }
        this.setData({
            projectPhases: detail.list
        })
    },
    phasesHandleFilter({
        detail
    }) {
        if (detail.name != "confirm") return;
        let stagename = ['全部']
        try {
            if (detail.stagename[0] != 0) {
                stagename = detail.stagename.map(v => this.data.projectPhases[0].list[v].stagename)
            }
        } catch (error) {

        }
        this.selectComponent('#Filtrate').setShowArrText(stagename)
        this.setData({
            stagename
        })
        this.setComingYear()
    }
})