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

Page({
    data: {
        loading: false,
        repetitionShow: false,
        repetitionList: [],
        isSubmit: false,
        sa_projectid: 0,
        showAll: false,
        disabled: true,
        siteid: null,
        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: "option",
                optionNmae: "tradefield",
                optionType: "radio", //复选   radio 单选
                value: "",
                placeholder: "选择领域",
                valueName: "tradefield",
                checking: "base",
                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, //必填
                direction: "horizontal"
            }
        ],
        countDown: "", //查重倒计时
    },
    onLoad(options) {
        let siteid = wx.getStorageSync('userMsg').siteid,
            form = this.data.form;
        if (siteid == 'HY') this.setHY();
        if (['NB', 'TZ', 'YOSTEST1'].includes(siteid)) {
            form.splice(form.findIndex(v => v.optionNmae == 'scaleunitname') + 1, 0, {
                label: "预计签约金额(元)",
                error: false,
                errMsg: "",
                type: "digit",
                value: "",
                placeholder: "请填写金额",
                valueName: "signamount_due",
                checking: "base",
                required: false
            })
            this.setData({
                form
            })
        }

        if (options.data) {
            let data = JSON.parse(options.data);
            let disabled = options.disabled == "true";
            data.sa_brandid = [data.brandname, [data.sa_brandid]]
            this.setData({
                disabled: false,
                sa_projectid: data.sa_projectid,
                form: form.map(v => {
                    if (v.valueName != 'region') {
                        v.value = data[v.valueName];
                    } else {
                        v.value = data.province ? [data.province, data.city, data.county] : []
                    };
                    if (disabled) {
                        if (['projectname', 'region', 'address'].includes(v.valueName)) v.disabled = true
                    }
                    return v
                })
            });
        } else {
            //查询默认项目规模单位
            this.getUnitname();
        }
        getApp().globalData.Language.getLanguagePackage(this, options.data ? '编辑项目' : '新建项目');
    },
    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 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
                    })
                }
            }
        }
    },
    getUnitname() {
        _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 = this.data.form.findIndex(v => v.label == '项目规模单位');
                if (index != -1) this.setData({
                    [`form[${index}].value`]: res.data[0].value
                })
            }
        })
    },
    /* 表单必填项是否完成 */
    onConfirm({
        detail
    }) {
        this.setData({
            disabled: detail
        })
    },
    // 是否显示全部
    onChange({
        detail
    }) {
        this.setData({
            showAll: detail
        })
    },
    /* 查询是否重复 */
    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"
            })
            if (wx.getStorageSync('userMsg').siteid != 'HY') 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(this.data.sa_projectid ? '是否继续保存项目' : '是否继续创建项目'),
                cancelText: getApp().globalData.Language.getMapText('取消'),
                confirmText: getApp().globalData.Language.getMapText(this.data.sa_projectid ? '保存' : '创建'),
                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] || "";
        data.signamount_due = data.signamount_due || 0;
        let query = await this.handleQueryRepetition({
            sa_projectid: this.data.sa_projectid,
            ...data
        });
        if (query.total != 0) {
            if (this.data.siteid == 'HY') {
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.joint([{
                            v: '查询到',
                            t: 1
                        },
                        {
                            v: query.total,
                            r: '“',
                            f: "”"
                        }, {
                            v: '条疑似重复项目信息，是否确定继续' + this.data.sa_projectid ? '保存' : '创建' + '项目',
                            t: 1,
                        }
                    ]),
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: getApp().globalData.Language.getMapText(this.data.sa_projectid ? '保存' : '创建'),
                    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: query.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.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
            })
            wx.showToast({
                title: getApp().globalData.Language.getMapText('项目规模不可为0'),
                icon: "none"
            })
            return;
        }
        delete(data.region);
        _Http.basic({
            "id": 20221020144202,
            "content": {
                sa_projectid: this.data.sa_projectid,
                ...data
            }
        }).then(res => {
            this.setData({
                loading: false
            })
            console.log("新建项目", res)
            wx.showToast({
                title: res.code != '1' ? res.msg : getApp().globalData.Language.getMapText('保存成功'),
                icon: "none",
                mask: true
            })
            if (res.code != '1') return;
            //绑定疑似重复标签
            if (tag) _Http.basic({
                "id": 20220929090901,
                "content": {
                    "ownertable": "sa_project",
                    "ownerid": res.data.sa_projectid,
                    "datatag": ["疑似重复"]
                }
            })
            setTimeout(() => {
                let page = getCurrentPages()[getCurrentPages().length - 2];
                if (page.__route__ == 'packageA/project/index') {
                    wx.redirectTo({
                        url: '/packageA/project/detail?id=' + res.data.sa_projectid,
                    })
                } else if (page.__route__ == 'packageA/project/detail') {
                    wx.navigateBack()
                    page.getDetail();
                }
            }, 500)
        })
    }

})