const app = require('../../utils/util.js');
var util = require('../../utils/md5.js')
import WxValidate from '../../utils/WxValidate';
Page({
  data: {
    postindex: null,
    incomeindex: null,
    educationindex: null,
    posttext: '请选择',
    incometext: '请选择',
    educationtext: '请选择',
    userName: '', //姓名
    idCardNumber: '', //身份证号码
    age: '', //年龄
    parameter: [{
      name: '男'
    }, {
      name: '女',
    }],
    postList: [{
        name: '在职人员'
      },
      {
        name: '两委人员'
      },
      {
        name: '社会组织人员'
      },
      {
        name: '志愿者'
      },
      {
        name: '学生'
      },
      {
        name: '其他'
      },
    ],

    incomeList: [{
        name: '暂无'
      },
      {
        name: '500元以下'
      },
      {
        name: '500-1000元'
      },
      {
        name: '1000-2000元'
      },
      {
        name: '2000-5000元'
      },
      {
        name: '5000元-1万元'
      },
      {
        name: '1-2万元'
      },
      {
        name: '2万元以上'
      },
    ],
    educationList: [{
        name: '小学'
      },
      {
        name: '初中'
      },
      {
        name: '高中'
      },
      {
        name: '大专'
      },
      {
        name: '本科'
      },
      {
        name: '本科以上'
      },
    ],
  },
  uploadIdcard() {
    wx.showLoading({
      title: '加载中',
    })
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        console.log(res, '图片的临时路径')
        let tempFilePaths = res.tempFilePaths[0]
        this.goOcr(tempFilePaths)
      },
      fail: () => {
        wx.hideLoading();
      }
    })
  },
  uploadIdimg() {
    wx.showLoading({
      title: '加载中',
    })
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        console.log(res, '图片的临时路径')
        let tempFilePaths = res.tempFilePaths[0]
        wx.uploadFile({
          url: app.globalData.publicUrl + '/sys/user/upload',
          filePath: tempFilePaths,
          name: 'uploadFile',
          formData: {
            "user": "test",
          },
          header: {
            appletsId: wx.getStorageSync('openId'),
          },
          success: (res) => {
            console.log(res)
            let datas = JSON.parse(res.data)
            console.log(datas.data)
            this.goFace(datas.data)
          }
        })
      },
      fail: (e) => {
        wx.hideLoading();
      }
    })
  },
  goFace(file) {
    wx.request({
      url: app.globalData.publicUrl + '/user/getPeople',
      method: "POST",
      header: {
        appletsId: wx.getStorageSync('openId')
      },
      data: {
        photoPath: file
      },
      success: (res) => {
        wx.hideLoading();
        console.log(res, '有没有face')
        if (res.data.code == 0) {
          this.setData({
            myPhoto: file
          })
        } else {
          wx.showToast({
            title: '面部识别不通过，请重新上传',
            icon: 'none',
            duration: 3000,
          })
        }
      },
      fail: () => {
        wx.hideLoading();
      }
    })
  },
  // 百度身份证OCR接口 首先去后台获得token
  goOcr(file) {
    wx.request({
      url: app.globalData.publicUrl + '/applet/getToken',
      method: "GET",
      header: {
        appletsId: wx.getStorageSync('openId')
      },
      success: (res) => {
        wx.hideLoading();
        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
                      console.log(result, "00000000");
                      _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.data.userName
                      if (_this.data.userName == result['姓名'].words) {
                        _this.setData({
                          userName: result['姓名'].words,
                          idCardNumber: result['公民身份号码'].words,
                          parameter: _this.data.parameter,
                          age: tYear - aa
                        })
                        wx.uploadFile({
                          url: app.globalData.publicUrl + '/sys/user/upload',
                          filePath: file,
                          name: 'uploadFile',
                          formData: {
                            "user": "test",
                          },
                          header: {
                            appletsId: wx.getStorageSync('openId'),
                          },
                          success: (res) => {
                            console.log(res)
                            let datas = JSON.parse(res.data)
                            console.log(datas.data)
                            this.setData({
                              idPhoto: datas.data
                            })
                            // this.goOcr(datas.data)
                          }
                        })
                      } else {
                        wx.showModal({
                          showCancel: false,
                          content: '证件信息与后台登记姓名不一致'
                        })
                      }
                    } else {
                      wx.showToast({
                        title: "身份证OCR识别失败",
                        icon: 'none',
                        duration: 2000,
                      })
                    }
                  },
                  // complete: (e) => {
                  //   wx.hideLoading();
                  // }
                })
              },
              // 错误信息
              fail: console.error
            })
          } else {
            // wx.hideLoading();
            wx.showToast({
              title: '身份证识别失败,token失效',
              icon: 'none',
              duration: 2000,
            })
          }
        } else {
          wx.hideLoading()
        }
      },
      fail: () => {
        wx.hideLoading();
      }
    })
  },
  postListChange: function (e) {
    this.setData({
      postindex: e.detail.value,
      posttext: '',
    })
  },
  changeIdCard(e) {
    console.log(e.detail.value, "121212");
    var myDate = new Date();
    var tYear = myDate.getFullYear();
    let aa = parseInt(e.detail.value.slice(6, 10));
    console.log(aa);
    this.setData({
      age: tYear - aa
    })
  },
  incomeListChange: function (e) {
    this.setData({
      incomeindex: e.detail.value,
      incometext: '',
    })
  },

  educationListChange: function (e) {
    this.setData({
      educationindex: e.detail.value,
      educationtext: '',
    })
  },
  initValidate() {
    const rules = {
      userName: {
        required: true,
      },
      sex: {
        required: true,
      },
      idCardNumber: {
        required: true,
        idcard: true,
      },
      age: {
        required: true,
      },
      job: {
        required: true,
      },
      income: {
        required: true,
      },
      education: {
        required: true,
      },
      idCardPicPath: {
        required: true,
      },
      headPicPath: {
        required: true,
      }
      // params.idCardPicPath = this.data.idPhoto
      // params.headPicPath = this.data.myPhoto
    };
    const messages = {
      userName: {
        required: '请输入您的姓名',
      },
      sex: {
        required: '请输入您的性别',
      },
      idCardNumber: {
        required: '请输入您的身份证号',
        idcard: '身份证号格式错误 ',
      },
      age: {
        required: '请输入您的年龄',
      },
      job: {
        required: '请输入您的职务',
      },
      income: {
        required: '请输入您的收入',
      },
      education: {
        required: '请输入您的学历',
      },
      idCardPicPath: {
        required: '请上传您的身份证照片',
      },
      headPicPath: {
        required: '请上传您本人的照片',
      },
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  showModal(error) {
    wx.showToast({
      title: error.msg,
      icon: 'none',
      duration: 2000,
    })
  },
  formSubmit(e) {
    // console.log(e.detail, "表单的内容");
    /***4-3(表单提交校验)*/
    const params = e.detail.value
    params.idCardPicPath = this.data.idPhoto
    params.headPicPath = this.data.myPhoto
    params.IsPerfect = '1'
    console.log(params, '表单的内容')
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    /*** 这里添写验证成功以后的逻辑**/
    //验证通过以后->
    this.submitInfo(params);
  },
  //修改信息接口
  submitInfo(params) {
    wx.request({
      url: app.globalData.publicUrl + '/applet/suppleUserInfo',
      method: "POST",
      data: params,
      header: {
        appletsId: wx.getStorageSync('openId')
      },
      success: (res) => {
        if (res.data.code == 0) {
          console.log(res, "0000");
          wx.showModal({
            showCancel: false,
            content: '提交成功',
            success() {
              // wx.switchTab({
              //   url: '/pages/index/index',
              // })
              wx.reLaunch({
                url: '/pages/faceRecognition/faceRecognition',
              })
            }
          })
        }
      }
    })
  },
  //获得当前登陆人的信息
  userInfo() {
    wx.request({
      url: app.globalData.publicUrl + '/applet/findUserInfo',
      method: "GET",
      header: {
        appletsId: wx.getStorageSync('openId')
      },
      success: (res) => {
        console.log(res.data.data, "000");
        this.data.parameter.forEach(item => {
          if (item.name == res.data.data.sex) {
            item.checked = true;
          }
        })
        //赋值问题 
        let jonIndex = this.data.postList.findIndex(item => {
          return item.name == res.data.data.job
        })
        if (jonIndex != -1) {
          this.setData({
            posttext: '',
            postindex: jonIndex,
          })
        } else {
          this.setData({
            posttext: '请选择',
          })
        }
        let incomeindex = this.data.incomeList.findIndex(item => {
          return item.name == res.data.data.income
        })
        if (incomeindex != -1) {
          this.setData({
            incometext: '',
            incomeindex: incomeindex,
          })
        } else {
          this.setData({
            incometext: '请选择',
          })
        }
        let educationindex = this.data.educationList.findIndex(item => {
          return item.name == res.data.data.education
        })
        if (educationindex != -1) {
          this.setData({
            educationtext: '',
            educationindex: educationindex,
          })
        } else {
          this.setData({
            educationtext: '请选择',
          })
        }
        this.setData({
          userName: res.data.data.userName,
          parameter: this.data.parameter,
          idCardNumber: res.data.data.idCardNumber,
          age: res.data.data.age,
          // posttext: res.data.data.job,
          // incometext: res.data.data.income,
          // educationtext: res.data.data.education,
        })
        console.log(this.data.postList, "赋值上了么");

      }
    })
  },
  onLoad: function () {
    this.initValidate();
    this.userInfo();
  },
})