import {
    ApiModel
} from "../../utils/api";
const _Http = new ApiModel();
import {
    TestVerify
} from "../../utils/verify"
const _Verify = new TestVerify();
const utilMd5 = require('../../utils/md5');
let countDownTime1 = null;
const QR = require('../../miniprogram_npm/qrcode-base64/index.js');
import {
    base64src
} from '../../components/My_TwoDimensionalCode/base64src';
Page({
    /**
     * 页面的初始数据
     */
    data: {
        pageType: 0, //0报名 1查看二维码 2
        rulesChecked: true, //同意用户隐私协议
        isNoToken: false, //是否存在登录
        countDownTime: 30, //倒计时
        tactivityid: 2, //展会id
        fname: "", //姓名
        fidcard: "", //身份证号
        fphonenumber: "", //手机号
        password: '', //验证码
        fcompname: "", //公司
        frole: "", //职位
        findustry: "", //行业
        faddress: "", //地址
        fchannel: "", //入会渠道
        errTips: {
            fname: false, //姓名
            fidcard: false, //身份证号
            fphonenumber: false, //手机号
            password: false, //验证码
            fcompname: false, //公司
            frole: false, //职位
            findustry: false, //行业
            faddress: false,
            fchannel: false,
        },
        throttle: false, //截流
        msg: null,
        myShowModel: false, //角色选择
        userIndex: null, //选择账号下标
        qrcodeURL: null,
        butText: '下一步',
        fquestionnaire: [],
        surveysList: [{
            title: '你所在的公司来自哪里（where does your compangy come from）？',
            arr: ['中国大陆公司（Mainland China company）', '海外公司中国大陆分支机构（Overseas company mailand China branch）', '海外公司（含港、澳、台地区）Overseas companies（including Hong Kong，Macao and Taiwan）']
        }, {
            title: '您的工作性质（what is your function）？',
            arr: ['管理（Management）', '采购（Purchasing）', '市场/销售（Marketing/Sales)', '生产/制造（Production/Manufacturing）', '设计师（Designer）', '研发（Research/Development）', '零售（Retailing）', '广告/推广/传媒（Advertising/Promotion）', '政府/管理人员（Government/Administration）', '原料供应商（Material Suppliers）']
        }, {
            title: '公司主要经营范围（what is your company’sprimary activity）？',
            arr: ['面料（Material）', '辅料（Accessory）', '家用纺织品（Famliy textile)', '家具（Furniture）', '纤维/纱线（Fiber/Yarn）', '流行趋势（Fashion trend）', '检测（Tset）', '服务/咨询（Service/Consultant）', '媒体广告（Media advertisement）', '行业协会（Tradeassociation）']
        }, {
            title: '感兴趣的产品（which products are you in terested in）？',
            arr: ['窗帘布面料（Curtain Fabric)', '沙发布面料（Sofa Fabric)', '墙布面料（Wallcloth Fabric)', '功能性纺织品（Functional Textile)', '各类辅料（Accessory）', '趋势（trend)']
        }, {
            title: '通过以下什么途径知道本展会（How did you learm about the exhibition）？',
            arr: ['主办单位邀请函（Directmai/Invitation）', '报纸广告（Newspaper)', '杂志（Magazine Advertisement)', '网络（Internet)', '供应商/参展商邀请（Invitation From Supplier/Exhibitor）', '朋友/同事/同行（Friends/Colleagues Business/Associates）', '行业协会（Trade Association)']
        }]
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            tactivityid: options.id
        })
        //判断是否存在登录态
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "customer.activity.activitysignup",
            "method": "getsignupmsg",
            "content": {
                "tactivityid": options.id
            }
        }).then(res => {
            console.log("获取个人信息", res)
            if (res.msg == '失败') {
                this.setData({
                    isNoToken: true
                })
            } else {
                this.setData({
                    fphonenumber: wx.getStorageSync('userData').fphonenumber
                })
                if (res.data.length >= 1) {
                    this.setData({
                        pageType: 1,
                        msg: res.data[0]
                    })
                    this.qrCode();
                    this.goTop();
                }
            }
        })
    },
    qrCode() {
        let codeText = this.data.msg.tactivitysignupid + '';
        console.log(codeText)
        var imgData = QR.drawImg(codeText, {
            typeNumber: 4,
            errorCorrectLevel: 'M',
            size: 500
        })
        base64src(imgData, res => {
            this.setData({
                qrcodeURL: res
            });
        });
    },
    radioChange(e) {
        const {
            name,
            index
        } = e.currentTarget.dataset;
        const data = {
            "question": name,
            "answer": e.detail
        }
        let fquestionnaire = this.data.fquestionnaire;
        fquestionnaire[index] = data;
        console.log(fquestionnaire);

    },
    /* 获取验证码 */
    getVerifyCode() {
        //验证手机号码
        if (!_Verify.phoneNumber(this.data.fphonenumber, 1)) return this.setData({
            "errTips.fphonenumber": true
        });
        /* 倒计时中阻止 */
        if (this.data.countDownTime != 30) return wx.showToast({
            title: '请勿重复获取验证码',
            icon: "none"
        });
        _Http.getPassword({
            "phonenumber": this.data.fphonenumber,
            "client": "wechat_customer"
        }).then(res => {
            this.setData({
                countDownTime: this.data.countDownTime - 1
            })
            countDownTime1 = setInterval(() => {
                if (this.data.countDownTime != 0) {
                    this.setData({
                        countDownTime: this.data.countDownTime - 1
                    })
                } else {
                    clearInterval(countDownTime1);
                    this.setData({
                        countDownTime: 30
                    })
                }
            }, 1000);
            wx.showToast({
                title: res.msg,
                icon: "none",
                duration: 3000
            })
        })
    },
    //验证必填项
    verify() {
        let errTips = this.data.errTips,
            result = false;
        for (let key in this.data.errTips) {
            if (this.data.isNoToken) {
                if (this.data[key] == '') {
                    errTips[key] = true;
                    result = true;
                }
            } else {
                if (this.data[key] == '' && key != 'password') {
                    errTips[key] = true;
                    result = true;
                }
            }
        };
        if (this.data.fidcard.length != 18) {
            errTips.fidcard = true;
            result = true;
        }
        this.setData({
            errTips
        })
        return result;
    },
    /* 提交表单 */
    submitData(e) {
        if (this.data.throttle) return;
        if (!this.data.rulesChecked) return wx.showToast({
            title: '请先勾选《用户隐私协议》',
            icon: "none"
        })
        if (e.target.dataset.text == '下一步') {
            if (this.verify()) return wx.showToast({
                title: '请完善表格必填项',
                icon: "none"
            });
            if (!this.data.isNoToken) {
                //存在登录态，直接提交
                // this.signup(wx.getStorageSync('userData').token);
                this.setData({
                    pageType: 2,
                    butText: '立即报名'
                })
                this.goTop();
            } else {
                //未存在登录态，先登录在提交
                if (!this.data.password) {
                    this.setData({
                        "errTips.password": true
                    })
                    return wx.showToast({
                        title: '还未填写验证码',
                        icon: "none"
                    });
                };
                _Http.login({
                    "phonenumber": this.data.fphonenumber,
                    "password": utilMd5.hexMD5(this.data.password),
                    "client": "wechat_customer"
                }).then(res => {
                    /* 结果验证 */
                    if (res.msg != '成功') {
                        this.setData({
                            "errTips.password": true
                        });
                        return wx.showToast({
                            title: '账号或验证码错误!',
                            icon: "none"
                        });
                    }
                    console.log("用户登录", res)
                    if (res.account_list.length == 1) {
                        // this.signup(res.account_list[0].token);
                        wx.setStorageSync('userData', res.account_list[0]);
                        this.setData({
                            pageType: 2,
                            butText: '立即报名'
                        })
                        this.goTop();
                    } else {
                        this.setData({
                            account_list: res.account_list,
                            myShowModel: true
                        })
                    }
                })
            }
        } else {
            let c = 0;
            for (let i = 0; i < this.data.fquestionnaire.length; i++) {
                if (typeof (this.data.fquestionnaire[i]) == 'object') c += 1;
            }
            if (c != this.data.surveysList.length) {
                wx.showToast({
                    title: '请完善问卷调查',
                    icon: "none"
                })
            } else {
                this.signup(wx.getStorageSync('userData').token)
            }
        }
    },
    //回到顶部
    goTop: function (e) { // 一键回到顶部
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: 0
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },
    /* 获取焦点 */
    inputFocus(e) {
        const {
            name
        } = e.currentTarget.dataset;
        let errTips = this.data.errTips;
        errTips[name] = false;
        this.setData({
            errTips
        })
    },
    /* 失去焦点 */
    inputBlur(e) {
        const {
            name
        } = e.currentTarget.dataset;
        const {
            value
        } = e.detail;
        if (name == 'fphonenumber') {
            if (!_Verify.phoneNumber(this.data.fphonenumber, 1)) return this.setData({
                "errTips.fphonenumber": true
            })
        } else if (name == 'fidcard') {
            if (this.data.fidcard.length != 18) {
                wx.showToast({
                    title: '身份证号码格式错误',
                    icon: "none"
                })
                return this.setData({
                    "errTips.fidcard": true
                })
            }
        }
        if (value.trim() == "") {
            let errTips = this.data.errTips;
            errTips[name] = true;
            this.setData({
                errTips
            })
        }
    },
    /* 选择用户 */
    userSelect(e) {
        const {
            index,
            item
        } = e.currentTarget.dataset;
        this.setData({
            userIndex: index
        })
        wx.setStorageSync('userData', item);
        this.setData({
            pageType: 2,
            butText: '立即报名'
        })
        this.goTop();
    },
    /* 提交报名表 */
    signup(token) {
        _Http.basic({
            "accesstoken": token,
            "classname": "customer.activity.activitysignup",
            "method": "getsignupmsg",
            "content": {
                "tactivityid": this.data.tactivityid
            }
        }).then(res => {
            if (res.msg != '成功') return wx.showToast({
                title: res.data,
                icon: "none"
            })
            if (res.data.length >= 1) {
                this.setData({
                    pageType: 1,
                    msg: res.data[0]
                })
                this.qrCode();
                this.goTop();
            } else {
                _Http.basic({
                    "accesstoken": token,
                    "classname": "customer.activity.activitysignup",
                    "method": "signup",
                    "content": {
                        "fname": this.data.fname,
                        "fidcard": this.data.fidcard,
                        "fphonenumber": this.data.fphonenumber,
                        "fcompname": this.data.fcompname,
                        "frole": this.data.frole,
                        "findustry": this.data.findustry,
                        "faddress": this.data.faddress,
                        "fchannel": this.data.fchannel,
                        "tactivityid": this.data.tactivityid,
                        "fquestionnaire": this.data.fquestionnaire
                    }
                }).then(res => {
                    console.log("提交报名", res)
                    if (res.msg != '成功') return wx.showToast({
                        title: res.data,
                        icon: "none"
                    })
                    this.setData({
                        throttle: true
                    });
                    _Http.basic({
                        "accesstoken": token,
                        "classname": "customer.activity.activitysignup",
                        "method": "getsignupmsg",
                        "content": {
                            "tactivityid": this.data.tactivityid
                        }
                    }).then(res => {
                        if (res.msg != '成功') return wx.showToast({
                            title: res.data,
                            icon: "none"
                        })
                        this.setData({
                            pageType: 1,
                            msg: res.data[0]
                        })
                        this.qrCode();
                        this.goTop();
                        wx.showToast({
                            title: '报名成功'
                        })
                    })
                    /* setTimeout(() => {
                        wx.navigateBack({
                            delta: 1,
                        })
                    }, 500); */
                })
            }
        })
    },
    /* input事件剔除特殊字符 */
    eliminate(value) {
        const {
            name
        } = value.target.dataset;
        this.setData({
            [name]: _Verify.Eliminate(value.detail)
        })
    },
    /* 用户守则 */
    rulesOnChange() {
        this.setData({
            rulesChecked: !this.data.rulesChecked
        })
    },
    viewRules() {
        wx.downloadFile({
            url: 'https://bwj.obs.cn-east-2.myhuaweicloud.com/resources/PrivacyPolicy.docx',
            success: (res) => {
                console.log(res)
                wx.openDocument({
                    filePath: res.tempFilePath,
                    fail: (err) => {
                        console.log(err)
                        wx.showToast({
                            title: '读取失败,请稍后再试',
                            icon: "none"
                        })
                    }
                })
            },
            fail: (err) => {
                console.log(err)
                wx.showToast({
                    title: '读取失败,请稍后再试',
                    icon: "none"
                })
            }
        })
        return
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})