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

Page({
    data: {
        content: {},
        detail: {},
    },
    onLoad(options) {
        getApp().globalData.Language.getLanguagePackage(this, '联系人详情')

        options.groupname && delete options.groupname;
        options.sys_phonebookid = options.id;
        options.nocache = true;
        this.data.content = options;
        this.getDetail();

        const auth = wx.getStorageSync('auth').waddresslist;
        let tabsList = [{
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }, {
            label: "关联线索",
            icon: "icon-tabxiansuo",
            model: "#Clue"
        }, {
            label: "关联客户",
            icon: "icon-tabkehu",
            model: "#Client"
        }, {
            label: "关联项目",
            icon: "icon-xiangmu",
            model: "#Project"
        }];
        if (auth.isdatafollowup) tabsList.push({
            label: "跟进动态",
            icon: "icon-tabgenjinjilu",
            model: "#Trace"
        })
        if (auth.istask) tabsList.push({
            label: "任务",
            icon: "icon-tabrenwu",
            model: "#Work"
        })
        tabsList = tabsList.concat([{
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        }, {
            label: "操作记录",
            icon: "icon-tabcaozuojilu1",
            model: "#Record"
        }])
        this.setData({
            tabsList,
            auth,
            options: auth.options
        })
    },
    getDetail() {
        _Http.basic({
            "id": "20220914135203",
            "content": this.data.content
        }).then(res => {
            console.log("联系人详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.msg,
                icon: "none"
            })
            res.data.showSalesfeesamount = CNY(res.data.salesfeesamount);
            this.setData({
                detail: res.data
            })
            if (this.data.tabsActive == 1) {
                this.partialRenewal(true);
            }
            if (this.data.auth.isdatatag) this.getTags()
            if (this.data.auth.isdatateam) this.getGroup()
            this.setPreview(res.data);
            this.setTabbarList()
        })
    },
    //详情按钮回调
    tabbarOnClick({
        detail
    }) {
        let data = this.data.detail,
            that = this;
        if (data.NAME) data.name = data.NAME;
        switch (detail.label) {
            case "跟进":
                this.selectComponent("#Trace").insetr();
                break;
            case "呼叫":
                wx.makePhoneCall({
                    phoneNumber: data.phoneNumber || data.telephone,
                })
                break;
            case "更换负责人":
                wx.navigateTo({
                    url: `/pages/group/select?data=${JSON.stringify({
                                             ownertable:'sys_phonebook',
                                             ownerid:this.data.detail.sys_phonebookid,
                                        })}&radio=true&principal=true`,
                })
                break;

            case "编辑":
                data.sys_enterpriseids = [
                    [],
                    []
                ];
                data.sa_customers.forEach(v => {
                    data.sys_enterpriseids[0].push(v.name)
                    data.sys_enterpriseids[1].push(v.sys_enterpriseid)
                })
                let detail = JSON.stringify(data);
                wx.navigateTo({
                    url: '/packageA/contacts/insert?data=' + detail,
                })
                break;
            case "删除":
                that.deleteData();
                break;
        }
    },
    /* 删除 */
    deleteData() {
        let that = this;
        const contacts = this.data.detail;
        let content = getApp().globalData.Language.getMapText('是否确认删除') + (contacts.name || contacts.NAME)
        if (contacts.islinkcustomer || contacts.islinkproject) content = getApp().globalData.Language.getMapText('当前联系人已存在关联客户/项目，是否确定删除')
        wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content,
            cancelText: getApp().globalData.Language.getMapText('取消'),
            confirmText: that.data.language['确定'] || '确定删除',
            success({
                confirm
            }) {
                if (confirm) _Http.basic({
                    "id": "20220831164703",
                    "version": 1,
                    "content": {
                        "sys_phonebookid": contacts.sys_phonebookid
                    }
                }).then(res => {
                    console.log("删除", res)
                    if (res.code != '1') return wx.showToast({
                        title: res.data || res.msg,
                        icon: "none"
                    })
                    getApp().globalData.Language.showToast('删除成功')
                    setTimeout(() => {
                        wx.navigateBack()
                    }, 500);
                })
            }
        })
    },
    /* 设置tabbar */
    async setTabbarList() {
        let detail = this.data.detail,
            isLeader = detail.leaderid == wx.getStorageSync('userMsg').userid,
            tabbarList = [{
                icon: "icon-guanlian-bodadianhua",
                label: "呼叫"
            }],
            editdataleader = isLeader;
        if (!isLeader) {
            let res = await getApp().agentOrNot('sys_phonebook', this.data.detail.sys_phonebookid),
                data = res.code == '1' ? res.data : {
                    editable: 0,
                    editdataleader: 0
                }
            if (this.data.auth.isdatateam) isLeader = this.selectComponent("#Group").data.editable == 1;
            if (!isLeader) isLeader = data.editable == 1;
            editdataleader = data.editdataleader;
        }
        if (this.data.auth.isdatafollowup) tabbarList.unshift({
            icon: "color-genjin",
            label: "跟进"
        })
        if (editdataleader) tabbarList.push({
            icon: "color-genghuanfuzeren",
            label: "更换负责人"
        })
        if (!isLeader) {
            let s = await getApp().agentOrNot('sys_phonebook', this.data.detail.sys_phonebookid);
            isLeader = s.data.editable == 1;
        }
        if (isLeader) tabbarList = tabbarList.concat({
            icon: "color-bianji",
            label: "编辑"
        }, {
            icon: "icon-shanchu",
            label: "删除"
        })
        this.setData({
            tabbarList,
            isLeader
        });
    },
    setPreview(item) {
        this.setData({
            list1: [{
                label: "姓名",
                value: item.NAME || item.name || '--'
            }, {
                label: "联系方式",
                value: item.phonenumber || item.telephone || '--'
            }, {
                label: "分级",
                value: item.grade || '--'
            }, {
                label: "性别",
                value: item.sex || '--'
            }, {
                label: "生日",
                value: item.birthday || '--'
            }, {
                label: "家庭地址",
                value: item.homeaddress || '--'
            }, {
                label: "微信",
                value: item.wechatnum || '--'
            }, {
                label: "邮箱",
                value: item.email || '--'
            }, {
                label: "传真",
                value: item.fax || '--'
            }, {
                label: "部门",
                value: item.depname || '--'
            }, {
                label: "职位",
                value: item.position || '--'
            }, {
                label: "群组",
                value: item.groupname || '--'
            }, {
                label: "偏好",
                value: item.preference || '--'
            }, {
                label: "爱好",
                value: item.hobby || '--'
            }, {
                label: "备注",
                value: item.remarks || '--'
            }, {
                label: "负责人",
                value: item.leader || '--'
            }],
            list2: [{
                label: "创建人",
                value: item.createby || '--'
            }, {
                label: "创建时间",
                value: item.createdate || '--'
            }, {
                label: "最近编辑人",
                value: item.changeby || '--'
            }, {
                label: "最近编辑时间",
                value: item.changedate || '--'
            }, {
                label: "最近跟进人",
                value: item.followupby || '--'
            }, {
                label: "最近跟进时间",
                value: item.followupdate || '--'
            }, {
                label: "转手次数",
                value: item.leadernum || '0'
            }]
        })

    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags();
    },
    getGroup() {
        this.selectComponent("#Group").getList().then(this.setTabbarList)
    },
    //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 = this.data.detail.sys_phonebookid;
            if(model == "#Files") init = true;
            if (total == null || init) {
                Component.getList(id, init);
            } else if (pageNumber <= pageTotal) {
                Component.getList(id, false);
            }
        }
    },
    /* 更换负责人 */
    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: 'sys_phonebook',
                                ownerid: that.data.detail.sys_phonebookid,
                                userid: arr[0],
                                isaddoldleader: s.confirm ? 1 : 0
                            }
                        }).then(res => {
                            console.log("更换负责人", res)
                            if (res.code != '1') return wx.showToast({
                                title: res.msg,
                                icon: "none"
                            });
                            wx.showToast({
                                title: getApp().globalData.Language.getMapText('更换成功'),
                                icon: "none",
                                mask: true
                            });
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 2
                                });
                            }, 300)
                        })
                    }
                })
            }
        })
    },
    onShow() {
        _Http.updateList = function () {
            ["#Clue", "#Client", "#Project"].forEach(modle => {
                try {
                    const page = this.selectComponent(modle)
                    page && page.updateList()
                } catch (error) {

                }
            })
        }.bind(this);
    },
    onUnload() {
        _Http.getGroup && _Http.getGroup(true)
        _Http.updateList && _Http.updateList(true)
    },
})