// index.js
// 获取应用实例
const app = getApp()
const util = require('../../../utils/jmsUtil.js');
const user = require('../../../utils/user.js');
const api = require('../../../api/jms.js');


Page({
  data: {
		isChecked:false,
    userInfo: {},
    mobile: '',
    captcha: '', //验证码
    code: '', //小程序登录code
    isUat: false,
    isPro:true
  },
  onLoad() {  
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.type == 1) {
			
		}
  
  },
  onUatChange(e) { //是否体验版
    console.info(e);
    this.setData({
      isUat: e.detail,
      isPro:!e.detail,
    }); 
    console.log('uat....',e.detail); 
  },
  onProChange(e){
    this.setData({
      isPro: e.detail,
      isUat:!e.detail
    }); 
  },
  goShelter() {
    wx.navigateTo({
      url: '/pages/shelter/index',
    })
  },
  onShow() {
    let that = this;
    //验证是否登陆过
    user.checkLogin().then(res => {
			app.globalData.hasLogin = true;
			wx.redirectTo({
				url: '/pages/temp/serviceOrder/serviceOrder',
			});
 

    }).catch(res => {
      
    })
  },
  getLoginCode() {
    let that = this;
    user.login().then(res => {
      console.info(res)
      that.setData({
        code: res.code
      })
    })
  },
  getPhoneNumber: function (e) { 
    wx.setStorageSync('isUat', false);
    var ivObj = e.detail.iv
    var telObj = e.detail.encryptedData
    var that = this;
    //------执行Login--------- 
    util.request(api.AuthRegister, {
      code: that.data.code,
      encryptedData: telObj,
      iv: ivObj,
      loginType: 1

    }, 'POST').then(function (res) {
      console.info(res)
      if (res.errno === 0) {
        //存储用户信息  
        console.info("登录成功2")
        app.globalData.hasLogin = true;
        wx.setStorageSync('userInfo', res.data.userInfo);
        wx.setStorageSync('token', res.data.token);
        that.setData({
          mobile: res.data.mobile
        })
        wx.showToast({
          title: '授权注册成功',
          icon: 'success',
          duration: 2000,
          complete: function () {
            //   if(res.data.userInfo.type==1)
            //   wx.navigateTo({
            //     url: '/pages/pre/index',
            //   })
            //  else 
            // wx.navigateTo({
            //   url: '/pages/servant/servant',
            // }) 

            wx.switchTab({
              url: '/pages/new/serviceOrder/serviceOrder',
              success: function (e) {
                var page = getCurrentPages().pop();
                if (page == undefined || page == null) return;
                page.onLoad();
              }
            })


          }
        })
      } else {
        console.info(res);
        that.getLoginCode();
        wx.showToast({
          title: res.errmsg,
          duration: 3000,
          icon: 'none'
        });
      }
    });

    //-----------------是否授权，授权通过进入主页面，授权拒绝则停留在登陆界面
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { //用户点击拒绝 
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，功能无法使用!!!',
        showCancel: false,
        confirmText: '确定',
        success: function (res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/index/index',
              success: function (e) {
                var page = getCurrentPages().pop();
                if (page == undefined || page == null) return;
                page.onLoad();
              }
            })
          };
        }
      })
    }
  },
  /**
   * 如果勾选了体验版 流程如下
   * 1，先用手机号和验证码 去正式库验证通过
   * 2，将api.WxApiRoot修改为体验测试版本的WxApiRoot_Uat
   * 3，再次提交验证 将输入手机号修改为体验指定的手机号，完成登录
   * @param {*} e 
   */
  getUserProfile(e) {
    wx.setStorageSync('isUat', true);
    let that = this
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        //登录
        util.request(api.AuthLoginByCaptcha, {
          mobile: that.data.mobile,
          captcha: that.data.captcha,
          userInfo: res.userInfo,
          code: that.data.code
        }, "POST").then(res => {
            //存储用户信息  
            console.info("登录成功")
          if (res.errno == 0) {
            //如果是uat版 再次验证登录
            if (that.data.isUat) {
              console.info('uat')
              //替换链接
              api.WxApiRoot=api.WxApiRoot_Uat;
              util.request(api.AuthLoginUat).then(ress => {
                app.globalData.hasLogin = true; 
                wx.setStorageSync('userInfo', ress.data.userInfo);
                wx.setStorageSync('token', ress.data.token);
                console.info(wx.getStorageSync('token'))
                that.setData({
                  mobile: ress.data.mobile
                });
                wx.showToast({
                  title: '授权注册成功',
                  icon: 'success',
                  duration: 2000,
                  complete: function () {
                    wx.switchTab({
                      url: '/pages/new/serviceOrder/serviceOrder',
                      success: function (e) {
                        var page = getCurrentPages().pop();
                        if (page == undefined || page == null) return;
                        page.onLoad();
                      }
                    })
                  }
                })

              })
            } else {
              console.info('not uat')
              app.globalData.hasLogin = true;
              wx.setStorageSync('userInfo', res.data.userInfo);
              wx.setStorageSync('token', res.data.token);
              that.setData({
                mobile: res.data.mobile
              });
              wx.showToast({
                title: '授权注册成功',
                icon: 'success',
                duration: 2000,
                complete: function () {
                  wx.switchTab({
                    url: '/pages/new/serviceOrder/serviceOrder',
                    success: function (e) {
                      var page = getCurrentPages().pop();
                      if (page == undefined || page == null) return;
                      page.onLoad();
                    }
                  })
                }
              })
            }  
          
          } else {  
             util.showErrorToast(res.errmsg); 
            // wx.showToast({
            //   title: res.errmsg,
            //   duration: 3000
            // });
          }
        }).catch(res => {

        })
      }
    })
  },
  getCaptcha() { 
    if (this.data.mobile.length != 11 || this.data.mobile.startsWith("1") == false) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none',
        duration: 3000
      });
      return;
    }
    util.request(api.SendLoginCode, {
      tel: this.data.mobile
    }, "POST").then(res => {
      if (res.errno == 0)
        wx.showToast({
          title: '验证码发送成功',
          duration: 3000
        });
      else
        wx.showToast({
          title: res.errmsg,
					duration: 3000,
					icon:'none'
        });
    }).catch(res => {
      console.info('getCaptcha error')
      wx.showToast({
        title: res.errmsg,
				icon:'none',
        duration: 3000
      });
    })

	},
	loginTemp(){
		if (this.data.mobile.length != 11 || this.data.mobile.startsWith("1") == false) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none',
        duration: 3000
      });
      return;
    }else if(this.data.captcha==''){
			wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 3000
      });
      return;
		}else{
			      //登录
						util.request(api.PartJobLogin, {
							tel: this.data.mobile,
							verifyCode: this.data.captcha,
						
						}, "POST").then(res => {
								//存储用户信息  
								console.info("登录成功")
							if (res.errno == 0) {
									 app.globalData.hasLogin = true; 
									 let user= res.data.user;
									 user.isPartJob=res.data.isPartJob;
										wx.setStorageSync('userInfo', user);
										wx.setStorageSync('token', res.data.token);
									wx.redirectTo({
										url: '/pages/temp/serviceOrder/serviceOrder',
									});
								
									
							
							}else if(res.errno === 301)
							{
								wx.showModal({
									title: '提示',
									content: '您还未注册，是否现在去注册？',
									// showCancel:false,
									complete: (res) => {
										if (res.cancel) {
											
										}
								
										if (res.confirm) {
										wx.navigateTo({
											url: '/pages/temp/register/register',
										})
										}
									}
								})
							} else {  
								//  util.showErrorToast(res.errmsg); 
								wx.showToast({
									title: res.errmsg,
									icon:'none',
									duration: 3000
								});
							
							}
						}).catch(err => {
		
						})




			
		}
	},
  bindMobileInput(e) { 
    this.setData({
      mobile: e.detail.value
    });

  },
  bindcaptchaInput(e) {
    this.setData({
      captcha: e.detail.value
    });
  },
  goRegister() {
    wx.navigateTo({
      url: '/pages/temp/register/register',
    })
	},
	checkProBtn(){
		wx.navigateTo({
      url: '/pages/temp/jzxhAppletsUserPro/jzxhAppletsUserPro'
    })
	},
	checkChange(e){
		this.setData({
      isChecked: e.detail,
    });
	}
})