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

    /* {
            label: "企业等级",
            error: false,
            errMsg: "",
            type: "option",
            optionNmae: "agentgrade",
            optionType: "radio", //复选   radio 单选
            value: "",
            placeholder: "企业等级",
            valueName: "grade",
            checking: "base",
            required: false
        }, */

Page({
    data: {
        loading: false,
        repetitionShow: false,
        repetitionList: [],
        isSubmit: false,
        showAll: false,
        oldcontactsid: 0,
        sys_phonebookid: 0,
        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: "route",
            url: "/packageA/publicCustomer/pond/index",
            value: "",
            params: {
                "id": 20221206195102,
                "content": {
                    nocache: true,
                    "where": {
                        "condition": ""
                    }
                }
            },
            query: "&radio=true",
            placeholder: "选择所属公海池",
            valueName: "sa_customerpoolid",
            checking: "base",
            required: true
        }, {
            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: "telephone",
            required: false
        }, {
            label: "省市县",
            error: false,
            errMsg: "",
            type: "region",
            value: [],
            placeholder: "所在地区",
            valueName: "region",
            required: false
        }, {
            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,
                valueKey: "sa_customersid",
                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",
            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
        }],
        content: {
            "sa_customersid": 0, //新增是传0
            "sys_enterpriseid": 0, //合作企业档案ID，新增是传0，更新
            phonenumber: "",
        },
        disabled: true,
        countDown: "", //查重倒计时
    },
    setOption(item) {
        let i = this.data.form.findIndex(v => v.valueName == item.valueName);
        this.setData({
            [`form[${i}]`]: item
        })
    },
    /* 打开通讯录 */
    openContacts() {
        let that = this;
        let page = that.selectComponent("#Form");
        let form = page.data.form,
            index = form.findIndex(v => v.label == '联系人');
        if (form[index].disabled) return;

        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) {
                        form[index].value = item.name;
                        that.data.oldcontactsid = item.contactsid
                        that.data.sys_phonebookid = item.sys_phonebookid
                        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: "phonenumber",
                                required: true,
                                checking: "phone"
                            }
                        }
                        that.setData({
                            form
                        })
                        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: "phonenumber",
                    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
            })
        }
    },
    onLoad(options) {
        getApp().globalData.Language.getLanguagePackage(this, '设置公海客户');
        if (options.data) {
            let data = JSON.parse(options.data);
            let form = this.data.form.map(v => {
                if (v.valueName != 'region') {
                    v.value = data[v.valueName];
                    if (v.valueName == "grade") v.value = data[v.valueName] + "";
                } else {
                    v.value = data.province ? [data.province, data.city, data.county] : []
                }
                return v
            })
            try {
                let contactsinfo = data.contactsinfo[0];
                let isTelephone = contactsinfo.telephone ? "1" : "0";
                form.splice(5, 0, isTelephone == 0 ? {
                    label: "手机号",
                    error: false,
                    errMsg: "",
                    type: "number",
                    value: contactsinfo.phonenumber || '',
                    placeholder: "联系人手机号码",
                    valueName: "phonenumber",
                    required: false,
                    checking: "phone",
                    disabled: true
                } : {
                    label: "座机电话",
                    error: false,
                    errMsg: "",
                    type: "telephone",
                    value: contactsinfo.telephone.split("-"),
                    valueName: "telephone1",
                    required: false,
                    checking: "telephone",
                    disabled: true
                })
                form.splice(5, 0, {
                    label: "联系方式",
                    error: false,
                    errMsg: "",
                    hint: "",
                    type: "radio",
                    value: isTelephone,
                    radioList: [{
                        id: '0',
                        name: '手机号'
                    }, {
                        id: '1',
                        name: '座机电话'
                    }],
                    valueName: "isTelephone", //绑定的字段名称
                    required: false, //必填
                    interrupt: true,
                    checking: `true`,
                    phonenumber: "",
                    telephone: ["", ""],
                    disabled: true
                })
                form.splice(5, 0, {
                    label: "联系人",
                    error: false,
                    errMsg: "",
                    type: "textarea",
                    value: contactsinfo.name || '',
                    placeholder: "联系人名称",
                    valueName: "name",
                    checking: "base",
                    slot: "TXL",
                    required: false,
                    disabled: true
                })
            } catch (error) {

            }
            this.setData({
                disabled: false,
                content: {
                    sa_customersid: data.sa_customersid,
                    parentid: data.parentid,
                    sys_enterpriseid: data.sys_enterpriseid,
                    sa_customerpoolid: data.sa_customerpoolid,
                    source: data.source,
                },
                form
            })
        } else {
            this.data.form.splice(5, 0, {
                label: "手机号",
                error: false,
                errMsg: "",
                type: "number",
                value: "",
                placeholder: "联系人手机号码",
                valueName: "phonenumber",
                required: true,
                checking: "phone"
            })
            this.data.form.splice(5, 0, {
                label: "联系方式",
                error: false,
                errMsg: "",
                hint: "",
                type: "radio",
                value: "0",
                radioList: [{
                    id: '0',
                    name: '手机号'
                }, {
                    id: '1',
                    name: '座机电话'
                }],
                valueName: "isTelephone", //绑定的字段名称
                required: true, //必填
                interrupt: true,
                checking: `true`,
                phonenumber: "",
                telephone: ["", ""]
            })
            this.data.form.splice(5, 0, {
                label: "联系人",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "联系人名称",
                valueName: "name",
                checking: "base",
                slot: "TXL",
                required: true
            })
            this.setData({
                form: this.data.form
            })
        }
        /* 获取来源 */
        _Http.basic({
            "classname": "sysmanage.develop.optiontype.optiontype",
            "method": "optiontypeselect",
            "content": {
                "typename": "cluesource",
                pageSize: 9999
            }
        }).then(res => {
            console.log("获取线索来源", res)
            if (res.code == '1') {
                let form = this.data.form;
                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
                })
            }
        })
        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
                })
            })
        }
    },
    /* 工商查询 */
    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, //地区
            telephone: item.phone,
        }
        this.setData({
            form: this.data.form.map(v => {
                if (data[v.valueName]) v.value = data[v.valueName];
                return v
            }),

        })
    },
    /* 工商查询 */
    queryClient() {
        let data = this.selectComponent("#Form").query();
        if (data.enterprisename == '') {
            getApp().globalData.Language.showToast('您还未填写企业名称')
        } else {
            this.setData({
                form: this.selectComponent("#Form").data.form,
            })
            this.selectComponent("#Info").queryClient(data.enterprisename)
        }
    },
    repClose() {
        /* if (this.data.isSubmit) {
            let that = this;
            wx.showModal({
                title: getApp().globalData.Language.getMapText('提示'),
                content: `是否继续${this.data.content.sys_enterpriseid==0?'创建':'编辑'}客户`,
                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,
            ...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.showToast('未查询到疑似重复的客户信息')
        } else {
            getApp().globalData.Language.modeBoxPrompts([{
                t: 1,
                v: '查询到',
                r: " "
            }, {
                v: query.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,
            ...data
        });
        if (query.total != 0) {
            getApp().globalData.Language.modeBoxPrompts([{
                t: 1,
                v: '查询到',
                r: " "
            }, {
                v: query.total,
                r: " "
            }, {
                t: 1,
                v: '条疑似重复客户信息,不允许保存',
            }])
            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) {
        this.setData({
            loading: true
        })
        let data = this.selectComponent("#Form").submit();
        data.province = data.region[0] || "";
        data.city = data.region[1] || "";
        data.county = data.region[2] || "";
        data.sa_customerpoolid = data.sa_customerpoolid[0] ? data.sa_customerpoolid[1][0] : 0;
        data.parentid = data.parentid[0] ? data.parentid[1][0] : 0;
        data.ispublic = 1; //是否为公海客户
        delete(data.region);
        try {
            data.contactsinfo = {
                "name": data.name,
                "telephone": "",
                "phonenumber": data.isTelephone == 0 ? data.phonenumber || '' : data.telephone1.join("-") || '',
                sys_phonebookid: this.data.sys_phonebookid || 0,
                oldcontactsid: this.data.oldcontactsid
            }
        } catch (error) {

        }
        _Http.basic({
            "id": 20221010164302,
            "content": {
                ...this.data.content,
                ...data,
            }
        }).then(res => {
            this.setData({
                loading: false
            })
            console.log("新建医院", res)
            if (res.code != '1') return wx.showToast({
                title: res.msg,
                icon: "none"
            })
            getApp().globalData.Language.showToast('保存成功')
            //绑定疑似重复标签
            if (tag) _Http.basic({
                "id": 20220929090901,
                "content": {
                    "ownertable": "sa_customers",
                    "ownerid": res.data.sa_customersid,
                    "datatag": ["疑似重复"]
                }
            })
            setTimeout(() => {
                getCurrentPages().forEach(v => {
                    switch (v.__route__) {
                        case 'packageA/publicCustomer/index':
                            v.getList(true);
                            break;
                        case 'packageA/publicCustomer/detail':
                            wx.navigateBack()
                            v.getDetail();
                            v.selectComponent("#Contacts").getList(this.data.content.sa_customersid, true)
                            break;
                    }
                })
                let pages = getCurrentPages();
                if (pages[pages.length - 2].__route__ == 'packageA/publicCustomer/index') wx.redirectTo({
                    url: '/packageA/publicCustomer/detail?id=' + res.data.sa_customersid,
                })
            }, tag ? 500 : 300);

        })
    },
})