const _Http = getApp().globalData.http,
    currency = require("../../utils/currency"),
    CNY = value => currency(value, {
        symbol: "￥",
        precision: 2
    }).format();
Page({
    data: {
        isLeader: false, //是否为负责人
        tabsActive: 0, //tabs 选中项
        sa_contractid: "",
        tabsList: [{
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }],
        tabbarList: [],
    },
    onLoad(options) {
        this.setData({
            sa_contractid: options.id,
            isAdmin: wx.getStorageSync('auth').wcontract.options.some(v => v == "admin"), //是否具有管理权限
            options: wx.getStorageSync('auth').wcontract.options, //权限列表
        });
        this.getDetail();
    },
    getDetail() {
        _Http.basic({
            "id": 20221121195102,
            "content": {
                nocache: true,
                "sa_contractid": this.data.sa_contractid
            },
        }).then(res => {
            console.log("合同详情", res)
            if (res.msg != '成功') return wx.showToast({
                title: res.msg,
                icon: "none"
            });

            let isLeader = res.data.leader.some(some => some.userid == wx.getStorageSync('userMsg').userid),
                tabbarList = [{
                    icon: "icon-genjin",
                    label: "跟进"
                }];
            if (this.data.isAdmin) tabbarList = [{
                icon: "icon-genjin",
                label: "审核"
            }, {
                icon: "icon-genjin",
                label: "反审核"
            }].concat(tabbarList);
            if (isLeader || this.data.isAdmin) {
                tabbarList = [{
                    icon: "icon-zhuanyi",
                    label: "更换负责人"
                }, {
                    icon: "icon-genjin",
                    label: "终止"
                }, {
                    icon: "icon-shanchu",
                    label: "作废"
                }].concat(tabbarList)
                if (res.data.status == '新建') tabbarList.push({
                    icon: "icon-bianji",
                    label: "编辑"
                });
                if (isLeader && res.data.status == '已提交') {
                    tabbarList.unshift({
                        icon: "icon-genjin",
                        label: '撤回'
                    })
                } else {
                    tabbarList.unshift({
                        icon: "icon-genjin",
                        label: '提交'
                    })
                }
            };
            let data = res.data,
                tabsList = this.data.tabsList,
                tabsActive = 0;
            switch (data.type) {
                case "框架":
                    data.type = '经销商合作协议'
                    tabsList = tabsList.concat([{
                        label: "产品明细折扣",
                        icon: "icon-tabchanpin",
                        model: '#PiscountProduct'
                    }, {
                        label: "产品类别折扣",
                        icon: "icon-tabchanpinleibie",
                        model: '#PiscountType'
                    }, {
                        label: "业绩目标",
                        icon: "icon-tabrenwu",
                        model: '#Objective'
                    }, {
                        label: "跟进动态",
                        icon: "icon-tabgenjindongtai1",
                        model: '#Trace'
                    }]);
                    tabsActive = 1;
                    break;
                case "工具借用":
                    data.type = '工具使用(借用)协议'
                    tabsList = tabsList.concat([{
                        label: "工具清单",
                        icon: "icon-tabgongjuqingdan",
                        model: '#Product'
                    }, {
                        label: "跟进动态",
                        icon: "icon-tabgenjindongtai1",
                        model: '#Trace'
                    }])
                    tabsActive = 1;
                    break;
                case "居间":
                    data.type = '居间协议'
                    break;
                case "项目":
                    /*  {
                        label: "合同条款",
                        num: 132
                    }, */
                    data.type = data.typemx + '项目协议'
                    tabsList = tabsList.concat([{
                        label: "产品明细折扣",
                        icon: "icon-tabchanpin",
                        model: '#Product'
                    }, {
                        label: "产品类别折扣",
                        icon: "icon-tabchanpinleibie",
                        model: '#PiscountType'
                    }, {
                        label: "跟进动态",
                        icon: "icon-tabgenjindongtai1"
                    }]);
                    tabsActive = 1;
                    break;
            };
            tabsList.push({
                label: "任务",
                icon: "icon-tabrenwu",
                model: "#Work"
            })
            this.setDetail(data);
            this.setData({
                isLeader,
                tabbarList,
                detail: data,
                list2: [{
                    label: "创建人",
                    value: data.createby
                }, {
                    label: "创建时间",
                    value: data.createdate
                }, {
                    label: "最近编辑人",
                    value: data.changeby
                }, {
                    label: "最近编辑时间",
                    value: data.changedate
                }, {
                    label: "提交人",
                    value: data.submitby
                }, {
                    label: "提交时间",
                    value: data.submitdate
                }, {
                    label: "审核人",
                    value: data.checkby
                }, {
                    label: "审核时间",
                    value: data.checkdate
                }, {
                    label: "作废原因",
                    value: data.leader.deletereason
                }, {
                    label: "转手次数",
                    value: data.leader[0].leadernum
                }],
                tabsList,
                tabsActive
            });

            /* 更新列表数据 */
            let page = getCurrentPages().find(v => v.__route__ == 'packageA/contract/index');
            if (page) {
                let i = page.data.list.findIndex(v => v.sa_contractid == this.data.sa_contractid);
                if (i != -1) page.setData({
                    [`list[${i}].status`]: res.data.status
                })
            }

            this.getTags();
            this.getGroup();
            this.partialRenewal();
        })
    },
    /* 设置详情信息 */
    setDetail(data) {
        let briefs = [{
                label: "合同编号",
                value: data.billno
            }, {
                label: "合同类型",
                value: data.type
            }, {
                label: "经销商",
                value: data.enterprisename
            }, {
                label: "整体折扣",
                value: data.discountrate * 100 + "%"
            }, {
                label: "签约日期",
                value: data.signdate
            }, {
                label: "状态",
                value: data.status
            }],
            list1 = [{
                label: "合同标题",
                value: data.title
            }, {
                label: "合同编号",
                value: data.billno
            }, {
                label: "合同类型",
                value: data.type
            }, {
                label: "签约日期",
                value: data.signdate
            }, {
                label: "合同有效期",
                value: data.begdate + ' 至 ' + data.enddate
            }, {
                label: "合同模板",
                value: data.type
            }, {
                label: "合同描述",
                value: data.remarks
            }, {
                label: "负责人",
                value: data.leader[0].name
            }, {
                label: "状态",
                value: data.status
            }];
        if (data.typemx) {
            console.log(data)
            briefs.splice(3, 0, {
                label: "项目",
                value: data.projectname
            })
            briefs.splice(4, 0, {
                label: "项目编号",
                value: data.projectnum
            })
            briefs.splice(5, 0, {
                label: "有效期",
                value: data.begdate + ' 至 ' + data.enddate
            })
            briefs.splice(6, 1)
            briefs.splice(7, 0, {
                label: "签约金额(元)",
                value: CNY(data.signamount)
            })
            briefs.splice(7, 0, {
                label: "折扣(%)",
                value: data.discountrate * 100 + "%"
            })
            list1.splice(3, 0, {
                label: data.typemx == '直销' ? '客户' : "经销商",
                value: data.enterprisename
            })

            list1.splice(4, 0, {
                label: "项目",
                value: data.projectname
            })
            list1.splice(5, 0, {
                label: "品牌",
                value: data.brandname
            })
            list1.splice(6, 0, {
                label: "领域",
                value: data.tradefields
            })
            list1.splice(7, 0, {
                label: "项目编号",
                value: data.projectnum
            })
            list1.splice(8, 0, {
                label: "项目地址",
                value: data.address
            })
            list1.splice(9, 0, {
                label: "收货人",
                value: data.name
            })
            list1.splice(10, 0, {
                label: "收货人电话",
                value: data.phonenumber
            })
            list1.splice(11, 0, {
                label: "业务员",
                value: data.salername
            })
            list1.splice(12, 0, {
                label: "签约金额",
                value: CNY(data.signamount)
            })
            list1.splice(13, 0, {
                label: "折扣(%)",
                value: data.discountrate * 100 + "%"
            })
            if (data.typemx == '直销') briefs[2].label = '客户';
        } else {
            switch (data.type) {
                case "居间协议":
                    briefs.splice(2, 1, {
                        label: "居间服务商",
                        value: data.enterprisename
                    })
                    briefs.splice(3, 0, {
                        label: "项目",
                        value: data.projectname
                    })
                    briefs.splice(4, 0, {
                        label: "项目编号",
                        value: data.projectnum
                    })
                    briefs.splice(5, 1, {
                        label: data.calculatemodel == 1 ? '订单金额比例' : '产品折扣',
                        value: data.calculatemodel == 1 ? data.orderratio * 100 + '%' : data.productdiscount * 100 + '%'
                    })
                    briefs.splice(3, 0, {
                        label: "项目合同",
                        value: data.ascription_title
                    })
                    briefs.splice(7, 0, {
                        label: "合同有效期",
                        value: data.begdate + "-" + data.enddate
                    })
                    list1.splice(3, 0, {
                        label: "居间服务商",
                        value: data.enterprisename
                    })
                    list1.splice(4, 0, {
                        label: "项目合同",
                        value: data.ascription_title
                    })
                    list1.splice(5, 0, {
                        label: "项目",
                        value: data.projectname
                    })
                    list1.splice(6, 0, {
                        label: "项目编号",
                        value: data.projectnum
                    })
                    list1.splice(8, 0, {
                        label: data.calculatemodel == 1 ? '订单金额比例' : '居间产品折扣',
                        value: data.calculatemodel == 1 ? data.orderratio * 100 + '%' : data.productdiscount * 100 + '%'
                    })
                    break;
                case "工具使用(借用)协议":
                    briefs.splice(2, 1, {
                        label: "客户",
                        value: data.enterprisename
                    })
                    briefs.splice(3, 1, {
                        label: "单套价格",
                        value: data.signamount
                    })
                    briefs.splice(5, 0, {
                        label: "合同有效期",
                        value: data.begdate + ' 至 ' + data.enddate
                    })

                    list1.splice(3, 0, {
                        label: "客户",
                        value: data.enterprisename
                    })
                    list1.splice(4, 0, {
                        label: "单套价格",
                        value: data.signamount
                    })
                    break;
                case "经销商合作协议":
                    briefs[3].label = '折扣(%)';
                    briefs.splice(3, 0, {
                        label: "签约金额(元)",
                        value: CNY(data.signamount)
                    })
                    list1.splice(3, 0, {
                        label: "经销商",
                        value: data.enterprisename
                    })
                    list1.splice(4, 0, {
                        label: "签约金额(元)",
                        value: CNY(data.signamount)
                    })
                    list1.splice(5, 0, {
                        label: "折扣(%)",
                        value: data.discountrate * 100 + "%"
                    })
                    list1.splice(6, 0, {
                        label: "品牌",
                        value: data.brandname
                    })
                    list1.splice(7, 0, {
                        label: "领域",
                        value: data.tradefields
                    })
                    break;
            }
        }
        this.setData({
            briefs,
            list1
        })
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags();
    },
    //更新团队成员
    getGroup() {
        this.selectComponent("#Group").getList();
    },
    //局部数据更新 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_contractid;
            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.showModal({
                    title: '提示',
                    content: `是否确定终止当前协议`,
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20221212102802,
                            "content": {
                                "sa_contractid": that.data.sa_contractid
                            }
                        }).then(res => {
                            console.log("提交报价单", res)
                            wx.showToast({
                                title: res.msg == '成功' ? "已终止" : res.msg,
                                icon: "none"
                            })
                            if (res.msg == '成功') setTimeout(() => {
                                that.getDetail();
                            }, 300)
                        })
                    }
                })
                break;
            case "提交":
                if (data.status != '新建') return wx.showToast({
                    title: '当前状态不可提交!',
                    icon: "none"
                })
                wx.showModal({
                    title: '提示',
                    content: `是否确定提交当前协议，提交后禁止使用部分功能`,
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20221121202802,
                            "content": {
                                "sa_contractids": [that.data.sa_contractid]
                            }
                        }).then(res => {
                            console.log("提交报价单", res)
                            wx.showToast({
                                title: res.msg == '成功' ? "提交成功" : res.msg,
                                icon: "none"
                            })
                            if (res.msg == '成功') setTimeout(() => {
                                that.getDetail();
                            }, 300)
                        })
                    }
                })
                break;
            case "审核":
                if (data.status != '已提交') return wx.showToast({
                    title: '当前状态不可审核!',
                    icon: "none"
                })
                wx.showModal({
                    title: '提示',
                    content: `是否通过当前协议`,
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20221121203102,
                            "version": 1,
                            "content": {
                                "type": 1, //0：不通过，1：通过
                                "sa_contractids": [that.data.sa_contractid]
                            }
                        }).then(res => {
                            console.log("审核合同", res)
                            wx.showToast({
                                title: res.msg == '成功' ? "审核成功" : res.msg,
                                icon: "none"
                            })
                            if (res.msg == '成功') setTimeout(() => {
                                that.getDetail();
                            }, 300)
                        })
                    }
                })
                break;
            case "撤回":
                if (data.status != '已提交') return wx.showToast({
                    title: '当前状态不可撤回!',
                    icon: "none"
                })
                wx.showModal({
                    title: '提示',
                    content: `是否撤回审核当前协议`,
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20230130091502,
                            "content": {
                                "sa_contractid": that.data.sa_contractid,
                            }
                        }).then(res => {
                            console.log("撤回审核合同", res)
                            wx.showToast({
                                title: res.msg == '成功' ? "撤回审核成功" : res.msg,
                                icon: "none"
                            })
                            if (res.msg == '成功') setTimeout(() => {
                                that.getDetail();
                            }, 300)
                        })
                    }
                })
                break;

            case "反审核":
                if (data.status == '新建') return wx.showToast({
                    title: '当前状态不可反审核!',
                    icon: "none"
                })
                wx.showModal({
                    title: '提示',
                    content: `是否反审核当前协议`,
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20221212135402,
                            "content": {
                                "sa_contractid": that.data.sa_contractid,
                            }
                        }).then(res => {
                            console.log("反审核合同", res)
                            wx.showToast({
                                title: res.msg == '成功' ? "反审核成功" : res.msg,
                                icon: "none"
                            })
                            if (res.msg == '成功') setTimeout(() => {
                                that.getDetail();
                            }, 300)
                        })
                    }
                })
                break;
            case "跟进":
                wx.navigateTo({
                    url: `/packageA/setclient/modules/trace/add/index?ownertable=sa_contract&ownerid=${data.sa_contractid}`,
                })
                break;
            case "作废":
                wx.showModal({
                    title: '提示',
                    content: '是否确认作废该协议？',
                    complete: ({
                        confirm
                    }) => {
                        if (confirm) _Http.basic({
                            "id": 20221121202502,
                            "version": 1,
                            "content": {
                                "sa_contractids": [this.data.detail.sa_contractid]
                            }
                        }).then(res => {
                            wx.showToast({
                                title: res.msg == '成功' ? '已作废协议' : res.msg,
                                icon: "none"
                            });
                            if (res.msg == '成功') {
                                setTimeout(() => {
                                    getCurrentPages().forEach(v => {
                                        if (v.__route__ == 'packageA/contract/index') {
                                            v.setData({
                                                list: v.data.list.filter(value => value.sa_contractid != this.data.detail.sa_contractid),
                                                'content.total': v.data.content.total - 1
                                            })
                                        }
                                    })
                                    wx.navigateBack();
                                }, 300)
                            }
                        })
                    }
                })
                break;
            case "编辑":
                this.toEdit();
                break;
            case "更换负责人":
                wx.navigateTo({
                    url: `/pages/group/select?data=${JSON.stringify({
                             ownertable:"sa_contract",
                             ownerid:data.sa_contractid,
                        })}&radio=true&principal=true`,
                })
                break;
        }
    },
    toEdit() {
        let data = this.data.detail,
            type = null;
        data.invaliddate = [data.begdate, data.enddate]
        data.sys_enterpriseid = [data.enterprisename, [data.sys_enterpriseid]];
        data.sa_projectid = [data.projectname, [data.sa_projectid]];
        switch (data.type) {
            case "经销商合作协议":
                type = "type1"
                break;
            case "经销项目协议":
                type = "type2"
                break;
            case "直销项目协议":
                type = "type3"
                break;
            case "居间协议":
                data.ascription_contractid = [data.ascription_title, [data.ascription_contractid]];
                data.radios = data.calculatemodel + "";
                type = "type4"
                break;
            case "工具使用(借用)协议":
                type = "type5"
                break;
        };
        if (type) wx.navigateTo({
            url: `/packageA/contract/add/${type}/index?data=${JSON.stringify(data)}`,
        })

    },
    /* 更换负责人 */
    handelSubmit(arr) {
        const that = this;
        wx.showModal({
            title: '提示',
            content: '是否确认更换负责人',
            complete: ({
                confirm
            }) => {
                if (confirm) _Http.basic({
                    "id": 20220930103701,
                    "content": {
                        ownertable: "sa_contract",
                        ownerid: that.data.detail.sa_contractid,
                        userid: arr[0]
                    }
                }).then(res => {
                    console.log("更换负责人", res)
                    if (res.msg != '成功') return wx.showToast({
                        title: res.data,
                        icon: "none"
                    });
                    wx.showToast({
                        title: '更换成功！',
                        icon: "none"
                    });
                    setTimeout(() => {
                        that.getDetail();
                        wx.navigateBack();
                    }, 300)
                })
            }
        })
    },
    onUnload() {
        let page = getCurrentPages().find(v => v.__route__ == 'packageA/contract/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: 20221121201502,
            content
        }).then(res => {
            console.log("更新合同列表", res);
            if (res.msg == '成功') page.setData({
                list: res.data,
                "content.total": res.total
            })
        })
    }
})