const _Http = getApp().globalData.http,
    currency = require("../../utils/currency"),
    CNY = value => currency(value, {
        symbol: "￥",
        precision: 2
    }).format();
Page({
    data: {
        loading: true,
        isLeader: false, //是否为负责人
        tabsActive: 0, //tabs 选中项
        sat_orderclueid: "",
        deletereasonShow: false,
        deletereason: "",
        invalidreasonShow: false,
        invalidreason: "",
        detail: '',
        siteShow: false,
        tabbarList: [],
        sColors: getApp().globalData.sColors,
    },
    onLoad(options) {
        getApp().globalData.Language.getLanguagePackage(this, '线索详情');
        const appAuth = wx.getStorageSync('auth').worderclue;
        let tabsList = [{
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }, {
            label: "跟进记录",
            icon: "icon-tabgenjinjilu",
            model: "#follow"
        }, {
            label: "线索来源",
            icon: "icon-tabxiansuo",
            model: "#Clue"
        }, {
            label: "联系人",
            icon: "icon-tablianxiren",
            model: "#Contacts"
        }, {
            label: "操作",
            icon: "icon-tabcaozuojilu1",
            model: "#Record"
        }];
        if (appAuth.isdatafollowup) tabsList.push({
            label: "跟进动态",
            icon: "icon-tabgenjinjilu",
            model: "#Trace"
        })
        if (appAuth.istask) tabsList.push({
            label: "任务",
            icon: "icon-tabrenwu",
            model: "#Work"
        })
        tabsList.push({
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        })
        this.setData({
            sat_orderclueid: options.sat_orderclueid || options.id,
            isAdmin: appAuth.options.some(v => v == "admin"), //是否具有管理权限
            tabsList,
            appAuth
        });
        this.getDetail();
    },
    getDetail() {
        _Http.basic({
            "classname": "saletool.orderclue.web.orderclue",
            "method": "selectDetail",
            "version": 1,
            "content": {
                "nocache": true,
                "sat_orderclueid": this.data.sat_orderclueid
            },
        }).then(res => {
            console.log("线索详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.data,
                icon: "none"
            });

            let list1 = [{
                label: "医院名称",
                value: res.data.enterprisename_customer
            }, {
                label: "联系人",
                value: res.data.name
            }, {
                label: "联系角色",
                value: res.data.contactsrole
            }, {
                label: "手机号/座机号码",
                value: res.data.phonenumber
            }, {
                label: "微信",
                value: res.data.wechatnum
            }, {
                label: "省市县",
                value: res.data.province ? res.data.province + res.data.city + res.data.county : ''
            }, {
                label: "地址",
                value: res.data.address
            }, {
                label: "项目名称",
                value: res.data.projectname
            }, {
                label: "项目规模",
                value: res.data.scale ? res.data.scale + res.data.unitname : ""
            }, {
                label: "总投资额(万元)",
                value: CNY(res.data.totalinvestment)
            }, {
                label: "造价(万元)",
                value: CNY(res.data.costofconstruction)
            }, {
                label: "预计开工时间",
                value: res.data.begdate_due
            }, {
                label: "预计完工时间",
                value: res.data.enddate_due
            }, {
                label: "市场活动",
                value: res.data.campaign_name
            }, {
                label: "领域",
                value: res.data.tradefield
            }, {
                label: "设计院",
                value: res.data.institute
            }, {
                label: "设计师",
                value: res.data.designer
            }, {
                label: "关联项目",
                value: res.data.projectname1
            }, {
                label: "来源",
                value: res.data.cluesource
            }, {
                label: "线索概况",
                value: res.data.notes
            }, {
                label: '负责人',
                value: res.data.leader && res.data.leader.length > 0 ? res.data.leader[0].name : ''
            }, {
                label: '上图员',
                value: res.data.uppictured
            }, {
                label: '分配状态',
                value: res.data.allocationstatus,
                style: `color:${this.data.sColors[res.data.allocationstatus]}`
            }, {
                label: '跟进状态',
                value: getApp().globalData.Language.getMapText(res.data.status),
                style: `color:${this.data.sColors[res.data.status]}`
            }];
            if (wx.getStorageSync('userMsg').siteid == 'HY') list1 = list1.filter(v => !["项目预算(万元)", "总投资额(万元)", "造价(万元)"].includes(v.label))

            this.setData({
                loading: false,
                detail: res.data,
                briefs: [{
                    label: "联系人",
                    value: res.data.name
                }, {
                    label: "手机号/座机号码",
                    value: res.data.phonenumber
                }, {
                    label: "市场活动",
                    value: res.data.campaign_name
                }, {
                    label: "领域",
                    value: res.data.tradefield
                }, {
                    label: '负责人',
                    value: res.data.leader && res.data.leader.length > 0 ? res.data.leader[0].name : ''
                }, {
                    label: '分配状态',
                    value: res.data.allocationstatus,
                    style: `color:${this.data.sColors[res.data.allocationstatus]}`
                }, {
                    label: '跟进状态',
                    value: getApp().globalData.Language.getMapText(res.data.status),
                    style: `color:${this.data.sColors[res.data.status]}`
                }, {
                    label: '跟进次数',
                    value: res.data.followcount || '0'
                }, {
                    label: '营销费用',
                    value: CNY(res.data.salesfeesamount || '0')
                }],
                list1,
                list2: [{
                    label: "创建人",
                    value: res.data.createBy
                }, {
                    label: "创建时间",
                    value: res.data.createDate
                }, {
                    label: "分配人",
                    value: res.data.assignedBy
                }, {
                    label: "分配时间",
                    value: res.data.assignedDate
                }, {
                    label: "最近跟进人",
                    value: res.data.followBy
                }, {
                    label: "最近跟进时间",
                    value: res.data.followDate
                }, {
                    label: "最近编辑人",
                    value: res.data.editBy
                }, {
                    label: "最近编辑时间",
                    value: res.data.editDate
                }, {
                    label: "无效原因",
                    value: res.data.invalidreason
                }, {
                    label: "作废原因",
                    value: res.data.deletereason
                }, {
                    label: "跟进次数",
                    value: res.data.followcount
                }, {
                    label: "转手次数",
                    value: res.data.leader[0].leadernum
                }]
            });
            /* 更新列表中状态 */
            let page = getCurrentPages().find(v => v.__route__ == 'packageA/saleClue/index');
            if (page) {
                let index = page.data.list.findIndex(v => v.sat_orderclueid == res.data.sat_orderclueid);
                if (index != -1) page.setData({
                    [`list[${index}].status`]: res.data.status
                })
            }
            if (this.data.appAuth.isdatatag) this.getTags();
            if (this.data.appAuth.isdatateam) this.getGroup();
            this.setTabbarList()
            this.partialRenewal();
        })
    },
    async setTabbarList() {
        let tabbarList = [{
                icon: "color-genjin",
                label: "跟进"
            }],
            detail = this.data.detail,
            isLeader = detail.leader.some(v => v.userid == wx.getStorageSync('userMsg').userid),
            editdataleader = isLeader ? 1 : 0;
        if (!isLeader) {
            let res = await getApp().agentOrNot("sat_orderclue", this.data.sat_orderclueid),
                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 (wx.getStorageSync('auth').worderclue.options.some(v => v == "shiftSite")) {
            tabbarList.push({
                icon: "icon-CRM",
                label: "转站点"
            })
            this.setData({
                siteShow: true
            })
        }
        if (this.data.isAdmin || isLeader) tabbarList.push({
            icon: "color-bianji",
            label: "编辑"
        })

        if (wx.getStorageSync('userMsg').siteid == 'HY') {
            if (this.data.appAuth.options.includes('transferAudit') && detail.iscustomer == 0 && detail.istransformingtocustomer == 1) tabbarList.push({
                icon: "icon-zhuanhuashenhe",
                label: "转化客户审核"
            })
            if (this.data.appAuth.options.includes('transferProjectReview') && detail.isproject == 0 && detail.istransformingtoproject == 1) tabbarList.push({
                icon: "icon-zhuanhuashenhe",
                label: "转化项目审核"
            })
        }
        if (this.data.isAdmin || isLeader) {
            if (detail.iscustomer == 0 && detail.istransformingtocustomer == 0) tabbarList.push({
                icon: "icon-dibu-zhuanhuan",
                label: "转化客户"
            })
            if (detail.isproject == 0 && detail.istransformingtoproject == 0) tabbarList.push({
                icon: "icon-dibu-zhuanhuan",
                label: "转化项目"
            })
            if (editdataleader) tabbarList.push({
                icon: "color-genghuanfuzeren",
                label: "更换负责人"
            })
        }
        if (isLeader) {
            tabbarList.push({
                icon: "icon-dibu-wuxiao",
                label: "无效"
            })
            if (detail.isprivate == 0) tabbarList.push({
                icon: "icon-dibu-tuihui",
                label: "退回"
            })
        }
        if (detail.status == '已转化') tabbarList = tabbarList.filter(item => {
            return item.label == '编辑' || item.label == '跟进' || item.label == '转化客户' || item.label == '转化项目' || item.label == '转化项目审核' || item.label == '转化客户审核'
        })
        if (detail.isproject) tabbarList = tabbarList.filter(v => v.label != '转化项目')
        if (detail.iscustomer) tabbarList = tabbarList.filter(v => v.label != '转化客户')
        if (detail.status != '待跟进' && detail.status != '跟进中' && detail.status != '已转化') tabbarList = [];
        tabbarList.push({
            icon: "icon-dibu-jieshu",
            label: "作废"
        })
        this.setData({
            tabbarList,
            isLeader,
            isFollow: tabbarList.some(v => v.label == '跟进')
        })
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    getTags() {
        if (this.data.appAuth.isdatatag) this.selectComponent("#Tags").getTags();
    },
    //更新团队成员
    getGroup() {
        if (this.data.appAuth.isdatateam) 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.sat_orderclueid;
            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/saleClue/addClue?rowData=${JSON.stringify(this.data.detail)}`,
                })
                break;
            case "作废":
                that.setData({
                    deletereasonShow: true
                })
                break;
            case "无效":
                that.setData({
                    invalidreasonShow: true
                })
                break;
            case "转站点":
                that.selectComponent("#ShiftSite").showSite()
                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: ({
                        confirm
                    }) => {
                        if (confirm) _Http.basic({
                            "id": 20221207160802,
                            "content": {
                                sat_orderclueid: data.sat_orderclueid
                            }
                        }).then(res => {
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('退回成功') : res.msg,
                                icon: "none"
                            });
                            setTimeout(() => {
                                let page = getCurrentPages().find(v => v.__route__ == 'packageA/saleClue/index');
                                if (page) page.getList(true)
                                wx.navigateBack();
                            }, 500)
                        })
                    }
                })
                break;
            case "转化项目":
                wx.navigateTo({
                    url: `/packageA/saleClue/change?rowData=${JSON.stringify(this.data.detail)}`,
                })
                break;
            case "转化客户":
                let detail = this.data.detail;
                delete detail.leader;
                wx.navigateTo({
                    url: `/packageA/saleClue/translate?data=${JSON.stringify(detail)}`,
                })
                break;
            case "转化项目审核":
                wx.navigateTo({
                    url: `/packageA/saleClue/audit/project?data=${JSON.stringify(this.data.detail)}`,
                })
                break;
            case "转化客户审核":
                wx.navigateTo({
                    url: `/packageA/saleClue/audit/client?data=${JSON.stringify(this.data.detail)}`,
                })
                break;
            case "跟进":
                wx.navigateTo({
                    url: `/packageA/publicClue/modules/follow/insert?sat_orderclueid=` + this.data.detail.sat_orderclueid + '&resource=销售线索'
                })
                _Http.changeItem = this.updateFollowList.bind(this)
                break;
            case "更换负责人":
                wx.navigateTo({
                    url: `/pages/group/select?data=${JSON.stringify({
                             ownertable:"sat_orderclue",
                             ownerid:data.sat_orderclueid,
                        })}&radio=true&principal=true`,
                })
                break;
        }
    },
    updateFollowList() {
        this.selectComponent("#follow").getList(this.data.sat_orderclueid, 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: "sat_orderclue",
                                ownerid: that.data.detail.sat_orderclueid,
                                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
                                });
                            }, 300)
                        })
                    }
                })
            }
        })
    },
    onUnload() {
        const page = getCurrentPages().find(v => v.__route__ == 'packageA/saleClue/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: '20221101094502',
            content
        }).then(res => {
            console.log("更新线索列表", res);
            if (res.code == '1') {
                page.setData({
                    list: res.data,
                    "content.total": res.total
                })
                page.getTags();
            }
        })
    },
    /* 完成情况说明输入 */
    areaInput(e) {
        this.setData({
            [e.currentTarget.dataset.name]: e.detail.value
        })
    },
    /* 确认无效 */
    invalidItem() {
        let that = this;
        _Http.basic({
            id: "20221208100602",
            "content": {
                "sat_orderclueid": this.data.detail.sat_orderclueid,
                sat_ordercluefollowuplogid: 0,
                "content": this.data.invalidreason,
                "followupmode": "",
                "logtype": "无效",
                "competitor": ""
            }
        }).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(() => {
                this.getDetail();
                this.selectComponent("#follow").getList(that.data.detail.sat_orderclueid, true)
                this.onCancel()
                this.setData({
                    invalidreason: ""
                })
            }, 300)
        })
    },
    deleteItem() {
        let that = this;
        _Http.basic({
            "id": 20221123193702,
            "content": {
                "sat_orderclueids": [this.data.detail.sat_orderclueid],
                deletereason: this.data.deletereason
            }
        }).then(res => {
            wx.showToast({
                title: res.code == '1' ? getApp().globalData.Language.getMapText('操作成功') : res.msg,
                icon: "none"
            });
            this.onCancel();
            this.setData({
                deletereason: ""
            })
            that.getDetail();
            setTimeout(() => {
                let pages = getCurrentPages(),
                    page = pages[pages.length - 2];
                if (page.getList) page.setData({
                    list: page.data.list.filter(v => v.sat_orderclueid != that.data.detail.sat_orderclueid),
                    "content.total": page.data.content.total - 1,
                })
            }, 300)
        })
    },
    onCancel() {
        this.setData({
            deletereasonShow: false,
            invalidreasonShow: false,
        })
    }
})