let _Http = getApp().globalData.http,
    count = null;

Page({
    data: {
        showAll: false,
        repetitionShow: false,
        repetitionList: [],
        isSubmit: false,
        content: {},
        disabled: true,
        countDown: "", //查重倒计时
        superaddition: {
            sys_phonebookid: 0,
            oldcontactsid: 0,
        }
    },
    queryClient() {
        let data = this.selectComponent("#Form").query();
        if (data.enterprisename == '') {
            wx.showToast({
                title: `您还未填写企业名称`,
                icon: "none"
            });
        } else {
            this.setData({
                form: this.selectComponent("#Form").data.form,
            })
            this.selectComponent("#Info").queryClient(data.enterprisename)
        }
    },
    /* 打开通讯录 */
    openContacts() {
        let that = this;
        wx.navigateTo({
            url: '/packageA/setclient/contacts',
        })
        getApp().globalData.handleSelect = (item) => {
            wx.showModal({
                title: getApp().globalData.Language.getMapText('提示'),
                content: getApp().globalData.Language.getMapText('是否确定选择') + item.name,
                cancelText: getApp().globalData.Language.getMapText('取消'),
                confirmText: getApp().globalData.Language.getMapText('确定'),
                complete: ({
                    confirm
                }) => {
                    if (confirm) {
                        console.log(item)
                        let page = that.selectComponent("#Form");
                        let form = page.data.form,
                            index = form.findIndex(v => v.label == '联系人');
                        form[index].value = item.name;
                        if (item.phonenumber.indexOf('-') !== -1) {
                            form[index + 1].value = "1";
                            form[index + 2] = {
                                label: "座机电话",
                                error: false,
                                errMsg: "",
                                type: "telephone",
                                value: item.phonenumber.split("-"),
                                valueName: "telephone1",
                                required: true,
                                checking: "telephone"
                            }
                        } else {
                            form[index + 1].value = "0";
                            form[index + 2] = {
                                label: "手机号",
                                error: false,
                                errMsg: "",
                                type: "number",
                                value: item.phonenumber,
                                placeholder: "联系人手机号码",
                                valueName: "phonenumber1",
                                required: true,
                                checking: "phone"
                            }
                        }
                        that.setData({
                            form,
                            superaddition: {
                                sys_phonebookid: item.sys_phonebookid || 0,
                                oldcontactsid: item.contactsid || 0,
                            }
                        })
                        console.log(this.data.superaddition)
                        wx.navigateBack()
                        getApp().globalData.handleSelect = null;
                        page.confirm()
                    }
                }
            })
        };
    },
    /* 打断 */
    interrupt({
        detail
    }) {
        let {
            data,
            form,
            temporary
        } = detail;
        if (data.label == '联系方式') {
            let index = temporary.index + 1;
            if (data.value == 0) {
                data.telephone = form[index].value;
                if (data.telephone.join() == ',') data.telephone = "";
                form[index] = {
                    label: "手机号",
                    error: false,
                    errMsg: "",
                    type: "number",
                    value: data.phonenumber,
                    placeholder: "联系人手机号码",
                    valueName: "phonenumber1",
                    required: true,
                    checking: "phone"
                }
            } else {
                if (typeof (form[index].value) == 'object') form[index].value = "";
                data.phonenumber = form[index].value;
                form[index] = {
                    label: "座机电话",
                    error: false,
                    errMsg: "",
                    type: "telephone",
                    value: data.telephone || ["", ""],
                    valueName: "telephone1",
                    required: true,
                    checking: "telephone"
                }
            };
            this.setData({
                form
            })
        }
    },
    /* 工商查询 */
    introduce({
        detail
    }) {
        let item = detail;
        let data = {
            enterprisename: item.companyName, //企业名称
            taxno: item.taxNum, //税号
            contact: item.legalPerson, //法人
            region: [item.regProvince ? item.regProvince : item.regCity, item.regCity, item.regArea], //地区
            address: item.address, //地区
            phonenumber: item.phone,
        }
        this.setData({
            form: this.data.form.map(v => {
                if (v.valueName == "enterprisename") v.errMsg = '';
                if (data[v.valueName]) v.value = data[v.valueName];
                return v
            })
        })
    },
    setOption(item) {
        let i = this.data.form.findIndex(v => v.valueName == item.valueName);
        this.setData({
            [`form[${i}]`]: item
        })
    },
    onLoad(options) {
        getApp().globalData.Language.getLanguagePackage(this, '转化客户');
        if (options.data) {
            let data = JSON.parse(options.data);
            data.source = data.cluesource; //来源
            data.phonenumber1 = data.phonenumber;
            data.phonenumber = data.co_phonenumber;
            data.taxno = data.co_taxno;
            data.contact = data.co_name;

            let form = [{
                label: "医院名称",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "医院名称",
                valueName: "enterprisename",
                checking: "base",
                slot: "info",
                required: true
            }, {
                label: "企业简称",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "企业简称",
                valueName: "abbreviation",
                checking: "base",
                required: false
            }, {
                label: "医院类型",
                error: false,
                errMsg: "",
                type: "option",
                optionNmae: "customertypemx",
                optionType: "radio", //复选   radio 单选
                value: "",
                placeholder: "医院类型",
                valueName: "type",
                checking: "base",
                required: true
            }, {
                label: "客户分类",
                error: false,
                errMsg: "",
                type: "option",
                optionNmae: "customergrade",
                optionType: "radio", //复选   radio 单选
                value: "",
                placeholder: "客户分类",
                valueName: "customergrade",
                checking: "base",
                required: false
            }, {
                label: "客户行业",
                error: false,
                errMsg: "",
                type: "option", //自定义选择  配合预定接口
                optionNmae: "industry", //选择类型
                optionType: "checkbox", //复选   radio 单选
                value: "",
                placeholder: "客户所属行业",
                valueName: "industry",
                checking: "base",
                required: false
            }, {
                label: "税号",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "企业税号",
                valueName: "taxno",
                checking: "base",
                required: false
            }, {
                label: "法人",
                error: false,
                errMsg: "",
                type: "text",
                value: "",
                placeholder: "企业法人",
                valueName: "contact",
                checking: "base",
                required: false
            }, {
                label: "联系电话",
                error: false,
                errMsg: "",
                type: "number",
                value: "",
                placeholder: "联系电话",
                valueName: "phonenumber",
                required: false
            }, {
                label: "省市县",
                error: false,
                errMsg: "",
                type: "region",
                value: [],
                placeholder: "所在地区",
                valueName: "region",
                required: true
            }, {
                label: "详细地址",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "详细地址",
                valueName: "address",
                checking: "base",
                required: false
            }, {
                label: "上级企业",
                error: false,
                errMsg: "",
                type: "route",
                url: "/packageA/select/setclient/select",
                value: "",
                params: {
                    id: 20221012164402,
                    content: {
                        nocache: true,
                        "type": 1,
                        "isExport": 0,
                        isend: 0,
                        "where": {
                            "condition": "",
                            "status": "", //状态
                            "startdate": "",
                            "enddate": ""
                        },
                        "sort": [{
                            sortname: "默认",
                            sorted: 1,
                            sortid: 67,
                            reversed: 0
                        }]
                    },
                },
                query: "&radio=true&idname=sa_customersid",
                placeholder: "选择上级企业",
                valueName: "parentid",
                checking: "base",
                required: false
            }, {
                label: "客户来源",
                error: false,
                errMsg: "",
                type: "selector",
                range: [],
                rangeKey: "name",
                selectKey: "value",
                rangeIndex: "",
                value: "",
                placeholder: "来源",
                valueName: "source",
                checking: "base",
                required: true
            }, {
                label: "归属经销商",
                error: false,
                errMsg: "",
                type: "route",
                url: "/packageA/select/setclient/select",
                value: "",
                params: {
                    "id": 20230214162602,
                    "content": {
                        "hrid": wx.getStorageSync('userMsg').hrid,
                        "where": {
                            "condition": ""
                        }
                    },
                },
                query: "&radio=true&idname=sa_agentsid",
                placeholder: "归属经销商",
                valueName: "sa_agentsid",
                checking: "base",
                required: false
            }].map(v => {
                if (v.valueName == 'enterprisename') {
                    v.value = data.enterprisename_customer;
                } else if (v.valueName != 'region') {
                    v.value = data[v.valueName] || '';
                } else {
                    v.value = data.province ? [data.province, data.city, data.county] : []
                }
                return v
            })

            let isTelephone = data.phonenumber1.indexOf("-") != -1 ? "1" : "0";
            form.splice(5, 0, isTelephone == 0 ? {
                label: "手机号",
                error: false,
                errMsg: "",
                type: "number",
                value: data.phonenumber1 || '',
                placeholder: "联系人手机号码",
                valueName: "phonenumber1",
                required: true,
                checking: "phone"
            } : {
                label: "座机电话",
                error: false,
                errMsg: "",
                type: "telephone",
                value: data.phonenumber1.split("-"),
                valueName: "telephone1",
                required: true,
                checking: "telephone"
            })
            form.splice(5, 0, {
                label: "联系方式",
                error: false,
                errMsg: "",
                hint: "",
                type: "radio",
                value: isTelephone,
                radioList: [{
                    id: '0',
                    name: '手机号'
                }, {
                    id: '1',
                    name: '座机电话'
                }],
                valueName: "isTelephone", //绑定的字段名称
                required: true, //必填
                interrupt: true,
                checking: `true`,
                phonenumber: "",
                telephone: ["", ""]
            })
            form.splice(5, 0, {
                label: "联系人",
                error: false,
                errMsg: "",
                type: "textarea",
                value: data.name,
                placeholder: "联系人名称",
                valueName: "name",
                checking: "base",
                slot: "TXL",
                required: true
            })
            /* 获取来源 */
            _Http.basic({
                "classname": "sysmanage.develop.optiontype.optiontype",
                "method": "optiontypeselect",
                "content": {
                    "typename": "cluesource",
                    pageSize: 9999
                }
            }).then(res => {
                console.log("获取线索来源", res)
                if (res.code == '1') {
                    let item = form.find(v => v.label == '客户来源');
                    item.range = res.code == '1' ? res.data.map(v => {
                        v.name = getApp().globalData.Language.getMapText(v.value)
                        return v
                    }) : [];
                    this.setData({
                        form
                    })
                }
            })
            this.setData({
                content: {
                    sat_orderclueid: data.sat_orderclueid,
                    parentid: data.parentid || 0,
                },
                form
            })
            _Http.basic({
                id: 2024060715002601,
                content: {
                    companyName: data.enterprisename_customer,
                }
            }).then(res => {
                console.log("工商查询", res)
                if (res.data.address) {
                    /*      const index = form.findIndex(v => v.valueName == 'region')
                         form[index].value = [res.data.regCity, res.data.regCity, res.data.regArea]
                         form[index + 1].value = res.data.address
                         this.setData({
                             form
                         }) */
                    _Http.basic({
                        id: 20221208103601,
                        content: {
                            pageNumber: 1,
                            pageTotal: 1,
                            pageSize: 5,
                            keyword: res.data.companyName,
                        }
                    }).then(s => {
                        console.log("工商查询", res)
                        let item = Object.assign(s.data[0] || {}, res.data);
                        let data = {
                            enterprisename: item.companyName, //企业名称
                            taxno: item.taxNum, //税号
                            contact: item.legalPerson, //法人
                            region: [item.regProvince ? item.regProvince : item.regCity, item.regCity, item.regArea], //地区
                            address: item.address, //地区
                            phonenumber: item.phone,
                        }
                        this.setData({
                            form: this.data.form.map(v => {
                                if (data[v.valueName]) v.value = data[v.valueName];
                                return v
                            })
                        })
                    })
                } else {
                    form[0].errMsg = '请完善客户名称，该客户名称无法匹配工商信息，不可转化！'
                    this.setData({
                        form
                    })
                }
            })
        }
        if (wx.getStorageSync('userMsg').siteid == 'HY') {
            this.setData({
                form: this.data.form.map(v => {
                    if (["customergrade", "industry"].includes(v.valueName)) v.required = true;
                    return v
                })
            })
        }
    },
    repClose() {
        return this.setData({
            repetitionShow: false,
            isSubmit: false
        })

        if (this.data.isSubmit) {
            let 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: (res) => {
                    if (res.confirm) that.handleSubmit(true);
                }
            })
        }
        this.setData({
            repetitionShow: false,
            isSubmit: false
        })
    },
    /* 表单必填项是否完成 */
    onConfirm({
        detail
    }) {
        this.setData({
            disabled: detail
        })
    },
    // 是否显示全部
    onChange({
        detail
    }) {
        this.setData({
            showAll: detail
        })
    },
    /* 查询是否重复 */
    async queryRepetition(e) {
        let data = this.selectComponent("#Form").query();
        /* if (data.enterprisename == '') return wx.showToast({
            title: `您还未填写企业名称`,
            icon: "none"
        }); */
        data.province = data.region[0] || "";
        data.city = data.region[1] || "";
        data.county = data.region[2] || "";
        let res = await this.handleQueryRepetition({
            sa_customersid: this.data.content.sa_customersid || 0,
            ...data
        });
        console.log("查询重复", res)
        if (res.code != '1') return wx.showToast({
            title: res.msg,
            icon: "none"
        });
        this.setData({
            countDown: 6
        });
        count = setInterval(() => {
            let countDown = this.data.countDown;
            if (countDown == 0) {
                clearInterval(count);
                this.setData({
                    countDown: ""
                })
            } else {
                countDown--;
                this.setData({
                    countDown
                })
            }
        }, 1000)
        if (res.total == 0) {
            getApp().globalData.Language.modeBoxPrompts('未查询到疑似重复的客户信息')
        } else {
            getApp().globalData.Language.showToast([{
                t: 1,
                v: '查询到',
                r: " "
            }, {
                v: res.total,
                r: " "
            }, {
                t: 1,
                v: '条疑似重复客户信息,不允许保存',
            }])
            this.setData({
                repetitionShow: true,
                repetitionList: res.data.map(v => {
                    v.chars = v.chars.reduce((acc, item) => ({
                        ...acc,
                        ...item
                    }), {});
                    return v
                })
            })
        }
    },
    /* 处理查重 */
    handleQueryRepetition(content) {
        return _Http.basic({
            "id": 20221208172002,
            content
        })
    },
    async submit() {
        let data = this.selectComponent("#Form").submit();
        data.province = data.region[0] || "";
        data.city = data.region[1] || "";
        data.county = data.region[2] || "";
        let query = await this.handleQueryRepetition({
            sa_customersid: this.data.content.sa_customersid || 0,
            ...data
        });
        if (query.total != 0) {
            wx.showModal({
                content: getApp().globalData.Language.joint([{
                    t: 1,
                    v: '查询到',
                    r: " "
                }, {
                    v: query.total,
                    r: " "
                }, {
                    t: 1,
                    v: '条疑似重复客户信息,不可转化客户',
                }]),
                confirmText: this.data.language['确定'] || "我知道了"
            })
            this.setData({
                repetitionShow: true,
                repetitionList: query.data.map(v => {
                    v.chars = v.chars.reduce((acc, item) => ({
                        ...acc,
                        ...item
                    }), {});
                    return v
                }),
                isSubmit: true
            })
        } else {
            this.handleSubmit();
        }
    },
    handleSubmit(tag = false) {
        let data = Object.assign(this.selectComponent("#Form").submit(), this.data.superaddition)
        data.province = data.region[0] || "";
        data.city = data.region[1] || "";
        data.county = data.region[2] || "";
        data.parentid = data.parentid[1] ? data.parentid[1][0] : 0;
        data.sa_agentsid = data.sa_agentsid[1] ? data.sa_agentsid[1][0] : 0;
        delete(data.region);
        data.contactsinfo = {
            "name": data.name,
            "telephone": "",
            "phonenumber": data.isTelephone == 0 ? data.phonenumber1 || '' : data.telephone1.join("-") || ''
        }
        console.log(data)
        _Http.basic({
            "id": 20221216184302,
            "content": {
                ...this.data.content,
                ...data,
            }
        }).then(res => {
            console.log("转化客户", res)
            if (res.code != '1') return wx.showToast({
                title: res.data,
                icon: "none"
            })
            getApp().globalData.Language.showToast(wx.getStorageSync('userMsg').siteid != 'HY' ? '提交成功' : '转化成功')
            //绑定疑似重复标签
            if (tag) _Http.basic({
                "id": 20220929090901,
                "content": {
                    "ownertable": "sa_customers",
                    "ownerid": res.data.sa_customersid,
                    "datatag": ["疑似重复"]
                }
            })
            setTimeout(() => {
                if (wx.getStorageSync('userMsg').siteid == 'HY') {
                    getCurrentPages().forEach(v => {
                        if (v.__route__ == 'packageA/saleClue/detail') v.getDetail()
                    })
                    wx.navigateBack()
                } else {
                    getCurrentPages().forEach(v => {
                        switch (v.__route__) {
                            case 'packageA/saleClue/index':
                                v.getList(true);
                                break;
                            case 'packageA/setclient/detail':
                                v.getDetail();
                                break;
                        }
                    })
                    let pages = getCurrentPages();
                    if (pages[pages.length - 2].__route__ == 'packageA/saleClue/detail') {
                        wx.navigateBack();
                        getCurrentPages().forEach(item => {
                            console.log(item);
                            if (item.__route__ == 'packageA/saleClue/detail') {
                                item.getDetail()
                            }
                        })
                        wx.navigateTo({
                            url: '/packageA/setclient/detail?id=' + res.data.sa_customersid,
                        })
                    }
                }
            }, tag ? 500 : 300)
        })
    },
})