var company = getApp().globalData.company;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        realname: '',
        cardtype: '身份证',
        idcard: '',
        mobile: '',
        formctrl:{
            realname: '姓名',
            cardtype: '身份证',
            idcard: '证件号码',
            mobile: '手机号码' 
        },
        showTypePicker: false,
        columns: ['身份证','护照','港澳通行证','台胞证'],
    },
    selectCardtype(){
        this.setData({
            showTypePicker:true
        })
    },
    typePickerEnter(event){
        const { picker, value, index } = event.detail;
        console.log(picker, value, index);
        console.log(`当前值：${value}, 当前索引：${index}`);
        this.setData({
            cardtype:value,
            showTypePicker:false
        })
    },
    typePickerCancel(){
        console.log('取消');
        this.setData({
            showTypePicker:false
        })
    },
    onChange(){
        console.log(this.data.realname);
    },
    checkform(){
        let formctrl = this.data.formctrl;
        let keys = Object.keys(formctrl);
        for (let index = 0; index < keys.length; index++) {
            let key = keys[index];
            if(this.data[key].trim() == ''){
                console.log(key,this.data[key]);
                wx.showToast({
                  title: `请输入${formctrl[key]}`,
                  icon: 'error'
                })
                return false;
            }
        }
        // this.data.realname
        // this.data.idcard
        let checkName = /[\u4e00-\u9fa5]/.test(this.data.realname);
        if (!checkName) {
            wx.showToast({
                title: '请输入您的真实姓名',
                icon: 'none',
                duration: 2000
            })
            return false
        }
        let checkMobile = /^1[34578]\d{9}$/.test(this.data.mobile);
        if (!checkMobile) {
            wx.showToast({
                title: '手机号码格式有误',
                icon: 'none',
                duration: 2000
            })
            return false
        }
        let checkIdcard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/gi.test(this.data.idcard)
        if (!checkIdcard) {
            wx.showToast({
                title: '请输入正确的身份证号',
                icon: 'none',
                duration: 2000
            })
            return false
        }

        return true;
    },
    verifyIdcardName(){
        return new Promise((resolve,reject)=>{
            wx.request({
                url: "https://server.fmode.cn/api/apig/idcard", //请求接口的url
                method: "POST", //请求方式
                data: {
                    company: company,
                    cardNo: this.data.idcard,
                    realName: this.data.realname
                }, //请求参数
                header: {
                    "content-type": "application/json", // 默认值
                },
                success: (res) => {
                    if(res.statusCode != '200'){
                        console.log(res);
                        resolve(false)
                    }
                    console.log(res.data.data.result);
                    if (res.data.data.result.isok) {
                        resolve(true)
                    } else {
                        resolve(false)
                    }
                },
                fail:(err)=>{
                    console.log(err);
                    wx.showToast({
                        title: err,
                        icon: 'none',
                        duration: 2000
                    })
                }
            })
        })

    },
    async save(){
        let checked = this.checkform()
        console.log(checked);
        if(!checked){
            return false
        }
        let verifyIdcardName = await this.verifyIdcardName()
        console.log(verifyIdcardName);
        if(!verifyIdcardName){
            wx.showToast({
              title: '身份校验失败，请输入真实姓名和身份证号',
              icon: 'none'
            })
            return false
        }
        wx.showToast({
            title: '添加成功',
            icon: 'none',
            duration: 1000
          })

        let formdata = {
            realname:this.data.realname,
            cardtype:this.data.cardtype,
            idcard:this.data.idcard,
            mobile:this.data.mobile
        };
        let customers = wx.getStorageSync("customers")
        if(customers){
            console.log(customers);
            customers.forEach((customer,index) =>{
                if(customer.realname == this.data.realname){
                    customers[index] = formdata
                }
            })
        }else {
            customers = []
            customers.push(formdata)
        }
        wx.setStorageSync("customers",customers)
        setTimeout(()=>{
            wx.navigateBack({
                delta: 1,
              }) 
        },1000)
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options);
        let {type,name}=options;
        if(type== 'edit' && name){
            this.initCustomerInfo(name)
        }
    },
    initCustomerInfo(name){
        let customers = wx.getStorageSync("customers")
        if(customers){
            console.log(customers);
            customers.forEach((customer,index) =>{
                if(customer.realname == name){
                    this.setData({
                        realname: customer.realname,
                        cardtype: customer.cardtype,
                        idcard: customer.idcard,
                        mobile: customer.mobile,
                    })
                }
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

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

    },

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

    },

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

    },

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

    }
})