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_customersid: 0,
        modeList: [{
                name: '潜在',
            },
            {
                name: '合作中'
            },
            {
                name: '已终止'
            }
        ],
        changeMode: false,
        sColors: getApp().globalData.sColors,
    },
    onLoad(options) {
        const appAuth = wx.getStorageSync('auth').wCustomer;
        let tabsList = [{
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }, {
            label: "地址管理",
            icon: "icon-tabdizhi",
            model: "#Address"
        }, {
            label: "关联合同",
            icon: "icon-tabhetong",
            model: "#Contract"
        }];
        if (appAuth.isdatafollowup) tabsList.unshift({
            label: "跟进动态",
            icon: "icon-tabgenjinjilu",
            model: "#Trace"
        })
        tabsList = tabsList.concat([{
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        }, {
            label: "操作",
            icon: "icon-tabcaozuojilu1",
            model: "#Record"
        }])
        this.setData({
            sa_customersid: options.id,
            isAdmin: appAuth.options.some(v => v == "admin"), //是否具有管理权限
            options: appAuth.options, //权限列表
            tabsList,
            appAuth
        })
        this.getDetail();
        getApp().globalData.Language.getLanguagePackage(this, '医院详情');
    },
    modeSelect(e) {
        let {
            sa_customersid,
            status
        } = this.data.detail,
            that = this;
        wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content: getApp().globalData.Language.getMapText('是否确定将合作模式更改为') + `：“${e.detail.name}”`,
            cancelText: getApp().globalData.Language.getMapText('取消'),
            confirmText: getApp().globalData.Language.getMapText('确定'),
            complete: (res) => {
                if (res.cancel) that.modeCancel()
                if (res.confirm) _Http.basic({
                    "id": 20221010164602,
                    "content": {
                        "sa_customersids": [sa_customersid],
                        "status": e.detail.name
                    }
                }).then(res => {
                    console.log("更改合作状态", res)
                    wx.showToast({
                        title: res.code == '1' ? getApp().globalData.Language.getMapText('修改成功') : res.msg,
                        icon: "none"
                    })
                    if (res.code == '1') that.getDetail()
                    that.modeCancel()
                })
            }
        })
    },
    modeCancel() {
        this.setData({
            changeMode: false
        })
    },
    //详情按钮回调
    tabbarOnClick({
        detail
    }) {
        let data = this.data.detail,
            that = this;
        switch (detail.label) {
            case "更改合作状态":
                this.setData({
                    changeMode: true
                })
                break;
            case "退回":
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('是否确定将') + `${data.enterprisename}` + getApp().globalData.Language.getMapText('退回到公海客户'),
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: getApp().globalData.Language.getMapText('确定'),
                    complete: (res) => {
                        console.log(data)
                        if (res.confirm) _Http.basic({
                            "id": 20221014102602,
                            "content": {
                                "sa_customerpoolid": data.sa_customerpoolid_source,
                                "sa_customersid": data.sa_customersid
                            }
                        }).then(res => {
                            console.log("公海线索退回", res)
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('退回成功') : res.msg,
                                icon: "none"
                            });
                            if (res.code == '1') setTimeout(() => {
                                let page = getCurrentPages().find(v => v.__route__ == 'packageA/setclient/index');
                                if (page) page.setData({
                                    list: page.data.list.filter(v => v.sa_customersid != data.sa_customersid)
                                });
                                wx.redirectTo({
                                    url: '/packageA/publicCustomer/detail?id' + data.sa_customersid,
                                })
                            }, 300)
                        })
                    }
                });
                break;
            case "回收":
                wx.navigateTo({
                    url: `/packageA/publicCustomer/pond/index?params=${JSON.stringify({
                        "id": 20221206195102,
                        "content": {
                            nocache:true,
                            "where": {
                                "condition": ""
                            }
                        }
                    })}`,
                })
                getApp().globalData.handleSelect = this.handleTransfer.bind(this);
                break;
            case "跟进":
                this.selectComponent("#Trace").insetr();
                break;
            case "编辑":
                data.parentid = data.superiorenterprisename ? [data.superiorenterprisename, [data.parentid]] : "";
                wx.navigateTo({
                    url: `/packageA/setclient/addAndEditor?data=${JSON.stringify(data)}`,
                })
                break;
            case "作废":
                wx.navigateTo({
                    url: `/packageA/setclient/delete?item=${JSON.stringify({
                        "sa_customersids": [this.data.detail.sa_customersid],
                        datastatus: 1, //（0:正常；1:作废；2:锁定）
                    })}&id=20221012164002`,
                })
                break;
            case "暂缓":
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('暂缓的客户将不计入客户相关数据统计，是否确定暂缓该客户？'),
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: that.data.language['确定'] || '确定暂缓',
                    complete: (res) => {
                        console.log(data)
                        if (res.confirm) _Http.basic({
                            "id": 20221010164602,
                            "content": {
                                "sa_customersids": [data.sa_customersid],
                                "status": '暂缓'
                            }
                        }).then(res => {
                            console.log("客户暂缓", res)
                            getApp().globalData.Language.showToast(res.code == '1' ? "已将客户暂缓" : res.msg)
                            that.getDetail();
                        })
                    }
                });
                break;
            case "取消暂缓":
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('是否确定取消暂缓并继续跟进客户'),
                    cancelText: getApp().globalData.Language.getMapText('关闭'),
                    confirmText: that.data.language['确定'] || '确定取消',
                    complete: (res) => {
                        console.log(data)
                        if (res.confirm) _Http.basic({
                            "id": 20221010164602,
                            "content": {
                                "sa_customersids": [data.sa_customersid],
                                "status": '潜在'
                            }
                        }).then(res => {
                            console.log("客户取消暂缓", res)
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('已取消暂缓') : res.msg,
                                icon: "none"
                            });
                            getApp().globalData.Language.showToast(res.code == '1' ? "已取消暂缓" : res.msg)
                            that.getDetail();
                        })
                    }
                });
                break;
            case "更换负责人":
                wx.navigateTo({
                    url: `/pages/group/select?data=${JSON.stringify({
                         ownertable:"sa_customers",
                         ownerid:this.data.sa_customersid,
                    })}&radio=true&principal=true`,
                })
                break;
            case "终止":
                wx.showModal({
                    content: getApp().globalData.Language.getMapText('是否确定终止客户合作') + '?',
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: that.data.language['确定'] || '确定终止',
                    complete: ({
                        confirm
                    }) => {
                        if (confirm) _Http.basic({
                            "id": 20221010164602,
                            "content": {
                                "sa_customersids": [this.data.sa_customersid],
                                "status": "已终止"
                            }
                        }).then(res => {
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('已终止合作状态') : res.msg,
                                icon: "none"
                            });
                            that.getDetail();
                        })
                    }
                })
                break;
            case "恢复":
                wx.showModal({
                    content: getApp().globalData.Language.getMapText('是否确定恢复客户合作') + '?',
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: that.data.language['确定'] || '确定恢复',
                    complete: ({
                        confirm
                    }) => {
                        if (confirm) _Http.basic({
                            "id": 20221010164602,
                            "content": {
                                "sa_customersids": [this.data.sa_customersid],
                                "status": "潜在"
                            }
                        }).then(res => {
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('已恢复合作状态') : res.msg,
                                icon: "none"
                            });
                            that.getDetail();
                        })
                    }
                })
                break;
            case "查看重复":
                _Http.basic({
                    "id": 20221208172002,
                    "content": {
                        ...data,
                        pageSize: 999
                    }
                }).then(res => {
                    console.log("查看重复", res)
                    if (res.code != '1') return wx.showToast({
                        title: res.msg,
                        icon: "none"
                    });
                    if (res.data.length == 0) return wx.showToast({
                        title: getApp().globalData.Language.getMapText('未查询到重复数据'),
                        icon: "none"
                    });
                    this.setData({
                        repetitionList: res.data.map(v => {
                            v.chars = v.chars.reduce((acc, item) => ({
                                ...acc,
                                ...item
                            }), {});
                            return v
                        }),
                        repetitionShow: true
                    })
                })
                break;
            default:
                console.log(detail)
                break;
        }
    },
    /* 前去重复项详情 */
    toRepDetail(e) {
        const {
            item
        } = e.currentTarget.dataset;
        wx.navigateTo({
            url: '/packageA/setclient/detail?id=' + item.sa_customersid,
        })
        this.repClose()
    },
    /* 关闭查重 */
    repClose() {
        this.setData({
            repetitionShow: false
        })
    },
    /* 处理回收客户 */
    handleTransfer({
        value
    }) {
        wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content: getApp().globalData.Language.getMapText('是否确定将客户回收至') + `${value[0]}?`,
            cancelText: getApp().globalData.Language.getMapText('取消'),
            confirmText: getApp().globalData.Language.getMapText('确定'),
            complete: (res) => {
                if (res.confirm) _Http.basic({
                    "id": 20221014165602,
                    "content": {
                        "sa_customerpoolid": value[1][0], //公海池id
                        "sa_customersids": [this.data.detail.sa_customersid],
                        "sa_customersid": this.data.detail.sa_customersid
                    },
                }).then(res => {
                    console.log("回收客户", res)
                    wx.showToast({
                        title: res.code == '1' ? getApp().globalData.Language.getMapText('回收成功') : res.msg,
                        icon: "none"
                    });
                    if (res.code == '1') setTimeout(() => {
                        wx.navigateBack()
                        let page = getCurrentPages().find(v => v.__route__ == 'packageA/setclient/index');
                        if (page) page.setData({
                            list: page.data.list.filter(v => v.sa_customersid != this.data.detail.sa_customersid)
                        });
                        wx.redirectTo({
                            url: '/packageA/publicCustomer/detail?id=' + this.data.detail.sa_customersid,
                        })
                    }, 300)
                })
            }
        })
    },
    /* 更换负责人 */
    handelSubmit(arr) {
        const that = this;
        wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content: 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_customers",
                                ownerid: that.data.sa_customersid,
                                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
                            });
                            getCurrentPages().forEach(v => {
                                if (['packageA/setclient/index'].includes(v.__route__)) v.getList(true)
                            })
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 2
                                });
                            }, 300)
                        })
                    }
                })
            }
        })
    },
    /* 获取详情 */
    getDetail() {
        /* 基本信息 */
        _Http.basic({
            "id": 20221012164302,
            "content": {
                sa_customersid: this.data.sa_customersid
            },
        }).then(res => {
            console.log("详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.data,
                icon: "none"
            })
            this.setPreview(res);
            this.setData({
                loading: false,
                detail: res.data,
            })
            //获取标签
            if (this.data.appAuth.isdatatag) this.getTags();
            if (this.data.appAuth.isdatateam) this.getGroup()
            this.setTabbar();
            this.partialRenewal();
        });
    },
    async setTabbar() {
        /* 底部功能 */
        let detail = this.data.detail,
            isAdmin = this.data.isAdmin,
            isLeader = detail.leader.some(some => some.userid == wx.getStorageSync('userMsg').userid),
            editdataleader = isLeader ? 1 : 0,
            tabbarList = [];

        if (this.data.appAuth.isdatafollowup && detail.status != '已终止') tabbarList.push({
            icon: "color-genjin",
            label: "跟进"
        });

        if (!isLeader) {
            let res = await getApp().agentOrNot("sa_customers", this.data.sa_customersid),
                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) && detail.status != '已终止') {
            tabbarList.push({
                icon: "color-bianji",
                label: "编辑"
            })
            if (editdataleader) tabbarList.push({
                icon: "color-genghuanfuzeren",
                label: "更换负责人"
            })
        }
        if (detail.agentstatus == '启用' && detail.erpagentnum) {} else {
            if (isLeader || isAdmin) tabbarList.push({
                icon: "icon-shanchu",
                label: "作废"
            })
        }
        if (this.data.options.find(v => v == 'viewRepetition')) tabbarList.push({
            icon: "icon-a-shouyejingangquhehuoren",
            label: "查看重复"
        });
        this.setData({
            tabbarList,
            isLeader
        })
    },
    /*  {
            label: "企业等级",
            value: res.data.grade
        },  */
    setPreview(res) {
        /* 摘要信息 */
        let briefs = [{
            label: "医院类型",
            value: res.data.type
        }, {
            label: "上级企业",
            value: res.data.superiorenterprisename
        }, {
            label: "负责人",
            value: res.data.leader.map(v => v.name) || ""
        }];
        /*  {
            label: "企业等级",
            value: res.data.grade
        }, */
        /* 基本信息 */
        let list1 = [{
            label: "客户名称",
            value: res.data.enterprisename
        }, {
            label: "医院编号",
            value: res.data.sa_customersid
        }, {
            label: "erp编号",
            value: res.data.erpagentnum
        }, {
            label: "医院类型",
            value: res.data.type
        }, {
            label: "省市县",
            value: res.data.province ? [res.data.province, res.data.city, res.data.county] : ""
        }, {
            label: "详细地址",
            value: res.data.address
        }, {
            label: "合作状态",
            value: getApp().globalData.Language.getMapText(res.data.status),
            style: `color:${this.data.sColors[res.data.status]}`
        }, {
            label: "成交状态",
            value: res.data.tradingstatus,
            style: `color:${this.data.sColors[res.data.tradingstatus]}`
        }, {
            label: "成交次数",
            value: res.data.contact_signnum
        }, {
            label: "负责人",
            value: res.data.leader.map(v => v.name) || ""
        }, {
            label: "部门",
            value: res.data.leader.length ? res.data.leader[0].depname : ""
        }];
        /* 系统信息 */
        let 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.deletereason
        }, {
            label: "转手次数",
            value: res.data.leader[0] ? res.data.leader[0].leadernum : 0
        }];
        this.setData({
            briefs,
            list1,
            list2
        });
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    //局部数据更新 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 = model == "#Clue" ? this.data.detail.sa_customersid : this.data.detail.sys_enterpriseid;
            if (model == "#Files") init = true;
            if (total == null || init) {
                Component.getList(id, init);
            } else if (pageNumber <= pageTotal) {
                Component.getList(id, false);
            }
        }
    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags()
    },
    //更新团队成员
    getGroup() {
        this.selectComponent("#Group").getList().then(this.setTabbarList)
    },
    onReachBottom() {
        this.partialRenewal();
    },
    onUnload() {
        _Http.updateList && _Http.updateList()
        const page = getCurrentPages().find(v => v.__route__ == 'packageA/setclient/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: '20221012164402',
            content
        }).then(res => {
            console.log("更新客户列表", res);
            if (res.code == '1') {
                page.setData({
                    list: res.data,
                    "content.total": res.total
                })
                page.getTags()
            }
        })
    }
})