import WxValidate from '../../utils/WxValidate.js';
const app = require('../../utils/util.js');
const tools = require('../../utils/tool.js');
const COS = require('../../utils/cos.js');
Page({
  data: {
    imgsrc: '../../images/cardModel.png',
    questionList: [{
        name: '男',
        value: '男',
        checked: false
      },
      {
        name: '女',
        value: '女',
        checked: false
      }
    ],
    mzArr: [
      "汉族", "满族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "侗族", "瑶族", "白族", "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "傈僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族", "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "朝鲜族", "塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族", "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族", "赫哲族", "门巴族", "珞巴族", "基诺族", "其他"
    ],
    constellationArr: [
      "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座", "水瓶座", "双鱼座。"
    ],
    form: {
      card: '',
      name: '',
      sex: '',
      age: '',
      nativePlace: '',
      nation: '',
      birthday: '',
      constellation: ''
    }
  },
  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.toCos()
      }
    })
  },
  toCos() {
    var Bucket = 'yuehe-1257653330';
    var Region = 'ap-beijing';
    var ForcePathStyle = false;
    var prefix = 'https://' + Bucket + '.cos.' + Region + '.myqcloud.com/';
    if (ForcePathStyle) {
      prefix = 'https://cos.' + Region + '.myqcloud.com/' + Bucket + '/';
    }
    var stsCache;
    var getCredentials = (callback) => {
      if (stsCache && Date.now() / 1000 + 30 < stsCache.expiredTime) {
        callback(data.credentials);
        return;
      }
      wx.request({
        method: 'POST',
        url: app.globalData.publicUrl + '/wx/member/' + this.data.openid + '/getCosSts',
        success: function (result) {
          console.log(result, '222222222222')
          var credentials = result.data.credential.credentials;
          if (credentials) {
            stsCache = result.data.credential
          } else {
            wx.hideLoading()
            wx.showModal({
              title: '临时密钥获取失败',
              content: JSON.stringify(data),
              showCancel: false
            });
          }
          callback(stsCache && stsCache.credentials);
        },
        error: function (err) {
          wx.hideLoading()
          wx.showModal({
            title: '临时密钥获取失败',
            content: JSON.stringify(err),
            showCancel: false
          });
        }
      });
    };
    // 计算签名
    var getAuthorization = function (options, callback) {
      getCredentials(function (credentials) {
        callback({
          XCosSecurityToken: credentials.sessionToken,
          Authorization: COS({
            SecretId: credentials.tmpSecretId,
            SecretKey: credentials.tmpSecretKey,
            Method: options.Method,
            Pathname: options.Pathname,
          })
        });
      });
    };
    // 上传文件
    var Key = this.data.imgsrc.substr(this.data.imgsrc.lastIndexOf('/') + 1); // 这里指定上传的文件名
    var signPathname = '/';
    if (ForcePathStyle) {
      signPathname = '/' + Bucket + '/';
    }
    getAuthorization({
      Method: 'POST',
      Pathname: signPathname
    }, (AuthData) => {
      var requestTask = wx.uploadFile({
        url: prefix,
        name: 'file',
        filePath: this.data.imgsrc,
        formData: {
          'key': "face/" + Key,
          'success_action_status': 200,
          'Signature': AuthData.Authorization,
          'x-cos-security-token': AuthData.XCosSecurityToken,
          'Content-Type': '',
        },
        success: (res) => {
          console.log(res.header.Location)
          let card = 'form.card'
          this.setData({
            [card]: res.header.Location
          })
          this.toJx(res.header.Location)
        },
        fail: function () {
          wx.hideLoading()
          wx.showModal({
            title: '上传失败',
            showCancel: false
          });
        }
      });
      requestTask.onProgressUpdate(function (res) {
        console.log('进度:', res.progress);
      });
    });
  },
  toJx(location) {
    wx.request({
      url: app.globalData.publicUrl + '/wx/member/' + this.data.openid + '/ocrCard',
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        path: location,
        side: 'front'
      },
      success: (res) => {
        console.log(res)
        if (res.data.code == 0) {
          let res1 = JSON.parse(res.data.cardMessage)
          let card = 'form.card'
          let name = 'form.name'
          let sex = 'form.sex'
          let age = 'form.age'
          let nativePlace = 'form.nativePlace'
          let nation = 'form.nation'
          let birthday = 'form.birthday'
          let constellation = 'form.constellation'
          this.setData({
            [card]: res1.words_result['公民身份号码'].words,
            [name]: res1.words_result['姓名'].words,
            [sex]: res1.words_result['性别'].words,
            [age]: tools.formatTime(new Date()) - res1.words_result['出生'].words.substring(0, 4),
            [nativePlace]: res1.words_result['住址'].words,
            [nation]: res1.words_result['民族'].words,
            [birthday]: res1.words_result['出生'].words.substring(0, 4) + '-' + res1.words_result['出生'].words.substring(4, 6) + '-' + res1.words_result['出生'].words.substring(6, 8),
            [constellation]: this.getXingzuo(res1.words_result['出生'].words.substring(4, 6), res1.words_result['出生'].words.substring(6, 8))
          })
          const items = this.data.questionList;
          const values = res1.words_result['性别'].words;
          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
          })
        }
      },
      complete:()=>{
        wx.hideLoading()
      }
    })
  },
  getXingzuo(month, day) {
    const s = '魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯';
    const arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22];
    return s.substr(month * 2 - (day < arr[month - 1] ? 2 : 0), 2);
  },
  //报错 
  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)
  },
  // 表单提交事件
  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
    }
    wx.request({
      url: app.globalData.publicUrl + '/wx/member/' + this.data.openid + '/info',
      method: "POST",
      data: params,
      success: (res) => {
        console.log(res)
        if (res.data.code == 0) {
          wx.showModal({
            title: '上传成功',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/personInfoDetail/personInfoDetail',
                })
              }
            }
          });
        }
      }
    })
  },
  onLoad: function (options) {
    this.initValidate()
    const getOpenid = tools.openidStatus();
    this.setData({
      openid: getOpenid[0],
      sessionkey: getOpenid[1]
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})