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

Page({
    data: {
        showFiltrate: false,
        pageIndex: 0,
        admin: false,
        tabsActive: 0,
        active: null,
        tabbarList: [{
            icon: "icon-guanlian-bianji",
            label: "添加项目"
        }, {
            icon: "icon-guanlian-fuzhi",
            label: "移除项目"
        }],
        "content": {
            "type": 1,
            "dataid": wx.getStorageSync('userMsg').sa_saleareaid,
            "baseonproject": 1,
            "title": ""
        },
        isonlydep: false
    },
    onLoad(options) {
        this.setData({
            sa_salesforecastbillid: options.id
        })
        if (options.admin == 'true') this.setData({
            admin: true
        })
        let tabsList = [{
            label: "项目产品清单",
            icon: "icon-tabchanpin",
            model: "#Project"
        }, {
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        }, {
            label: "操作记录",
            icon: "icon-tabcaozuojilu1",
            model: "#Record"
        }];

        const {
            isdatafollowup,
            istask,
            isdatatag,
            isdatateam
        } = wx.getStorageSync('auth')[options.admin == 'true' ? 'finishforecastadmin' : 'finishforecast'];

        console.log(wx.getStorageSync('auth')[options.admin == 'true' ? 'finishforecastadmin' : 'finishforecast'])
        if (isdatafollowup) tabsList.push({
            label: "跟进动态",
            icon: "icon-tabgenjinjilu",
            model: "#Trace"
        })
        if (istask) tabsList.push({
            label: "任务",
            icon: "icon-tabrenwu",
            model: "#Work"
        })
        this.setData({
            tabsList,
            isdatatag,
            isdatateam
        })
        this.getDetail();
        if (isdatatag) this.getTags();
        if (isdatateam) this.getGroup()
        this.partialRenewal();
        getApp().globalData.Language.getLanguagePackage(this, '预测填报');
    },
    switchOnChange({
        detail
    }) {
        this.setData({
            isonlydep: detail
        });
        if (detail) this.setData({
            active: null,
            "content.type": 1,
            "content.dataid": wx.getStorageSync('userMsg').sa_saleareaid,
        });
        this.selectComponent("#organization").initDepAndUser();
        this.getRests();
    },
    /* 切换 */
    onChange(e) {
        this.setData({
            pageIndex: e.detail.index
        })
    },
    openFiltrate() {
        this.setData({
            showFiltrate: true
        })
    },

    onReady() {
        if (this.data.admin) this.selectComponent("#organization").initDepAndUser();
    },
    handleFilter({
        detail
    }) {
        if (detail.name == 'reset') {
            this.selectComponent("#organization").initDepAndUser()
            this.setData({
                active: null,
                "content.dataid": wx.getStorageSync('userMsg').sa_saleareaid,
                'content.type': 1,
                isonlydep: false
            })
        } else {
            let active = this.selectComponent("#organization").data.result;
            let type = active.userid ? 0 : 1,
                dataid = type == 0 ? active.userid : active.sa_saleareaid
            this.setData({
                active,
                'content.dataid': dataid,
                'content.type': type
            })
        }
        this.getRests();
    },
    getRests() {
        let content = this.data.content;
        content.isonlydep = this.data.isonlydep ? 1 : 0
        _Http.basic({
            "id": 20230705144804,
            content
        }).then(res => {
            console.log("其他预测单", res)
            if (res.code != '1') wx.showToast({
                title: res.msg,
                icon: "none"
            });
            if (res.data.allprojectamount) res.data.allprojectamount = CNY(res.data.allprojectamount)
            res.data.data = res.data.data.filter(v => v.sa_salesforecastbillid).map(v => {
                v.showAmount = CNY(v.projectamount)
                return v
            })
            this.setData({
                rests: res.data
            })
        })
    },
    getDetail() {
        _Http.basic({
            "id": 20230705144704,
            "content": {
                "sa_salesforecastbillid": this.data.sa_salesforecastbillid
            }
        }).then(res => {
            console.log("预测详情", res)
            if (res.code != '1') wx.showToast({
                title: res.msg,
                icon: "none"
            });
            res.data.projectamount = CNY(res.data.projectamount)
            this.setData({
                detail: res.data,
                'content.title': res.data.title,
                isLeader: res.data.userid == wx.getStorageSync('userMsg').userid
            });
            if (!this.data.isLeader) getApp().agentOrNot("sa_salesforecastbill", this.data.sa_salesforecastbillid).then(s => {
                console.log("代理人数据", s)
                this.setData({
                    isLeader: s.data.editable == 1 || this.selectComponent("#Group").data.editable == 1
                })
            })
            if (this.data.admin) this.getRests();
        })
    },
    tabbarOnClick({
        detail
    }) {
        switch (detail.label) {
            case "添加项目":
                this.toAddProject();
                break;
            case "移除项目":
                wx.navigateTo({
                    url: `/packageA/select/project/select2?params=${JSON.stringify({
                        "id": "20230705144904",
                        "content": {
                            nocache: true,
                            sa_salesforecastbillid:this.data.sa_salesforecastbillid,
                            pageSize: 20,
                            "where":{
                                "condition":""
                            }
                        }
                        })}&radio=true`,
                })
                getApp().globalData.handleSelect = this.deteleProject.bind(this);
                break;
        }
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    toAddProject() {
        wx.navigateTo({
            url: `/packageA/select/project/select2?params=${JSON.stringify({
                    "id": 20230705145604,
                    "content": {
                        nocache:true,
                        sa_salesforecastbillid:this.data.sa_salesforecastbillid,
                        "where":{
                            "condition":""
                        }
                    }
            })}`,
        });
        getApp().globalData.handleSelect = this.addProject.bind(this);
    },
    /* 添加项目 */
    addProject({
        list
    }) {
        let that = this;
        wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content: getApp().globalData.Language.joint([{
                t: 1,
                v: '是否确认添加',
                r: " "
            }, {
                v: list.length,
                r: " "
            }, {
                t: 1,
                v: '个项目',
                r: "?"
            }]),
            cancelText: getApp().globalData.Language.getMapText('取消'),
            confirmText: getApp().globalData.Language.getMapText('确定'),
            complete: ({
                confirm
            }) => {
                if (confirm) _Http.basic({
                    id: 20230705145104,
                    content: {
                        sa_salesforecastbillid: that.data.sa_salesforecastbillid,
                        "ownertable": "sa_project",
                        salesforecastproject: list.map(v => {
                            return {
                                ownerid: v.sa_projectid,
                                ownertable: "sa_project",
                                discountrate: v.discountrate,
                                sa_salesforecastprojectid: 0
                            }
                        })
                    }
                }).then(res => {
                    console.log("添加项目", res)
                    wx.showToast({
                        title: res.code == '1' ? getApp().globalData.Language.getMapText('添加成功') : res.msg,
                        icon: "none"
                    });
                    if (res.code == '1') {
                        that.setData({
                            tabsActive: that.data.tabsList.findIndex(v => v.label == '项目产品清单')
                        });
                        setTimeout(() => {
                            wx.navigateBack();
                            setTimeout(() => {
                                that.selectComponent('#Project').getList(that.data.sa_salesforecastbillid, false);
                            }, 300)
                        }, 300)
                    }
                })
            }
        })
    },
    /* 删除项目 */
    deteleProject({
        item
    }) {
        let that = this;
        wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content: getApp().globalData.Language.getMapText('是否确认移除') + `“${item.projectname}”`,
            cancelText: getApp().globalData.Language.getMapText('取消'),
            confirmText: getApp().globalData.Language.getMapText('确定'),
            complete: ({
                confirm
            }) => {
                if (confirm) _Http.basic({
                    "id": 20230705145304,
                    "content": {
                        "sa_salesforecastbillid": that.data.sa_salesforecastbillid,
                        "sa_salesforecastprojectids": [item.sa_salesforecastprojectid]
                    }
                }).then(res => {
                    console.log("移除项目", res)
                    if (res.code != '1') return wx.showToast({
                        title: res.msg,
                        icon: "none"
                    });
                    that.selectComponent("#Project").getList(that.data.sa_salesforecastbillid);
                    setTimeout(() => {
                        wx.showToast({
                            title: getApp().globalData.Language.getMapText('已移除') + `“${item.projectname}”`,
                            icon: "none"
                        })
                        let page = getCurrentPages().find(v => v.__route__ == 'packageA/select/project/select2');
                        if (page) page.deteleItem(item.sa_projectid);
                        that.getDetail();
                    }, 500)
                })
            }
        })
    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags();
    },
    //局部数据更新 tabs
    partialRenewal(init = false) {
        let model = this.data.tabsList[this.data.tabsActive].model;
        if (model) {
            let Component = this.selectComponent(model),
                {
                    total,
                    pageNumber,
                    pageTotal
                } = Component.data.content,
                id = this.data.sa_salesforecastbillid;
            if (model == "#Files") init = true;
            if (total == null || init) {
                Component.getList(id, init);
            } else if (pageNumber <= pageTotal) {
                Component.getList(id, false);
            }
        }
    },
    onReachBottom() {
        this.partialRenewal();
    },
    //更新团队成员
    getGroup() {
        this.selectComponent("#Group").getList().then(res => {
            if (!this.data.isLeader) this.setData({
                isLeader: this.selectComponent("#Group").data.editable == 1
            })
        });
    },
    onUnload() {
        let page = getCurrentPages()[getCurrentPages().length - 2];
        if (page.getRests) return page.getRests();
        let content = JSON.parse(JSON.stringify(page.data.content));
        content.pageSize = (content.pageNumber - 1) * content.pageSize;
        content.pageNumber = 1;
        _Http.basic({
            id: page.data.admin ? 20230705144604 : 20230706092304,
            content
        }).then(res => {
            console.log("更新预测", res);
            res.data = res.data.map(v => {
                v.showAmount = CNY(v.projectamount)
                return v
            })
            if (res.code == '1') page.setData({
                list: res.data,
                "content.total": res.total
            })
        })
    }
})