const _Http = getApp().globalData.http,
    currency = require("../../utils/currency"),
    CNY = value => currency(value, {
        symbol: "￥",
        precision: 2
    }).format();
Page({
    data: {
        loading: true,
        isLeader: false, //是否为负责人
        tabsActive: 1, //tabs 选中项
        sa_quotedpriceid: "",
        tabbarList: [],
        sColors: getApp().globalData.sColors,
    },
    onLoad(options) {
        getApp().globalData.Language.getLanguagePackage(this, '报价单详情');
        const appAuth = wx.getStorageSync('auth').woffer;
        let tabsList = [{
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }, {
            label: "产品明细折扣",
            icon: "icon-tabchanpin",
            model: "#Product"
        }, {
            label: "产品类别折扣",
            icon: "icon-tabchanpinleibie",
            model: "#PiscountType"
        }, {
            label: "其他费用",
            icon: "icon-tabkaipiaoxinxi",
            model: "#PettyExpense"
        }, {
            label: "历史报价",
            icon: "icon-tabbaojiadan",
            model: "#History"
        }, {
            label: "操作记录",
            icon: "icon-tabcaozuojilu1",
            model: "#Record"
        }, {
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        }];
        if (appAuth.isdatafollowup) tabsList.splice(5, 0, {
            label: "跟进动态",
            icon: "icon-tabgenjinjilu",
            model: "#Trace"
        })
        if (appAuth.istask) tabsList.push({
            label: "任务",
            icon: "icon-tabrenwu",
            model: "#Work"
        })
        this.setData({
            sa_quotedpriceid: options.sa_quotedpriceid,
            isAdmin: appAuth.options.some(v => v == "admin"), //是否具有管理权限
            options: appAuth.options, //权限列表
            tabsList,
            appAuth
        })
        this.getDetail(true);
    },
    getDetail(init = false) {
        _Http.basic({
            "id": 20221020165203,
            "version": 1,
            "content": {
                nocache: true,
                "sa_quotedpriceid": this.data.sa_quotedpriceid
            },
        }).then(res => {
            console.log("报价单详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.msg,
                icon: "none"
            });
            this.setPreview(res);
            this.setData({
                loading: false,
                detail: res.data,
            })
            this.setTabbarList();
            /* 更新列表数据 */
            let page = getCurrentPages().find(v => v.__route__ == 'packageA/offers/index');
            if (page) {
                let i = page.data.list.findIndex(v => v.sa_quotedpriceid == this.data.sa_quotedpriceid);
                if (i != -1 && page.data.list[i].status != res.data.status) page.setData({
                    [`list[${i}].status`]: res.data.status
                })
            }
            if (this.data.appAuth.isdatatag) this.getTags();
            if (this.data.appAuth.isdatateam) this.getGroup();
            this.partialRenewal();
        })
    },
    /* 设置显示字段 */
    setPreview(res) {
        let briefs = [{
            label: "报价类型",
            value: res.data.quotedpricetype
        }, {
            label: "项目",
            value: res.data.projectname
        }, {
            label: "客户",
            value: res.data.enterprisename
        }, {
            label: "是否特价",
            value: res.data.specialoffer == 1 ? '是' : '否'
        }, {
            label: "状态",
            value: getApp().globalData.Language.getMapText(res.data.status),
            style:`color:${this.data.sColors[res.data.status]}`
        }];
        //客户报价移除项目字段
        if (res.data.quotedpricetype == '客户报价') briefs.splice(1, 1);
        let list1 = [{
            label: "报价单号",
            value: res.data.billno
        }, {
            label: "报价类型",
            value: res.data.quotedpricetype
        }, {
            label: "产品系列",
            value: res.data.itemtype
        }, {
            label: "领域",
            value: res.data.tradefields
        }, {
            label: "品牌",
            value: res.data.brandname
        }, {
            label: "项目名称",
            value: res.data.projectname
        }, {
            label: "项目阶段",
            value: res.data.stagename
        }, {
            label: "客户",
            value: res.data.enterprisename
        }, {
            label: "电话",
            value: res.data.telephone
        }, {
            label: "客户联系人",
            value: res.data.contactsname
        }, {
            label: "联系人手机号",
            value: res.data.contactsphonenumber
        }, {
            label: "报价日期",
            value: res.data.billdate
        }, {
            label: "有效期",
            value: res.data.begdate + ' - ' + res.data.enddate
        }, {
            label: "整单折扣(%)",
            value: (res.data.discountrate * 100).toFixed(2) + '%'
        }, {
            label: "总金额",
            value: CNY(res.data.quotedpriceamount)
        }, {
            label: "是否特价",
            value: res.data.specialoffer == 1 ? '是' : '否'
        }, {
            label: "状态",
            value: getApp().globalData.Language.getMapText(res.data.status),
            style:`color:${this.data.sColors[res.data.status]}`
        }, {
            label: "负责人",
            value: res.data.leader.length ? res.data.leader[0].name : ""
        }, {
            label: "备注",
            value: res.data.remarks
        }];
        //客户报价移除项目字段
        if (res.data.quotedpricetype == '客户报价') list1.splice(4, 2);
        this.setData({
            briefs,
            list1,
            list2: [{
                label: "创建人",
                value: res.data.createby
            }, {
                label: "创建时间",
                value: res.data.createdate
            }, {
                label: "最近编辑人",
                value: res.data.changeby
            }, {
                label: "最近编辑时间",
                value: res.data.changedate
            }, {
                label: "提交人",
                value: res.data.submitby
            }, {
                label: "提交时间",
                value: res.data.submitdate
            }, {
                label: "审核人",
                value: res.data.checkby
            }, {
                label: "审核时间",
                value: res.data.checkdate
            }, {
                label: "复核人",
                value: res.data.checkby
            }, {
                label: "复核时间",
                value: res.data.checkdate
            }, {
                label: "作废原因",
                value: res.data.deletereason
            }, {
                label: "转手次数",
                value: res.data.leader.length ? res.data.leader[0].leadernum : ""
            }],
        })
    },
    /* 设置底部功能 */
    async setTabbarList() {
        let detail = this.data.detail,
            status = detail.status,
            isLeader = detail.leader.length ? detail.leader.some(v => v.userid == wx.getStorageSync('userMsg').userid) : false,
            isAdmin = this.data.isAdmin,
            specialoffer = detail.specialoffer == 1,
            editdataleader = isLeader,
            tabbarList = [];
        if (this.data.appAuth.isdatafollowup) tabbarList.push({
            icon: "color-genjin",
            label: "跟进"
        })
        if (!isLeader) {
            let res = await getApp().agentOrNot("sa_quotedprice", this.data.sa_quotedpriceid),
                data = res.code == '1' ? res.data : {
                    editable: 0,
                    editdataleader: 0
                }
            if (this.data.appAuth.isdatateam) isLeader = this.selectComponent("#Group").data.editable == 1;
            if (!isLeader) isLeader = data.editable == 1;
            editdataleader = data.editdataleader;
        }
        if (isLeader || isAdmin) {
            //负责人/管理员默认权限功能
            tabbarList.push({
                icon: "icon-guanlian-fuzhi",
                label: "复制"
            });
            if (status == '新建') {
                if (editdataleader) tabbarList.unshift({
                    icon: "color-genghuanfuzeren",
                    label: "更换负责人"
                })
                tabbarList = [{
                    icon: "icon-shanchu",
                    label: "作废"
                }, {
                    icon: "icon-dibu-bianji",
                    label: "编辑"
                }].concat(tabbarList);
            }
            //负责人 新建状态可以提交 提交状态可以撤回  负责人可以打印
            if (isLeader) {
                if (status == '新建') tabbarList.unshift({
                    icon: "icon-genjin",
                    label: '提交'
                })
                if (status == '提交') tabbarList.unshift({
                    icon: "icon-genjin",
                    label: '撤回'
                });
            }
        }
        if (specialoffer) {
            //开启特价
            switch (status) {
                case "提交":
                    if (this.data.options.some(v => v == 'isrecheck')) tabbarList.unshift({
                        icon: "icon-fuhe",
                        label: "复核"
                    })
                    break;
                case "复核":
                    if (this.data.options.some(v => v == 'isrecheck')) tabbarList.unshift({
                        icon: "icon-fanfuhe",
                        label: "反复核"
                    })
                    if (this.data.isAdmin) tabbarList.unshift({
                        icon: "icon-guanlian-fuzhi",
                        label: "审核"
                    })
                    break;
                case "审核":
                    if (this.data.isAdmin) tabbarList.unshift({
                        icon: "icon-guanlian-fuzhi",
                        label: "反审核"
                    })
                    break;
            }
        } else {
            //未开启特价
            //拥有管理权限 提交状态可以审核  审核状态可以反审核
            if (this.data.isAdmin && (status == '审核' || status == '提交')) tabbarList.unshift(status == '审核' ? {
                icon: "icon-guanlian-fuzhi",
                label: "反审核"
            } : {
                icon: "icon-guanlian-fuzhi",
                label: "审核"
            });
        }
        this.setData({
            tabbarList,
            isLeader,
            editdataleader
        });
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags();
    },
    //更新团队成员
    getGroup() {
        this.selectComponent("#Group").getList().then(this.setTabbarList)
    },
    //局部数据更新 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_quotedpriceid;
            if (model == "#Files") init = true;
            if (total == null || init) {
                Component.getList(id, init);
            } else if (pageNumber <= pageTotal) {
                Component.getList(id, false);
            }
        }
    },
    onReachBottom() {
        this.partialRenewal();
    },
    //详情按钮回调
    tabbarOnClick({
        detail
    }) {
        let data = this.data.detail,
            that = this;
        switch (detail.label) {
            case "编辑":
                wx.navigateTo({
                    url: `/packageA/offers/${data.quotedpricetype=='项目报价'?'addProjectOffer':'addSetclientOffer'}?data=${JSON.stringify(data)}`,
                })
                break;
            case "提交":
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText(`是否确定提交当前报价，提交后禁止使用部分功能`),
                    complete: ({
                        confirm
                    }) => {
                        if (confirm) _Http.basic({
                            "id": "2024091910001802",
                            "content": {
                                "ownertable": "sa_quotedprice", //sa_project,sa_contract,sa_quotedprice
                                "ownerid": that.data.sa_quotedpriceid
                            }
                        }).then(s => {
                            console.log("报价单是否可以提交", s)
                            if (s.code == 1) {
                                _Http.basic({
                                    "id": 20221020165303,
                                    "version": 1,
                                    "content": {
                                        "sa_quotedpriceid": that.data.sa_quotedpriceid
                                    }
                                }).then(res => {
                                    console.log("提交报价单", res)
                                    getApp().globalData.Language.showToast(res.code == '1' ? "提交成功" : res.msg)
                                    if (res.code == '1') setTimeout(() => {
                                        that.getDetail();
                                    }, 300)
                                })
                            } else {
                                _Http.basic({
                                    "id": 2024091910214302,
                                    "version": 1,
                                    "content": {
                                        "ownertable": "sa_quotedprice", //sa_project,sa_contract,sa_quotedprice
                                        "ownerid": that.data.sa_quotedpriceid
                                    }
                                }).then(v => {
                                    console.log("发送提醒", v)
                                    getApp().globalData.Language.showToast(v.code == '1' ? "已发送提醒" : res.msg)
                                })
                            }
                        })
                    }
                })
                break;
            case "审核":
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('是否通过当前报价'),
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: getApp().globalData.Language.getMapText('确定'),
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20221020165403,
                            "version": 1,
                            "content": {
                                "sa_quotedpriceid": that.data.sa_quotedpriceid,
                                ischeck: true
                            }
                        }).then(res => {
                            console.log("审核报价单", res)
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('审核成功') : res.msg,
                                icon: "none"
                            })
                            if (res.code == '1') setTimeout(() => {
                                that.getDetail();
                            }, 300)
                        })
                    }
                })
                break;
            case "反审核":
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('是否退回当前报价'),
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: getApp().globalData.Language.getMapText('确定'),
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20221020165403,
                            "version": 1,
                            "content": {
                                "sa_quotedpriceid": that.data.sa_quotedpriceid,
                                ischeck: false
                            }
                        }).then(res => {
                            console.log("反审核报价单", res)
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('反审核成功') : res.msg,
                                icon: "none"
                            })
                            if (res.code == '1') setTimeout(() => {
                                that.getDetail();
                            }, 300)
                        })
                    }
                })
                break;
            case "撤回":
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('是否撤回审核当前报价'),
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: getApp().globalData.Language.getMapText('确定'),
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20221125162803,
                            "version": 1,
                            "content": {
                                "sa_quotedpriceid": that.data.sa_quotedpriceid
                            }
                        }).then(res => {
                            console.log("撤回报价单", res)
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('撤回审核成功') : res.msg,
                                icon: "none"
                            })
                            if (res.code == '1') setTimeout(that.getDetail, 300)
                        })
                    }
                })
                break;
            case "跟进":
                wx.navigateTo({
                    url: `/prsx/trace/add/index?ownertable=sa_quotedprice&ownerid=${data.sa_quotedpriceid}&resource=报价单`,
                })
                break;
            case "复制":
                const {
                    billno,
                    sa_quotedpriceid
                } = data;
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('是否确认复制') + `“${billno}”`,
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: getApp().globalData.Language.getMapText('确定'),
                    complete: ({
                        confirm
                    }) => {
                        if (confirm) _Http.basic({
                            "id": 20221209094103,
                            "content": {
                                sa_quotedpriceid
                            },
                        }).then(res => {
                            console.log("复制报价单", res)
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('复制成功') : res.msg,
                                icon: "none",
                                mask: true
                            });
                            if (res.code == '1') setTimeout(() => {
                                wx.redirectTo({
                                    url: `/packageA/offers/detail?sa_quotedpriceid=${res.data.sa_quotedpriceid}`,
                                })
                                let page = getCurrentPages().find(v => v.__route__ == 'packageA/offers/index');
                                if (page) page.getList(true);
                            }, 300)
                        })
                    }
                })
                break;
            case "作废":
                wx.navigateTo({
                    url: `/packageA/offers/delete?id=${this.data.detail.sa_quotedpriceid}`,
                })
                break;
            case "更换负责人":
                wx.navigateTo({
                    url: `/pages/group/select?data=${JSON.stringify({
                             ownertable:"sa_quotedprice",
                             ownerid:data.sa_quotedpriceid,
                        })}&radio=true&principal=true`,
                })
                break;
            case "复核":
                isrecheck(1)
                break;
            case "反复核":
                isrecheck(0)
                break;
        }

        function isrecheck(isrecheck) {
            wx.showModal({
                title: getApp().globalData.Language.getMapText('提示'),
                content: getApp().globalData.Language.joint([{
                    v: '是否确定',
                    t: 1,
                }, {
                    v: isrecheck ? '复核' : '反复核',
                    t: 1,
                    r: ' ',
                    f: " "
                }, {
                    v: '报价单',
                    t: 1,
                }]),
                cancelText: getApp().globalData.Language.getMapText('取消'),
                confirmText: getApp().globalData.Language.getMapText('确定'),
                complete: (res) => {
                    if (res.confirm) _Http.basic({
                        "id": 20231206102404,
                        "content": {
                            "sa_quotedpriceid": data.sa_quotedpriceid,
                            isrecheck
                        }
                    }).then(res => {
                        wx.showToast({
                            title: res.code == '1' ? getApp().globalData.Language.joint([{
                                v: isrecheck ? '复核' : '反复核',
                                t: 1,
                                r: ' ',
                            }, {
                                v: '成功',
                                t: 1,
                            }]) : res.msg,
                            icon: "none"
                        })
                        if (res.code == '1') that.getDetail(true)
                    })
                }
            })
        }
    },
    /* 更换负责人 */
    handelSubmit(arr) {
        const that = this;
        wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content: getApp().globalData.Language.getMapText('是否确认更换负责人'),
            cancelText: getApp().globalData.Language.getMapText('取消'),
            confirmText: getApp().globalData.Language.getMapText('确定'),
            complete: ({
                confirm
            }) => {
                if (confirm) wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('是否参与该数据的后续工作'),
                    cancelText: getApp().globalData.Language.getMapText('不参与'),
                    confirmText: getApp().globalData.Language.getMapText('参与'),
                    complete: (s) => {
                        _Http.basic({
                            "id": 20220930103701,
                            "content": {
                                ownertable: "sa_quotedprice",
                                ownerid: that.data.detail.sa_quotedpriceid,
                                userid: arr[0],
                                isaddoldleader: s.confirm ? 1 : 0
                            }
                        }).then(res => {
                            console.log("更换负责人", res)
                            if (res.code != '1') return wx.showToast({
                                title: res.data,
                                icon: "none"
                            });
                            wx.showToast({
                                title: getApp().globalData.Language.getMapText('更换成功'),
                                icon: "none",
                                mask: true
                            });
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 2
                                });
                                /*  getCurrentPages().forEach(v => {
                                     if (['packageA/project/index'].includes(v.__route__)) v.getList(true)
                                 }) */
                            }, 300)
                        })
                    }
                })
            }
        })
    },
    onUnload() {
        const page = getCurrentPages().find(v => v.__route__ == 'packageA/offers/index');
        if (!page) return;
        let content = JSON.parse(JSON.stringify(page.data.content));
        content.pageSize = (content.pageNumber - 1) * content.pageSize;
        content.pageNumber = 1;
        _Http.basic({
            id: '20221020165103',
            content
        }).then(res => {
            console.log("更新报价单", res);
            if (res.code == '1') page.setData({
                list: res.data.map(v => {
                    v.progress = v.stage / v.totalstage * 100;
                    return v
                }),
                "content.total": res.total
            })
        })
    }
})