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

Page({
  data: {
    userInfo: {},
    mobile: '',
    captcha: '', //验证码
    code: '', //小程序登录code
    isUat: false,
    isPro: true,
    isJms: false,
    jmsMobile: '',
    jmsCaptcha: '',
    loginType: '' ,//0 全部显示 1：显示体验版 2：显示加盟商 
    disabled:false,//控制获取验证码按钮是否禁用
   countdown:'获取验证码',
   timer:null//用于保存定时器
  },

  onShareAppMessage: function () {
    let that = this;
    //获取分享id 用来追踪链接
    //引荐人和非引荐人的 链接不同 
    var path = '/pages/index/index';
    if (that.data.loginType)
      path = '/pages/index/index?type=' + that.data.loginType;
    return {
      title: "鲸致生活-服务者小程序",
      path: path,
      imageUrl: '/static/images/logo.png'
    }
  },
  onLoad(options) {
		
	
    //1 体验版 2加盟商兼职
    let loginType = options.type;
    if (!loginType)
      loginType = wx.getStorageSync('loginType');
    console.info(loginType);

    if (loginType) {
      this.setData({
        loginType: loginType
      })
      wx.setStorageSync('loginType', loginType);
      if (loginType == 2) {
        this.setData({
          isJms: true,
          isUat: false,
          isPro: false
        })
      } else if (loginType == 1) {
        this.setData({
          isJms: false,
          isUat: true,
          isPro: false
        })
      }
      console.info(loginType)
    }

    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.type == 1) return; //小哥登录 不验证地理位置
    this.getLoginCode();
    // map.getCity().then(res => {}).catch(res => {
    //   if (res == 3) {
    //     wx.showModal({
    //       title: '提醒',
    //       showCancel: false,
    //       content: '当前区域，无服务门店'
    //     })
    //   } else {
    //     wx.showModal({
    //       title: '提醒',
    //       showCancel: false,
    //       content: '您未授权，部分功能将受限'
    //     })

    //   }
    // })
  },
  onUatChange(e) { //是否体验版
    console.info(e);
    this.setData({
      isUat: true,
      isPro: false,
      isJms: false,
    });
    // this.setData({
    //   isUat: e.detail,
    // 	isPro:!e.detail,
    // 	isJms:!e.detail,
    // }); 
    console.log('uat....', e.detail);
  },
  onProChange(e) {
    this.setData({
      isPro: true,
      isUat: false,
      isJms: false,
    });

    // this.setData({
    //   isPro: e.detail,
    // 	isUat:!e.detail,
    // 	isJms:!e.detail,
    // }); 
  },
  onJmsChange(e) {
    this.setData({
      isPro: false,
      isUat: false,
      isJms: true,
    });
    // this.setData({
    //   isPro: !e.detail,
    // 	isUat:!e.detail,
    // 	isJms:e.detail,
    // }); 

  },
  goShelter() {
    wx.navigateTo({
      url: '/pages/shelter/index',
    })
  },
  onShow() {
    let that = this;
    //验证是否登陆过
    user.checkLogin().then(res => {
      app.globalData.hasLogin = true;
      let userInfo = wx.getStorageSync('userInfo');
      if (userInfo.isPartJob === true) {
        // 兼职人员
        wx.redirectTo({
          url: '/pages/temp/serviceOrder/serviceOrder',
        })
      } else {
        wx.switchTab({
          url: '/pages/new/serviceOrder/serviceOrder',
          success: function (e) {
            var page = getCurrentPages().pop();
            if (page == undefined || page == null) return;
            page.onLoad();
          }
        })
      }


    }).catch(res => {
      that.getLoginCode();
    })
  },
  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
		 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;
    }
    var that = this;
		//------执行Login--------- 
		util.request(api.AuthLoginByCaptcha, {
			mobile: that.data.mobile,
			captcha: that.data.captcha,
			// userInfo: res.userInfo,
			code: that.data.code
		}, 'POST').then(function (res) {
    // 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);
    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;
    }
    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,{
								phoneNumber: that.data.mobile
							}, "GET").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,
              icon:'none',
              duration: 3000
            });
          }
        }).catch(res => {

        })
      }
    })
  },
  // 开始倒计时的函数
  startCountdown: function() {
    let that = this;
    let countdown = 60; // 设置倒计时时间
    that.setData({
      countdown: countdown + '秒后重试',
      disabled:true
    });
    that.data.timer = setInterval(() => {
      countdown--;
      if (countdown <= 0) {
        clearInterval(that.data.timer); // 清除定时器
        that.setData({
          countdown: '获取验证码',
          timer: null,
          disabled:false
        });
      } else {
        that.setData({
          countdown: countdown + '秒后重试',
        });
      }
    }, 1000);
  },
  getCaptcha() {
    const that=this
    if (this.data.mobile.length != 11 || this.data.mobile.startsWith("1") == false) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none',
        duration: 3000
      });
      return;
    }
    console.info(api.AuthCaptcha)
    util.request(api.AuthCaptcha, {
      mobile: this.data.mobile
    }, "POST").then(res => {
      if (res.errno == 0){
        wx.showToast({
          title: '验证码发送成功',
          duration: 3000
        }); 
       that.startCountdown()
      }   
      else
        wx.showToast({
          title: res.errmsg,
          duration: 3000
        });
    }).catch(res => {
      console.info('getCaptcha error')
      wx.showToast({
        title: res.errMsg,
        icon: 'error',
        duration: 3000
      });
    })

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

  },
  bindcaptchaInput(e) {
    this.setData({
      captcha: e.detail.value
    });
  },
  goInvite() {
    wx.navigateTo({
      url: '/pages/upgrade/invite/invite',
    })
  },
  goTemp() {
    wx.navigateTo({
      url: '/pages/temp/login/login',
    });
  },
  bindJmsMobileInput(e) {
    this.setData({
      jmsMobile: e.detail.value
    });

  },
  bindJmsCaptchaInput(e) {
    this.setData({
      jmsCaptcha: e.detail.value
    });
  },
  getJmsCaptcha() {
    const that =this
    if (this.data.jmsMobile.length != 11 || this.data.jmsMobile.startsWith("1") == false) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none',
        duration: 3000
      });
      return;
    }
    jmsUtil.request(jms.SendLoginCode, {
      tel: this.data.jmsMobile
    }, "POST").then(res => {
      if (res.errno == 0){
         wx.showToast({
          title: '验证码发送成功',
          duration: 3000
        });
        that.startCountdown();
      }
       
      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.jmsMobile.length != 11 || this.data.jmsMobile.startsWith("1") == false) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none',
        duration: 3000
      });
      return;
    } else if (this.data.jmsCaptcha == '') {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 3000
      });
      return;
    } else {
      //登录
      jmsUtil.request(jms.PartJobLogin, {
        tel: this.data.jmsMobile,
        verifyCode: this.data.jmsCaptcha,

      }, "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 => {

      })
    }
  },
  bindJmsMobileInput(e) {
    this.setData({
      jmsMobile: e.detail.value
    });

  },
  bindJmsCaptchaInput(e) {
    this.setData({
      jmsCaptcha: e.detail.value
    });
  },
  goRegister() {
    wx.navigateTo({
      url: '/pages/temp/register/register',
    })
  },
  checkProBtn() {
    wx.navigateTo({
      url: '/pages/temp/jzxhAppletsUserPro/jzxhAppletsUserPro'
    })
	},
	chooseLogin(){
		this.setData({
			isJms:!this.data.isJms
		})
		
	}
})