import WxValidate from '../../utils/WxValidate.js';
const app = require('../../utils/util.js');
const tool = require('../../utils/tool.js');
const COS = require('../../utils/cos.js');
Page({
  data: {
    imgsrc: '../../images/cardModel.png',
    photo: '../../images/cardModel.png',
    questionList: [{
      name: '女',
      value: '0',
      checked: false
    }, {
      name: '男',
      value: '1',
      checked: false
    }],
    mzArr: [
      "汉族", "满族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "侗族", "瑶族", "白族", "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "傈僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族", "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "朝鲜族", "塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族", "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族", "赫哲族", "门巴族", "珞巴族", "基诺族", "其他"
    ],
    constellationArr: [],
    form: {
      idFront: '',
      idCard: '',
      name: '',
      sex: '',
      age: '',
      nativePlace: '',
      nation: '',
      birthday: '',
      constellation: '',
      photoUrl: ''
    }
  },
  change(e) {
    console.log(e)
    if (e.detail.value.length != 0) {
      this.setData({
        xyAgree: true
      })
    } else {
      this.setData({
        xyAgree: false
      })
    }
    console.log(this.data.xyAgree)
  },
  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.constellationArrValue[e.detail.value],
      constellationLabel: 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
      if (items[i].value == values) {
        items[i].checked = true
      }
    }
    let sex = 'form.sex';
    let sexValue = 0;
    if (e.detail.value == '男') {
      sexValue = 1;
    }
    this.setData({
      questionList: this.data.questionList,
      [sex]: sexValue
    })
    console.log(sexValue)
  },
  uploadCard(e) {
    let type = e.currentTarget.dataset.type
    wx.showLoading({
      title: '上传中',
    })
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        let tempFilePaths = res.tempFilePaths[0]
        console.log(tempFilePaths, '图片的临时路径')
        this.toCos(tempFilePaths, type)
      },
      fail: () => {
        wx.hideLoading()
      }
    })
  },
  toCos(path, type) {
    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) {
          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,
          })
        });
      });
    };
    // 上传文件
    console.log(path)
    var Key = path.substring(path.length - 20); // 这里指定上传的文件名
    console.log(Key, '我是名字')
    var signPathname = '/';
    if (ForcePathStyle) {
      signPathname = '/' + Bucket + '/';
    }
    getAuthorization({
      Method: 'POST',
      Pathname: signPathname
    }, (AuthData) => {
      var requestTask = wx.uploadFile({
        url: prefix,
        name: 'file',
        filePath: path,
        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)
          if (type == 'card') {
            this.setData({
              imgsrc: res.header.Location
            })
            this.toJx(res.header.Location)
          }
          if (type == 'photo') {
            let photoUrl = 'form.photoUrl';
            this.setData({
              photo: res.header.Location,
              [photoUrl]: res.header.Location
            })
            wx.hideLoading();
          }
        },
        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 idFront = 'form.idFront'
          let idCard = 'form.idCard'
          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'
          let res1 = JSON.parse(res.data.cardMessage)
          let sexTurn = 0;
          if (res1.words_result['性别'].words == '男') {
            sexTurn = 1;
          }
          let xz = this.getXingzuo(res1.words_result['出生'].words.substring(4, 6), res1.words_result['出生'].words.substring(6, 8));
          console.log(xz)
          for (let i = 0; i < this.data.constellationArr.length; i++) {
            console.log(this.data.constellationArr[i])
            if (this.data.constellationArr[i] == xz) {
              this.setData({
                constellationLabel: this.data.constellationArr[i],
                [constellation]: this.data.constellationArrValue[i]
              })
            }
          }
          this.setData({
            [idFront]: location,
            [idCard]: res1.words_result['公民身份号码'].words,
            [name]: res1.words_result['姓名'].words,
            [sex]: sexTurn,
            [age]: tool.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)

          })
          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
            if (items[i].name == values) {
              items[i].checked = true
            }
          }
          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 = {
      idFront: {
        required: true,
      },
      photoUrl: {
        required: true,
      },
      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 = {
      idFront: {
        required: '请上传身份证照片哟',
      },
      photoUrl: {
        required: '请上传本人照片哟',
      },
      name: {
        required: '请填写姓名哟',
        minlength: '请输入正确的名称哟',
        maxlength: '请输入正确的名称哟'
      },
      sex: {
        required: '请选择性别哟'
      },
      age: {
        required: '请填写年龄哟'
      },
      nativePlace: {
        required: '请填写户籍地址哟'
      },
      nation: {
        required: '请选择民族哟'
      },
      birthday: {
        required: '请填写生日哟'
      },
      constellation: {
        required: '请选择星座哟'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  getInfos() {
    wx.showLoading();
    wx.request({
      url: app.globalData.publicUrl + '/wx/member/' + this.data.openid + '/info',
      method: "get",
      success: (res) => {
        console.log(res, '我是获取的信息')
        let idFront = 'form.idFront'
        let photoUrl = 'form.photoUrl'
        let idCard = 'form.idCard'
        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'
        tool.formDetails('he_astrology').then(result => {
          this.setData({
            constellationArr: result[0],
            constellationArrValue: result[1]
          })
          if (res.data.info.constellation) {
            for (let i = 0; i < result[1].length; i++) {
              if (result[1][i] == res.data.info.constellation) {
                this.setData({
                  [constellation]: result[1][i],
                  constellationLabel: result[0][i],
                })
              }
            }
          }
        })
        if (res.data.code == 0) {
          const items = this.data.questionList
          const values = res.data.info.sex
          for (let i = 0, lenI = items.length; i < lenI; ++i) {
            if (items[i].value == values) {
              items[i].checked = true
            }
          }
          this.setData({
            imgsrc: res.data.info.idFront,
            [idFront]: res.data.info.idFront,
            photo: res.data.info.photoUrl,
            [photoUrl]: res.data.info.photoUrl,
            [idCard]: res.data.info.idCard,
            [name]: res.data.info.name,
            [sex]: res.data.info.sex,
            questionList: this.data.questionList,
            [age]: tool.formatTime(new Date()) - res.data.info.idCard.substring(6, 10),
            [nativePlace]: res.data.info.nativePlace,
            [nation]: res.data.info.nation,
            [birthday]: res.data.info.birthday
          })

        }
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
  // 表单提交事件
  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
    }
    if (!this.data.xyAgree) {
      wx.showToast({
        title: '请仔细阅读协议并勾选呦',
        icon: 'none',
        duration: 3000,
      })
      return false
    }
    wx.request({
      url: app.globalData.publicUrl + '/wx/member/' + this.data.openid + '/info',
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: params,
      success: (res) => {
        console.log(res)
        if (res.data.code == 0) {
          wx.showModal({
            title: '信息提交成功了呦',
            // content: '快去完善详细信息吧！',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/InfoType/InfoType',
                })
              }
            }
          });
        }
      }
    })
  },
  goxy(){
    wx.navigateTo({
      url: '/pages/infoAgreement/infoAgreement',
    })
  },
  async onLoad(options) {
    this.initValidate()
    tool.openidStatus().then(result => {
      this.setData({
        openid: result[0],
        sessionkey: result[1]
      })
      this.getInfos();
    })
  }
})