let _Http = getApp().globalData.http,
    sat_orderclueid = 0;
Page({
    data: {
        isuppictured: null,
        loading: false,
        showAll: false,
        content: {},
        disabled: true
    },
    clearProject() {
        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.setData({
                    "form[19].value": ""
                })
            }
        })
    },
    onLoad(options) {
        const isHy = ['HY', "YOSTEST1"].includes(wx.getStorageSync('userMsg').siteid)
        if (options.sat_orderclueid) sat_orderclueid = this.data.content.sat_orderclueid;
        let form = [{
                label: "是否上图",
                error: false,
                errMsg: "",
                hint: "",
                type: "radio",
                value: "0",
                radioList: [{
                    id: '1',
                    name: '是'
                }, {
                    id: '0',
                    name: '否'
                }],
                valueName: "isuppictured", //绑定的字段名称
                required: false, //必填
                direction: "horizontal",
                interrupt: true
            }, {
                label: "项目名称",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "项目名称",
                valueName: "projectname",
                checking: "base",
                required: false
            }, {
                label: "医院名称",
                error: false,
                errMsg: "",
                type: "text",
                value: "",
                placeholder: "医院名称",
                valueName: "enterprisename",
                checking: "base",
                slot: "info",
                required: false
            }, {
                label: "联系人",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "联系人名称",
                valueName: "name",
                checking: "base",
                slot: "TXL",
                required: true
            }, {
                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: ["", ""]
            }, {
                label: "手机号",
                error: false,
                errMsg: "",
                type: "number",
                value: "",
                placeholder: "联系人手机号码",
                valueName: "phonenumber",
                required: true,
                checking: "phone"
            }, {
                label: "联系人角色",
                error: false,
                errMsg: "",
                type: "text",
                value: "",
                placeholder: "联系人角色",
                valueName: "contactsrole",
                checking: "base",
                required: false
            }, {
                label: "微信",
                error: false,
                errMsg: "",
                type: "text",
                value: "",
                placeholder: "微信号",
                valueName: "wechatnum",
                checking: "base",
                required: false
            }, {
                label: isHy ? "项目地址" : "省市县",
                error: false,
                errMsg: "",
                type: "region",
                value: "",
                placeholder: "省市县",
                valueName: "region",
                checking: "base",
                required: false
            }, {
                label: isHy ? " " : '详细地址',
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "详细地址",
                valueName: "address",
                checking: "base",
                required: false
            }, {
                label: "项目规模",
                error: false,
                errMsg: "",
                type: "digit",
                value: "",
                placeholder: "请填写数值",
                valueName: "scale",
                checking: "base",
                required: false
            }, {
                label: "项目规模单位",
                error: false,
                errMsg: "",
                type: "option",
                optionNmae: "scaleunitname",
                optionType: "radio", //复选   radio 单选
                value: "",
                placeholder: "选择单位",
                valueName: "unitname",
                required: false
            }, {
                label: "总投资额(万元)",
                error: false,
                errMsg: "",
                type: "digit",
                value: "",
                placeholder: "请填写金额",
                valueName: "totalinvestment",
                checking: "base",
                required: false
            }, {
                label: "造价(万元)",
                error: false,
                errMsg: "",
                type: "digit",
                value: "",
                placeholder: "请填写金额",
                valueName: "costofconstruction",
                checking: "base",
                required: false
            }, {
                label: "预计开工时间",
                error: false,
                errMsg: "",
                type: "date",
                fields: "month",
                value: "",
                placeholder: "预计开工时间",
                valueName: "begdate_due",
                checking: "base",
                required: false
            }, {
                label: "预计完工时间",
                error: false,
                errMsg: "",
                type: "date",
                fields: "month",
                value: "",
                placeholder: "预计完工时间",
                valueName: "enddate_due",
                checking: "base",
                required: false
            },
            {
                label: "市场活动",
                error: false,
                errMsg: "",
                type: "route",
                url: "/packageA/select/selectActivity/index",
                value: "",
                params: {
                    "id": 20221101095102,
                    "content": {
                        nocache: true,
                        isAll: 0,
                        "where": {
                            'condition': '',
                            "unend": 1
                        }
                    }
                },
                query: "&radio=true",
                placeholder: "选择市场活动",
                valueName: "campaign_name",
                checking: "base",
                required: false
            }, {
                label: "领域",
                error: false,
                errMsg: "",
                type: "selector",
                range: [],
                rangeKey: "name",
                selectKey: "tradefield",
                rangeIndex: "",
                value: "",
                placeholder: "领域",
                valueName: "tradefield",
                required: true, //必填
            }, {
                label: "设计院",
                error: false,
                errMsg: "",
                type: "route",
                url: "/packageA/select/setclient/select",
                value: "",
                params: {
                    "id": 20230809094104,
                    "content": {
                        "pageNumber": 1,
                        "pageSize": 20,
                        "where": {
                            "condition": ""
                        }
                    }
                },
                query: "&radio=true&idname=sys_enterpriseid",
                placeholder: "选择设计院",
                valueName: "sys_enterpriseid",
                checking: "base",
                required: false,
                interrupt: true
            }, {
                label: "设计师",
                error: false,
                errMsg: "",
                type: "route",
                url: "/packageA/select/contacts/select",
                value: "",
                params: {
                    "id": 20240531165504,
                    "content": {
                        "pageNumber": 1,
                        "pageSize": 20,
                        "sys_enterpriseid": 0,
                        "where": {
                            "condition": "",
                            "workaddress": 0
                        }
                    }
                },
                query: "&radio=true",
                placeholder: "选择设计师",
                disabled: true,
                valueName: "contactsid",
                checking: "base",
                required: false
            }, {
                label: "关联项目",
                error: false,
                errMsg: "",
                type: "route",
                url: "/packageA/select/project/select",
                value: "",
                params: {
                    "id": 20230809085404,
                    "content": {
                        nocache: true,
                        sat_orderclueid,
                        "where": {
                            'condition': '',
                        }
                    }
                },
                query: "&radio=true",
                placeholder: "选择关联项目",
                valueName: "sa_projectid",
                checking: "base",
                required: false,
                interrupt: true,
                slot: "empty",
            }, {
                label: "来源",
                error: false,
                errMsg: "",
                type: "selector",
                range: [],
                rangeKey: "name",
                selectKey: "value",
                rangeIndex: "",
                value: "",
                placeholder: "来源",
                valueName: "cluesource",
                checking: "base",
                required: true
            }, {
                label: "线索概括",
                error: false,
                errMsg: "",
                type: "text",
                value: "",
                placeholder: "线索概括",
                valueName: "notes",
                checking: "base",
                required: false
            }
        ];
        if (wx.getStorageSync('userMsg').siteid == 'HY') form = form.filter(v => !["项目预算(万元)", "总投资额(万元)", "造价(万元)"].includes(v.label))
        getApp().globalData.Language.getLanguagePackage(this, options.rowData ? '编辑线索' : '添加线索');

        if (options.rowData) {
            let data = JSON.parse(options.rowData);
            let sys_enterpriseid = data.sys_enterpriseid;

            data.campaign_name = data.sat_campaignid ? [data.campaign_name, [data.sat_campaignid]] : "";
            data.contactsid = data.contactsid ? [data.designer, [data.contactsid]] : "";
            data.sa_projectid = data.sa_projectid ? [data.projectname1, [data.sa_projectid]] : "";
            data.sys_enterpriseid = data.sys_enterpriseid ? [data.institute, [data.sys_enterpriseid]] : "";

            if (data.phonenumber.includes("-")) {
                let index = form.findIndex(v => v.label == '手机号');
                data.telephone1 = data.phonenumber.split("-");
                form[index] = {
                    label: "座机电话",
                    error: false,
                    errMsg: "",
                    type: "telephone",
                    value: ["", ""],
                    valueName: "telephone1",
                    required: true,
                    checking: "telephone"
                }
            }

            form = form.map(v => {
                if (v.valueName == 'region') {
                    v.value = data.province ? [data.province, data.city, data.county] : []
                } else if (v.valueName == 'isTelephone') {
                    if (data.phonenumber.includes("-")) {
                        v.value = '1'
                        v.telephone = data.telephone1;
                    } else {
                        v.phonenumber = data.phonenumber
                    }
                } else if (v.valueName == 'campaign_name') {
                    v.value = data[v.valueName] ? [data[v.valueName],
                        [data.sat_campaignid]
                    ] : ""
                } else {
                    v.value = data[v.valueName];
                }
                return v
            });

            if (data.isuppictured == 1) {
                let valueNameList = ["enterprisename", "name", "projectname", "scale", "sys_enterpriseid", "contactsid", "uppictured"];
                form.forEach((v, i) => {
                    if (valueNameList.includes(v.valueName)) form[i].required = true;
                })
            }
            this.setData({
                form,
                'form[0].value': data.isuppictured + '',
                'form[2].value': data.enterprisename_customer || data.enterprisename || "",
                'form[18].disabled': sys_enterpriseid == 0,
                'form[18].params.content.sys_enterpriseid': sys_enterpriseid,
                'content.sa_customersid': data.sa_customersid || 0
            })

            if (data.sat_orderclueid) sat_orderclueid = data.sat_orderclueid;
            setTimeout(() => {
                this.selectComponent("#Form").confirm();
            }, 100)
        } else {
            _Http.basic({
                "classname": "sysmanage.develop.optiontype.optiontype",
                "method": "optiontypeselect",
                "content": {
                    pageNumber: 1,
                    "pageSize": 1,
                    "typename": "scaleunitname",
                    "parameter": {
                        "siteid": wx.getStorageSync('siteP').siteid
                    }
                }
            }).then(res => {
                console.log("项目规模", res)
                if (res.code == '1') {
                    let index = form.findIndex(v => v.label == '项目规模单位');
                    if (index != -1) form[index].value = res.data[0].value;
                    this.setData({
                        form
                    })
                }
            })
        }
        /* 获取领域 */
        _Http.basic({
            "id": 20221223141802,
            "content": {
                "pageNumber": 1,
                "pageSize": 99999,
                "where": {
                    "condition": ""
                }
            }
        }).then(res => {
            console.log("获取领域", res)
            let item = form.find(v => v.label == '领域');
            item.range = res.code == '1' ? res.data.map(v => {
                v.name = getApp().globalData.Language.getMapText(v.tradefield)
                return v
            }) : [];
            this.setData({
                form
            })
        })
        /* 查询是否为上图员 */
        _Http.basic({
            "classname": "webmanage.hr.hr",
            "method": "query_hrMain",
            "content": {
                "hrid": wx.getStorageSync('userMsg').hrid
            },
        }).then(res => {
            if (res.code != '1') return wx.showToast({
                title: res.msg,
                icon: "none"
            })
            this.data.isuppictured = res.data.isuppictured == 1 ? res.data.name : null;
            if (res.data.isuppictured == 0) {
                form[0].disabled = true;
                this.setData({
                    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 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({
            form
        })
    },
    /* 打开通讯录 */
    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;
                        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()
                    }
                }
            })
        };
    },
    async interrupt(e) {
        let {
            data,
            form,
            temporary
        } = e.detail;
        let that = this;
        switch (temporary.item.label) {
            case "关联项目":
                function setProject() {
                    form[temporary.index].value = data.value;
                    form.find(v => v.label == '项目名称').value = data.value[0];
                    that.setData({
                        form
                    })
                    wx.navigateBack()
                }
                _Http.basic({
                    "id": 20230812100204,
                    "content": {
                        sat_orderclueid,
                        "sa_projectid": data.item.sa_projectid
                    }
                }).then(res => {
                    console.log("查询项目有无绑定线索", res)
                    if (res.code != '1') return wx.showToast({
                        title: res.msg,
                        icon: "none"
                    })
                    if (res.data == 1) {
                        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) setProject();
                            }
                        })
                    } else {
                        setProject();
                    }
                })
                break;
            case "是否上图":
                let valueNameList = ["enterprisename", "name", "projectname", "scale", "sys_enterpriseid", "contactsid", "uppictured"];
                form.forEach((v, i) => {
                    if (valueNameList.includes(v.valueName)) form[i].required = data.value == 1;
                })
                if (form[temporary.index].value == 1) {
                    form.push({
                        label: "上图员",
                        error: false,
                        errMsg: "",
                        type: "text",
                        value: this.data.isuppictured || '',
                        placeholder: "暂无",
                        valueName: "sty",
                        checking: "base",
                        required: false,
                        disabled: true
                    })
                    console.log(form[form.length - 1])
                } else {
                    form = form.filter(v => v.label != '上图员')
                }
                break;
            case "设计院":
                temporary.item.value = data.value;
                form[temporary.index] = temporary.item;
                let index = form.findIndex(v => v.valueName == 'contactsid');
                if (index != -1) form[index] = {
                    label: "设计师",
                    error: false,
                    errMsg: "",
                    type: "route",
                    url: "/packageA/select/contacts/select",
                    value: "",
                    params: {
                        "id": 20240531165504,
                        "content": {
                            "pageNumber": 1,
                            "pageSize": 20,
                            "sys_enterpriseid": data.value[1][0],
                            "where": {
                                "condition": "",
                                "workaddress": 0
                            }
                        },
                    },
                    query: "&radio=true",
                    placeholder: "选择设计师",
                    valueName: "contactsid",
                    checking: "base",
                    required: form[0].value == 1
                }
                wx.navigateBack()
                break;
            case "联系方式":
                let i = temporary.index + 1
                if (data.value == 0) {
                    data.telephone = form[i].value;
                    if (data.telephone.join() == ',') data.telephone = "";
                    form[i] = {
                        label: "手机号",
                        error: false,
                        errMsg: "",
                        type: "number",
                        value: data.phonenumber,
                        placeholder: "联系人手机号码",
                        valueName: "phonenumber",
                        required: true,
                        checking: "phone"
                    }
                } else {
                    if (typeof (form[i].value) == 'object') form[i].value = "";
                    data.phonenumber = form[i].value;
                    form[i] = {
                        label: "座机电话",
                        error: false,
                        errMsg: "",
                        type: "telephone",
                        value: data.telephone || ["", ""],
                        valueName: "telephone1",
                        required: true,
                        checking: "telephone"
                    }
                };
                break;
        }
        this.setData({
            form
        })
        setTimeout(() => {
            this.selectComponent("#Form").confirm();
        }, 100)
    },
    introduce({
        detail
    }) {
        let item = detail;
        this.setData({
            [`form[0].value`]: item.companyName,
            [`form[7].value`]: [item.regProvince ? item.regProvince : item.regCity, item.regCity, item.regArea],
            [`form[8].value`]: item.address,
        })
    },
    queryClient() {
        let data = this.selectComponent("#Form").query();
        if (data.enterprisename == '') {
            wx.showToast({
                title: getApp().globalData.Language.getMapText('您还未填写企业名称'),
                icon: "none"
            });
        } else {
            this.setData({
                form: this.selectComponent("#Form").data.form,
            })
            this.selectComponent("#Info").queryClient(data.enterprisename)
        }
    },
    submit() {
        let content = this.selectComponent("#Form").submit();
        content.sat_orderclueid = sat_orderclueid;
        content.isprivate = 0; //0表示公海，1表示私域
        content.sat_campaignid = content.campaign_name ? content.campaign_name[1][0] : 0;
        content.contactsid = content.contactsid ? content.contactsid[1][0] : 0;
        content.sa_projectid = content.sa_projectid ? content.sa_projectid[1][0] : 0;
        content.sys_enterpriseid = content.sys_enterpriseid ? content.sys_enterpriseid[1][0] : 0;
        content.city = content.region[1] || "";
        content.county = content.region[2] || "";
        content.province = content.region[0] || "";
        delete(content.region)
        delete(content.campaign_name)
        if (content.enterprisename == "" && content.projectname == "") return getApp().globalData.Language.showToast('客户名称或项目名称为空，请完善信息')
        if (content.scale.length != 0 && content.scale == 0) return getApp().globalData.Language.showToast('项目规模不可为0')
        content.phonenumber = content.isTelephone == 0 ? content.phonenumber || '' : content.telephone1.join("-") || '';
        this.setData({
            loading: true
        })
        delete content.telephone1;
        delete content.isTelephone;
        _Http.basic({
            "id": "20221205162402",
            content
        }).then(res => {
            console.log("添加线索", res)
            this.setData({
                loading: false
            })
            wx.showToast({
                title: res.code != '1' ? res.msg : getApp().globalData.Language.getMapText('保存成功'),
                icon: "none"
            })
            if (res.code != '1') return;
            setTimeout(() => {
                wx.navigateBack();
                getCurrentPages().forEach(v => {
                    if (v.__route__ == 'packageA/saleAdmin/detail') {
                        v.getDetail();
                    } else if (v.__route__ == 'packageA/saleAdmin/index') {
                        v.getList(true);
                    } else if (['packageA/setclient/detail', 'packageA/publicCustomer/detail'].includes(v.__route__)) {
                        v.selectComponent("#Clue").getList(this.data.content.sa_customersid, true)
                    }
                })
            }, 300)
        })
    },
    // 是否显示全部
    onChange({
        detail
    }) {
        this.setData({
            showAll: detail
        })
    },
    /* 表单必填项是否完成 */
    onConfirm({
        detail
    }) {
        this.setData({
            disabled: detail
        })
    }
})