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

Page({
    data: {
        loading: false,
        showAll: false,
        repetitionShow: false,
        repetitionList: [],
        isSubmit: false,
        oldcontactsid: 0,
        sys_phonebookid: 0,
        content: {
            "sa_customersid": 0, //新增是传0
            "sys_enterpriseid": 0, //合作企业档案ID，新增是传0，更新
            "sa_customerpoolid": 0, //客户池（公海池）ID,默认或没有的时候传0
            phonenumber: "",
            ispublic: 0, //是否为公海客户
        },
        disabled: true,
        countDown: "", //查重倒计时
    },
    onLoad(options) {
        let form = [{
            label: "医院名称",
            error: false,
            errMsg: "",
            type: "textarea",
            value: "",
            placeholder: "医院名称",
            valueName: "enterprisename",
            checking: "base",
            slot: "info",
            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: "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,
                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
        }]
        if (options.data) {
            let data = JSON.parse(options.data);
            form = 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
            })
            this.setData({
                disabled: false,
                content: {
                    sa_customersid: data.sa_customersid,
                    sys_enterpriseid: data.sys_enterpriseid,
                    sa_customerpoolid: data.sa_customerpoolid,
                },
                form
            })
        }
        this.setData({
            form
        })
        getApp().globalData.Language.getLanguagePackage(this, options.data ? '编辑医院' : '新建医院');

    },
    /* 表单必填项是否完成 */
    onConfirm({
        detail
    }) {
        this.setData({
            disabled: detail
        })
    },
    // 是否显示全部
    onChange({
        detail
    }) {
        this.setData({
            showAll: detail
        })
    },
    /* 查询是否重复 */
    async queryRepetition(e) {
        let data = this.selectComponent("#Form").query();
        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 {
            wx.showToast({
                title: getApp().globalData.Language.getMapText('查询到') + res.total + getApp().globalData.Language.getMapText('条疑似重复客户信息'),
                icon: "none"
            })
            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(),
            that = this;
        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) {
            wx.showModal({
                content: getApp().globalData.Language.joint([{
                    t: 1,
                    v: '查询到',
                }, {
                    v: query.total,
                    f: "“",
                    r: "”"
                }, {
                    t: 1,
                    v: '条疑似重复客户信息,不可',
                    r: " "
                }, {
                    t: 1,
                    v: this.data.content.sa_customersid == 0 ? '创建' : '编辑',
                    r: " "
                }, {
                    t: 1,
                    v: '客户',
                }]),
                confirmText: that.data.language['确定'] || '我知道了',
                showCancel: false
            })
            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.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);
        try {
            data.contactsinfo = {
                "name": data.name,
                "telephone": "",
                "phonenumber": data.isTelephone == 0 ? data.phonenumber || '' : data.telephone1.join("-") || '',
                oldcontactsid: this.data.oldcontactsid,
                sys_phonebookid: this.data.sys_phonebookid || 0,
            }
        } catch (error) {

        }
        _Http.basic({
            "id": 20221012163902,
            "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/setclient/index':
                            v.getList(true);
                            break;
                        case 'packageA/setclient/detail':
                            v.getDetail();
                            v.selectComponent("#Contacts").getList(this.data.content.sa_customersid, true)
                            wx.navigateBack()
                            break;
                    }
                })
                let pages = getCurrentPages();
                if (pages[pages.length - 2].__route__ == 'packageA/setclient/index') wx.redirectTo({
                    url: '/packageA/setclient/detail?id=' + res.data.sa_customersid,
                })
            }, tag ? 500 : 300)
        })
    },
})