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

Page({
    data: {
        loading: false,
        showAll: false,
        repetitionShow: false,
        repetitionList: [],
        content: {
            sa_customersid: 0,
            province: '',
            city: '',
            county: ''
        },
        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: "hospitalgrade",
                optionType: "radio", //复选   radio 单选
                value: "",
                placeholder: "医院等级",
                valueName: "grade",
                checking: "base",
                required: true
            }, {
                label: "医院类型",
                error: false,
                errMsg: "",
                type: "option",
                optionNmae: "hospitaltype",
                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: "/prsx/select/saler/index",
                value: "",
                placeholder: "负责人",
                valueName: "saler_userid",
                checking: "base",
                required: true,
                params: {},
                query: "&radio=true",
                required: true,
                interrupt: true
            }, {
                label: "营销区域",
                error: false,
                errMsg: "",
                type: "selector",
                range: [],
                rangeKey: "areaname",
                selectKey: "areaname",
                rangeIndex: "",
                value: "",
                placeholder: "营销区域",
                valueName: "sa_saleareaid",
                required: true, //必填
                disabled: true
            }, {
                label: "医院规模",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "医院规模",
                valueName: "scale",
                checking: "base",
                required: false
            }, {
                label: "医院床位",
                error: false,
                errMsg: "",
                type: "number",
                value: "",
                placeholder: "医院床位",
                valueName: "bed",
                checking: "base",
                required: false
            }, {
                label: "手术间",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "手术间",
                valueName: "room",
                checking: "base",
                required: false
            }, {
                label: "主机数量",
                error: false,
                errMsg: "",
                type: "number",
                value: "",
                placeholder: "主机数量",
                valueName: "host",
                checking: "base",
                required: false
            }],
            hrid = '';
        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 == 'saler_userid') {
                        let leader = data.leader[0];
                        v.value = [leader.name, [leader.userid]]
                    }
                    if (v.valueName == 'sa_saleareaid') v.value = data.areaname;
                } else {
                    v.value = data.province ? [data.province, data.city, data.county] : []
                };
                if (['省市县', '详细地址'].includes(v.label)) v.disabled = true;
                return v
            })
            hrid = data.leader[0].hr.hrid;
            this.setData({
                disabled: false,
                content: {
                    sa_customersid: data.sa_customersid
                },
                form
            })
        } else {
            // 业务员
            if (![0, 21].includes(wx.getStorageSync('userMsg').usertype)) {
                let item = form.find(v => v.label == '负责人');
                if (item) item.disabled = true;
                hrid = wx.getStorageSync('userMsg').hrid;
                item.value = [wx.getStorageSync('userMsg').name, [wx.getStorageSync('userMsg').userid]]
            }
        }

        if (hrid) {
            _Http.basic({
                "method": "query_hrMain",
                "classname": "webmanage.hr.hr",
                "content": {
                    hrid
                },
            }).then(res => {
                if (res.code != 1) return;
                let obj = form.find(v => v.label == '营销区域')
                obj.range = res.data.salearea;
                if (obj.range.length == 1) obj.value = obj.range[0].areaname;
                obj.disabled = false;
                this.setData({
                    form
                })
            })
        }
        this.setData({
            form
        })
        getApp().globalData.Language.getLanguagePackage(this, options.data ? '编辑医院' : '新建医院');

    },
    /* 表单必填项是否完成 */
    onConfirm({
        detail
    }) {
        this.setData({
            disabled: detail
        })
    },
    // 是否显示全部
    onChange({
        detail
    }) {
        this.setData({
            showAll: detail
        })
    },
    interrupt(e) {
        const {
            data,
            form,
            temporary
        } = e.detail;
        console.log(data, form, temporary)
        if (temporary.item.label == '负责人') {
            form.find(v => v.label == '负责人').value = data.value;
            let obj = form.find(v => v.label == '营销区域')
            obj.range = data.item.sa_saleareas;
            obj.value = obj.range[0].areaname;
            obj.disabled = false;
            wx.navigateBack()
        }
        this.selectComponent("#Form").confirm();
        this.setData({
            form
        })
    },
    async submit() {
        this.setData({
            loading: true
        })
        let data = this.selectComponent("#Form").submit();
        data.saler_userid = data.saler_userid[1][0];
        data.sa_saleareaid = this.data.form.find(v => v.label == '营销区域').range.find(v => v.areaname == data.sa_saleareaid).sa_saleareaid;
        if (data.region.length) {
            data.province = data.region[0];
            data.city = data.region[1];
            data.county = data.region[2];
        }
        delete data.region
        let query = await this.handleQueryRepetition({
            sa_customersid: this.data.content.sa_customersid,
            ...data
        });
        if (query.total != 0) {
            wx.showModal({
                content: `查询到“${query.total}”条疑似重复医院信息,不可重复创建`,
                confirmText: '我知道了',
                showCancel: false
            })
            this.setData({
                loading: false,
                repetitionShow: true,
                repetitionList: query.data.map(v => {
                    v.chars = v.chars.reduce((acc, item) => ({
                        ...acc,
                        ...item
                    }), {});
                    return v
                }),
                isSubmit: true
            })
        } else {
            this.handleSubmit(data);
        }
    },
    handleSubmit(data) {
        _Http.basic({
            "id": 20221012163902,
            "content": {
                ...this.data.content,
                ...data,
            }
        }).then(res => {
            this.setData({
                loading: false
            })
            wx.showToast({
                title: res.code != '1' ? res.msg : '保存成功',
                icon: "none",
                mask: res.code == '1'
            })
            if (res.code != '1') return;
            getCurrentPages().forEach(v => {
                if (v.route == 'prsx/hospital/detail') v.getDetail()
            })
            setTimeout(() => {
                if (this.data.content.sa_customersid == 0) {
                    wx.redirectTo({
                        url: '/prsx/hospital/detail?id=' + res.data.sa_customersid,
                    })
                } else {
                    wx.navigateBack()
                }
            }, 300)
        })
    },
    repClose() {
        this.setData({
            repetitionShow: false,
            isSubmit: false
        })
    },
    /* 查询是否重复 */
    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
        })
    },
})