// pages/jigouRegistered/jigouRegistered.js
import Notify from '../../dist/notify/notify';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name:'',
    mobile: '',
    isOrganization: false,
    organizationTitle: '',
    legalPerson: '',
    organizationContact: '',
    showRule:false,//弹出机构认证须知
    fileList: [],
    fileList1: [],
    fileList2: [],
    fileList3: [],
    uploadPic: false,//展示上传素材部分
    upload:0,
   
    cli:0,
    content:'',
    legalPersonImgage1:'',
    legalPersonImgage2: '',
    licensenImgage:'',
    otherImgage:'',
    latitude:'',
    longitude:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var config = wx.getStorageSync('config');
    if (config.registed == true && config.unionId !== undefined) {
      //跳转到首页
      wx.switchTab({
        url: '../index/index',
      });
    } else {
      setTimeout(function () {
        config = wx.getStorageSync('config');
        if (config.registed == true && config.unionId !== undefined) {
          //跳转到首页
          wx.switchTab({
            url: '../index/index',
          });
        }
      }, 1000);
    }
    

    //获取机构注册说明文本
    var x=this;
    wx.request({
      url: app.url + 'ajax_get_organization_rule_text.php',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.status == 'OK') {
          x.setData({
            content: res.data.result
          })
        }
      }
    })
    
  },

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

  //获取用户的输入值[姓名]
  onChangeName(e) {
    // event.detail 为当前输入的值
    this.setData({
      name:e.detail
    })
  },

  //获取用户的输入值[法人姓名]
  onChangeLegalPerson(e) {
    // event.detail 为当前输入的值
    this.setData({
      name: e.detail
    })
  },

  //获取用户的输入值[手机号码]
  onChangeMobile(e) {
    // event.detail 为当前输入的值
    this.setData({
      mobile: e.detail
    })
  },

  //机构认证checkbox勾选或者取消勾选
  onChangeIsOrganization(event) {
    this.setData({
      isOrganization: event.detail
    });
    if (this.data.isOrganization==false){
      //隐藏图片上传区
      this.setData({
        uploadPic:0
      })
    }
    if(this.data.cli==1){
      if (this.data.isOrganization == true) {
        this.setData({
          uploadPic: 1
        })
      }
    }
  },

  //获取用户的输入值[机构名称]
  onChangeOrganizationTitle(e) {
    // event.detail 为当前输入的值
    this.setData({
      organizationTitle: e.detail
    })
  },

  //获取用户的输入值[法人姓名]
  onChangeLegalPerson(e) {
    // event.detail 为当前输入的值
    this.setData({
      legalPerson: e.detail
    })
  },

  //获取用户的输入值[法人手机]
  onChangeOrganizationContact(e) {
    // event.detail 为当前输入的值
    this.setData({
      organizationContact: e.detail
    })
  },
  surejigou(){
    this.setData({
      show:1,
      checked:true
    })
  },

  //提交注册资料
  regist(e){
    var that = this;
    //姓名必须输入
    if (that.data.name == null || that.data.name.trim()=="") {
      Notify('请输入姓名')
      return
    }

    //手机号码必须输入
    if (that.data.mobile == null || that.data.mobile.trim() == "") {
      Notify('请输入手机号码')
      return
    }
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(that.data.mobile)) {
      Notify("手机格式错误");
      return false;
    }

    var config = wx.getStorageSync('config');
    var location = wx.getStorageSync('location');
    // 获取用户信息
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
        //机构注册
        if (that.data.isOrganization == true) {
          //机构名称必须输入
          if (that.data.organizationTitle == null || that.data.organizationTitle.trim() == "") {
            Notify('请输入机构名称')
            return
          }
          //法人行密名必须输入
          if (that.data.legalPerson == null || that.data.legalPerson.trim() == "") {
            Notify('请输入法人姓名')
            return
          } 
          //法人行密名必须输入
          if (that.data.organizationContact == null || that.data.organizationContact.trim() == "") {
            Notify('请输入法人手机')
            return
          } 
          wx.request({
            url: app.url + 'ajax_get_unionid.php',
            data: {
              openid: config.openId,
              iv: res.iv,
              encryptedData: res.encryptedData

            },
            success(resp) {
              if (resp.data.status == 'OK') {
                wx.request({
                  url: app.url + 'ajax_social_user_register1.php',
                  data: {
                    unionId: resp.data.result.unionId,
                    openId: config.openId,
                    name: that.data.name,
                    mobile: that.data.mobile,
                    legalPerson: that.data.legalPerson,
                    organizationContact: that.data.organizationContact,
                    headerImg: app.globalData.userInfo.avatarUrl,
                    longitude: location.longitude,
                    latitude: location.latitude
                  },
                  header: { 'content-type': 'application/json' },
                  method: 'GET',
                  dataType: 'json',
                  success: function (res) {
                    wx.showToast({
                      title: res.data.result.message,
                      icon: 'success',
                      duration: 2000
                    });
                    //注册成功以后,弹出机构认证对话框
                    that.setData({
                      showRule: true,
                      uploadPic: 1
                    })
                  },
                  fail: function (res) {
                    console.log(res, '失败')
                  },
                  complete: function (res) { },
                })
              }
            }
          });

        }

        //普通用户注册
        if (that.data.isOrganization == false) {
          wx.request({
            url: app.url + 'ajax_social_user_register1.php',
            data: {
              unionId: config.unionId,
              openId: config.openId,
              name: that.data.name,
              mobile: that.data.mobile,
              headerImg: app.globalData.userInfo.avatarUrl,
              longitude: location.longitude,
              latitude: location.latitude
            },
            header: { 'content-type': 'application/json' },
            method: 'GET',
            dataType: 'json',
            success: function (res) {
              wx.showToast({
                title: res.data.result.message,
                icon: 'success',
                duration: 2000
              });
              //跳转到年龄选择
              wx.navigateTo({
                url: '../ageChange/ageChange',
              });

            },
            fail: function (res) {
              console.log(res, '失败')
            },
            complete: function (res) { },
          })
        }
      }
    })
  },

  //上传的图片[法人身份证1]
  delete(event) {
    const { index, name } = event.detail;
    const fileList = this.data[`fileList`];
    fileList.splice(index, 1);
    this.setData({ [`fileList`]: fileList });
  },  
  afterRead(event) {
    const { file, name } = event.detail;
    const fileList = this.data[`fileList`];
    this.setData({ 
      [`fileList`]: fileList.concat(file),
      legalPersonImgage1:file[0].path
    });
  },
  //上传的图片[法人身份证2]
  delete1(event) {
    const { index, name } = event.detail;
    const fileList1 = this.data[`fileList1`];
    fileList1.splice(index, 1);
    this.setData({ [`fileList1`]: fileList1 });
  },
  afterRead1(event) {
    const { file, name } = event.detail;
    const fileList1 = this.data[`fileList1`];

    this.setData({
       [`fileList1`]: fileList1.concat(file),
      legalPersonImgage2:file[0].path
        });
  },

  //上传的图片[营业执照]
  delete2(event) {
    const { index, name } = event.detail;
    const fileList2 = this.data[`fileList2`];
    fileList2.splice(index, 1);
    this.setData({ [`fileList2`]: fileList2 });
  },
  afterRead2(event) {
    const { file, name } = event.detail;
    const fileList2 = this.data[`fileList2`];

    this.setData({
      [`fileList2`]: fileList2.concat(file),
      licensenImgage: file[0].path
        });
  },

  //上传的图片[其他]
  delete3(event) {
    const { index, name } = event.detail;
    const fileList3 = this.data[`fileList3`];
    fileList3.splice(index, 1);
    this.setData({ [`fileList3`]: fileList3 });
  },
  afterRead3(event) {
    const { file, name } = event.detail;
    const fileList3 = this.data[`fileList3`];

    this.setData({
       [`fileList3`]: fileList3.concat(file),
      otherImgage: file[0].path 
       });
  },

  // 同意认证机构
  agree() {
    this.setData({
      showRule: false,
      upload: true
    })
  },

  //机构注册上传各种证明
  upload(){
    var recommend=true;
    var config = wx.getStorageSync('config');
    var that = this;
    //循环上传图片
    var uploadLegalPersonImgage1Complete = true;
    if (that.data.legalPersonImgage1 != null && that.data.legalPersonImgage1 != "") {
      uploadLegalPersonImgage1Complete = false;
      wx.uploadFile({
        url: app.url + 'ajax_social_user_register2.php?unionId=' + config.unionId + "&openId=" + config.openId,
        filePath: that.data.legalPersonImgage1,
        name: 'legalPersonImgage1',
        header: { 'content-type': 'multipart/form-data' },
        success: function (res) {
        },
        fail: function (res) {
          console.log(res, '上传失败')
        },
        complete: function (res) {
          uploadLegalPersonImgage1Complete = true;
        },
      })
    }

    //身份证反面
    var uploadLegalPersonImgage2Complete = true;
    if (that.data.legalPersonImgage2 != null && that.data.legalPersonImgage2 != "") {
      uploadLegalPersonImgage2Complete = false;
      wx.uploadFile({
        url: app.url + 'ajax_social_user_register2.php?unionId=' + config.unionId + "&openId=" + config.openId,
        filePath: that.data.legalPersonImgage2,
        name: 'legalPersonImgage2',
        header: { 'content-type': 'multipart/form-data' },
        success: function (res) {
        },
        fail: function (res) {
          console.log(res, '上传失败')
        },
        complete: function (res) {
          uploadLegalPersonImgage2Complete = true;
        },
      })
    }

    //营业执照
    var uploadLicensenImgageComplete = true;
    if (that.data.licensenImgage != null && that.data.licensenImgage != "") {
      uploadLicensenImgageComplete = false;
      wx.uploadFile({
        url: app.url + 'ajax_social_user_register2.php?unionId=' + config.unionId + "&openId=" + config.openId,
        filePath: that.data.licensenImgage,
        name: 'licensenImgage',
        header: { 'content-type': 'multipart/form-data' },
        success: function (res) {
        },
        fail: function (res) {
          console.log(res, '上传失败')
        },
        complete: function (res) {
          uploadLicensenImgageComplete = true;
        },
      })
    }
    //其他图片
    var uploadOtherImgageComplete = true;
    if (that.data.otherImgage != null && that.data.otherImgage != "") {
      uploadOtherImgageComplete = false;
      wx.uploadFile({
        url: app.url + 'ajax_social_user_register2.php?unionId=' + config.unionId + "&openId=" + config.openId,
        filePath: that.data.otherImgage,
        name: 'otherImgage',
        header: { 'content-type': 'multipart/form-data' },
        success: function (res) {
        },
        fail: function (res) {
          console.log(res, '上传失败')
        },
        complete: function (res) {
          uploadOtherImgageComplete = true;
        },
      })
    }

    //等待所有上传完成
    var a = setInterval(function () {
      //循环执行代码 
      if (uploadLegalPersonImgage1Complete && uploadLegalPersonImgage2Complete && uploadLicensenImgageComplete && uploadOtherImgageComplete) {
        //跳转到首页
        wx.showToast({
          title: '上传成功,请等待审核!',
          icon: 'success',
          duration: 2000
        });
        clearInterval(a)
        
        //跳转到年龄选择
        wx.navigateTo({
          url: '../ageChange/ageChange',
        });

      }

    }, 1000) //循环时间 这里是1秒
  },

  //判断上传的图片类型
  beforeRead(event) {
    const { file, callback } = event.detail;
    if (file[0].path.indexOf('jpg') < 0) {
      wx.showToast({ title: '请选择jpg图片上传', icon: 'none' });
      callback(false);
      return;
    }
    callback(true);
  }
})