import WxValidate from '../../utils/WxValidate.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgsrc: '../../images/cardModel.png',
    questionList: [{
        name: '男',
        value: '男',
        checked: true
      },
      {
        name: '女',
        value: '女',
        checked: false
      }
    ],
    mzArr: [
      "汉族", "满族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "侗族", "瑶族", "白族", "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "傈僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族", "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "朝鲜族", "塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族", "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族", "赫哲族", "门巴族", "珞巴族", "基诺族", "其他"
    ],
    constellationArr: [
      "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座", "水瓶座", "双鱼座。"
    ],
    form: {
      name: '',
      sex: '',
      age: '',
      nativePlace: '',
      nation: '',
      birthday: '',
      strar: ''
    }
  },
  // 表单提交事件
  formSubmit(e) {
    console.log(e.detail.value)
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    // this.showModal({
    //   msg: '提交成功'
    // })
    wx.navigateTo({
      url: '/pages/personInfoDetail/personInfoDetail',
    })
  },
  nationPicker(e) {
    let nation='form.nation'
    this.setData({
      [nation]: this.data.mzArr[e.detail.value],
    })
  },
  birthdayPicker(e) {
    let birthday='form.birthday'
    this.setData({
      [birthday]: e.detail.value
    })
  },
  constellationPicker(e) {
    let constellation='form.constellation'
    this.setData({
      [constellation]: this.data.constellationArr[e.detail.value]
    })
  },
  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    const items = this.data.questionList
    const values = e.detail.value
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].checked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].value === values[j]) {
          items[i].checked = true
          break
        }
      }
    }
    this.setData({
      questionList: this.data.questionList
    })
  },
  uploadCard() {
    // wx.showLoading({
    //   title: '加载中',
    // })
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        let tempFilePaths = res.tempFilePaths[0]
        console.log(tempFilePaths, '图片的临时路径')
        this.setData({
          imgsrc: tempFilePaths
        })
        // this.goOcr(tempFilePaths)
      }
      // ,
      // fail: () => {
      //   wx.hideLoading();
      // }
    })
  },
  // 百度身份证OCR接口 首先去后台获得token
  goOcr(file) {
    wx.request({
      url: app.globalData.publicUrl + '/applet/getToken',
      method: "GET",
      header: {
        appletsId: wx.getStorageSync('openId')
      },
      success: (res) => {
        if (res.data.data.status == 200) {
          let token = res.data.data.token;
          if (token) {
            var _this = this;
            wx.getFileSystemManager().readFile({
              filePath: file,
              encoding: 'base64',
              success: res1 => {
                console.log('读取本地文件basema ', res1)
                let img = 'data:image/png;base64,' + res1.data
                wx.request({
                  url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + token,
                  method: 'POST',
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  data: {
                    id_card_side: 'front',
                    image: img
                  },
                  dataType: 'json',
                  success: (e) => {
                    // 扫描后赋值 
                    if (e.data.idcard_number_type == 1) {
                      let result = e.data.words_result
                      _this.data.parameter.forEach(item => {
                        if (item.name == result['性别'].words) {
                          item.checked = true;
                        }
                      })
                      var myDate = new Date();
                      var tYear = myDate.getFullYear();
                      let aa = parseInt(result['公民身份号码'].words.slice(6, 10));
                      _this.setData({
                        userName: result['姓名'].words,
                        idCardNumber: result['公民身份号码'].words,
                        parameter: _this.data.parameter,
                        age: tYear - aa
                      })
                    } else {
                      wx.showToast({
                        title: "身份证识别失败",
                        icon: 'none',
                        duration: 2000,
                      })
                    }
                  }
                })
              }
            })
          } else {
            wx.showToast({
              title: '身份证识别失败',
              icon: 'none',
              duration: 2000,
            })
          }
        } else {
          wx.hideLoading()
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    })
  },
  //报错 
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //验证函数
  initValidate() {
    const rules = {
      name: {
        required: true,
        minlength: 2,
        maxlength: 4
      },
      sex: {
        required: true
      },
      age: {
        required: true
      },
      nativePlace: {
        required: true
      },
      nation: {
        required: true
      },
      birthday: {
        required: true
      },
      constellation: {
        required: true
      }
    }
    const messages = {
      name: {
        required: '请填写姓名',
        minlength: '请输入正确的名称',
        maxlength: '请输入正确的名称'
      },
      sex: {
        required: '请选择性别'
      },
      age: {
        required: '请填写年龄'
      },
      nativePlace: {
        required: '请填写户籍地址'
      },
      nation: {
        required: '请选择民族'
      },
      birthday: {
        required: '请填写生日'
      },
      constellation: {
        required: '请选择星座'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  onLoad: function (options) {
    this.initValidate()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})