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

Page({
    data: {
        showAll: false,
        form: [{
                label: "项目名称",
                error: false,
                errMsg: "",
                type: "textarea",
                value: "",
                placeholder: "项目名称",
                valueName: "projectname",
                checking: "base",
                required: true,
                interrupt: true,
                permit: true, //无视errMsg 运行提交
            }, {
                label: "项目类型",
                error: false,
                errMsg: "",
                type: "option",
                optionNmae: "projecttype",
                optionType: "radio", //复选   radio 单选
                value: "",
                placeholder: "选择类型",
                valueName: "projecttype",
                checking: "base",
                required: true
            }, {
                label: "项目方阶段",
                error: false,
                errMsg: "",
                type: "option",
                optionNmae: "squarestage",
                optionType: "radio", //复选   radio 单选
                value: "",
                placeholder: "选择项目方阶段",
                valueName: "squarestage",
                checking: "base",
                required: false
            }, {
                label: "项目等级",
                error: false,
                errMsg: "",
                type: "option",
                optionNmae: "projectgrade",
                optionType: "radio", //复选   radio 单选
                value: "",
                placeholder: "选择项目等级",
                valueName: "grade",
                checking: "base",
                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: "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: "budgetary",
                checking: "base",
                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: "date",
                fields: "month",
                value: "",
                placeholder: "预计签约时间",
                valueName: "signdate_due",
                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/brand/select",
                params: {
                    "id": 20220924163702,
                    "content": {
                        nochace: true,
                    }
                },
                query: "&radio=true",
                value: "",
                placeholder: "选择品牌",
                valueName: "sa_brandid",
                checking: "base",
                required: false
            }, {
                label: "品牌是否由提报方植入",
                error: false,
                errMsg: "",
                hint: "",
                type: "radio",
                value: "",
                radioList: [{
                    id: '1',
                    name: '是'
                }, {
                    id: '0',
                    name: '否'
                }],
                valueName: "isfillbrangd", //绑定的字段名称
                required: false, //必填
            }
        ],
        "content": {
            "sat_orderclueid": ""
        },
        disabled: true
    },
    onLoad(options) {
        getApp().globalData.Language.getLanguagePackage(this, '转化项目');
        if (wx.getStorageSync('userMsg').siteid == 'HY') this.setHY();
        let data = JSON.parse(options.rowData);
        data.sa_brandid = ""
        this.setData({
            form: this.data.form.map(v => {
                if (v.valueName != 'region') {
                    if (v.valueName == 'campaign_name') {
                        v.value = [data[v.valueName],
                            [data.sat_campaignid]
                        ]
                    } else {
                        v.value = data[v.valueName];
                    }
                } else {
                    v.value = data.province ? [data.province, data.city, data.county] : []
                }
                return v
            }),
            'content.sat_orderclueid': data.sat_orderclueid,
            'content.sat_campaignid': data.sat_campaignid
        });
        /* 获取领域 */
        _Http.basic({
            "id": 20221223141802,
            "content": {
                "pageNumber": 1,
                "pageSize": 99999,
                "where": {
                    "condition": ""
                }
            }
        }).then(res => {
            console.log("获取领域", res)
            let item = this.data.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: this.data.form
            })
        })
    },
    async interrupt(e) {
        let {
            data,
            form,
            temporary
        } = e.detail;
        if (data.label == "项目名称") {
            if (data.value) {
                const result = await this.selectComponent("#projectname").queryList(data.value);
                if (typeof result == 'string') {
                    data.errMsg = result;
                    form[0] = data;
                    this.setData({
                        form
                    })
                } else {
                    if (result) {
                        data.errMsg = '疑似重复';
                        form[0] = data;
                        this.setData({
                            form
                        })
                    } else {
                        if (data.errMsg) {
                            data.errMsg = '';
                            form[0] = data;
                            this.setData({
                                form
                            })
                        }
                    }
                }
            } else {
                if (data.errMsg) {
                    data.errMsg = '';
                    form[0] = data;
                    this.setData({
                        form
                    })
                }
            }
        }
    },
    setHY() {
        let required = ["预计签约时间", "项目等级", "详细地址", "项目规模"],
            remove = ["项目预算(万元)", "总投资额(万元)", "造价(万元)"];
        this.setData({
            form: this.data.form.filter(v => !remove.includes(v.label)).map(v => {
                if (required.includes(v.label)) v.required = true;
                // if (v.valueName == 'projectname') v.interrupt = false;
                return v
            }),
            siteid: wx.getStorageSync('userMsg').siteid,
        })
    },

    /* 查询是否重复 */
    async queryRepetition(e) {
        let data = this.selectComponent("#Form").query();
        /* if (data.projectname == '') 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_projectid: this.data.sa_projectid,
            ...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('未查询到疑似重复的项目信息')
            this.data.repetitionShow = false;
        } 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
                    }), {});
                    v.projectname = v.projectname.split('').map(text => {
                        let projectname = v.chars.projectname.join("") || ''
                        return projectname.includes(text) ? {
                            text,
                            color: "red"
                        } : {
                            text,
                            color: "#666666"
                        }
                    })
                    return v
                }),
            })
        }
    },
    repClose() {
        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
        })
    },
    /* 处理查重 */
    handleQueryRepetition(content) {
        return _Http.basic({
            "id": 20221208184202,
            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_projectid: this.data.sa_projectid,
            ...data
        });
        if (query.code == 0) return wx.showModal({
            content: query.msg,
            confirmText: getApp().globalData.Language.getMapText('关闭'),
            showCancel: false
        })
        if (query.total != 0) {
            if (this.data.siteid == 'HY') {
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('查询到') + query.total + getApp().globalData.Language.getMapText('条疑似重复项目信息，是否确定继续创建项目'),
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: getApp().globalData.Language.getMapText('创建'),
                    complete: (res) => {
                        if (res.confirm) that.handleSubmit(true);
                    }
                })
            } else {
                wx.showToast({
                    title: getApp().globalData.Language.getMapText('查询到') + query.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
                        }), {});
                        v.projectname = v.projectname.split('').map(text => {
                            let projectname = v.chars.projectname.join("") || ''
                            return projectname.includes(text) ? {
                                text,
                                color: "red"
                            } : {
                                text,
                                color: "#666666"
                            }
                        })
                        return v
                    }),
                    isSubmit: true
                })
            }
        } else {
            this.handleSubmit();
        }
    },
    handleSubmit(tag = false) {
        this.setData({
            loading: true
        })
        let data = {
            ...this.data.content,
            ...this.selectComponent("#Form").submit()
        };
        data.province = data.region[0] || "";
        data.city = data.region[1] || "";
        data.county = data.region[2] || "";
        data.tradefields = [data.tradefields];
        data.sa_brandid = data.sa_brandid ? data.sa_brandid[1][0] : 0;

        if (data.scale.length != 0 && data.scale == 0) {
            this.setData({
                loading: false
            })
            getApp().globalData.Language.showToast('项目规模不可为0')
            return;
        }

        if (data.unitname == "") {
            this.setData({
                loading: false
            })
            getApp().globalData.Language.showToast('还未选择项目规模单位')
            return;
        }

        delete(data.region);
        _Http.basic({
            "id": 20221124154902,
            content: data
        }).then(res => {
            this.setData({
                loading: false
            })
            console.log("转化", res)
            wx.showToast({
                title: res.code != '1' ? res.msg : getApp().globalData.Language.getMapText(wx.getStorageSync('userMsg').siteid != 'HY' ? '提交成功' : '转化成功'),
                icon: "none"
            })
            if (res.code != '1') return;
            //绑定疑似重复标签
            if (tag) _Http.basic({
                "id": 20220929090901,
                "content": {
                    "ownertable": "sa_project",
                    "ownerid": res.data.sa_projectid,
                    "datatag": ["疑似重复"]
                }
            })
            setTimeout(() => {
                getCurrentPages().forEach(v => {
                    if (v.__route__ == 'packageA/saleClue/detail') v.getDetail()
                })
                wx.navigateBack()
                if (wx.getStorageSync('userMsg').siteid != 'HY') {
                    wx.navigateTo({
                        url: `/packageA/project/detail?id=${res.data.sa_projectid}`,
                    })
                }
            }, 300)
        })
    },
    // 是否显示全部
    onChange({
        detail
    }) {
        this.setData({
            showAll: detail
        })
    },
    /* 表单必填项是否完成 */
    onConfirm({
        detail
    }) {
        this.setData({
            disabled: detail
        })
    }
})