// pages/mobileLogin/mobileLogin.js
import { smsLogin, sendSms,getCaptcha,phoneLogin} from "../../../api/api"
const app = getApp();
import {auth} from "../../../api/auth.js"
import {throttle} from "../../../utils/util"
import {base64src} from "../../../utils/base64ToImg"
let urlHost=app.hostConfig().agreehost;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showSuccess:false,
    showEntryTip:false,
    showEntryTip_second:false,
    show: false,
   check:false,
   sms:'',
   message:'',
   disabled:true,
   isActive:false,
   codeActive:true,
   imgCode:'',
   mobile:'',
   redirecUrl:'',
   timer:null,
   time:59,
   msg:'获取验证码',
   captchaUuid:'',
   captchaCode:'',
   loginDevice:5,
   smsType:2,
   img_host:app.hostConfig().imghost
  },
  onConfirmEntry(){
    this.setData({
      showEntryTip:false
    })
    //wx.setStorageSync('hasEntry', true);
  },
  onCloseEntry(){
    this.setData({
       showEntryTip:true,
      showEntryTip_second:true
    })
  },
  onConfirmEntry_second(){
    this.setData({
      showEntryTip_second:false,
    });
   
  },
  onCloseEntry_second(){
     wx.exitMiniProgram({success: (res) => {}})
     this.setData({
      showEntryTip_second:false,
      showEntryTip:false,
    });
    
   },
  onConfirmSuccess(){
    this.setData({
        showSuccess:false
    })
  },
  onCancelSuccess(){
    this.setData({
        showSuccess:false
    })
  },
  checkboxChange(e) {
    this.setData({
      check:e.detail
    })
  
  },
  getPhoneNumber:throttle(function(e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok'){
         auth().then(res => {
        phoneLogin('wx415cbcf96f4a3b27',{
            code:e.detail.code
        }).then((data)=>{
            const { envVersion } = wx.getAccountInfoSync().miniProgram;
            let token=''
            if(envVersion=="develop" || envVersion=="trial"){
                token="DEV_CASE_TOKEN"
            }else{
                token="PROD_CASE_TOKEN"
            }
           wx.setStorageSync(token, data.token);
          let url=this.data.redirectUrl?this.data.redirectUrl:'/pages/index/index';
        
          if(url.indexOf('login')!=-1 || url.indexOf('mobileLogin')!=-1){
            wx.reLaunch({
                url:'/pages/index/index'
            })
          }else{
            wx.reLaunch({
              url:url
            })
          } 
        }).catch(error=>{
            if(error.code==10007){
            console.log(error.msg)
               this.setData({
                 showSuccess:true,
                 message:error.msg,
                 mobile:error.data
               })
            }
        })
      });
    }else if(e.detail.errMsg == 'getPhoneNumber:fail user deny'){
      console.log('您拒绝手机号授权')
    }else{
      wx.showToast({
        title: '手机号授权失败',
        icon:'none'
      })
    }
  }),
  onConfirmSuccess(){
    let {mobile}=this.data;
  this.setData({
      showSuccess:false
  })
  app.method.navigateTo({
      url:'/case/pages/improveInfo/improveInfo?mobile='+mobile
  })
},
onCancelSuccess(){
    this.setData({
        showSuccess:false
    })
  },
  handleAgree(){
    if(!this.data.check){
      wx.showToast({
        title: '请同意《用户服务协议》!',
        icon:'none'
      })
      return false
    };
  },
  getUserInfo(event) {
    this.handlelogin();
  },
  onClose() {
    this.setData({ show: false });
  },
  handleThrottle:throttle(function(){
    this.getCode()
  }),
  handleGetCaptcha(){
    getCaptcha().then(res=>{
        base64src(res.captchaBase64Image,(img)=>{
          this.setData({
            imgCode:img,
            captchaUuid:res.captchaUuid
          })
        })
    })
  },
  goPwdLogin:throttle(function(){
    app.method.navigateTo({
    url:'/case/pages/pwdLogin/pwdLogin'
    })
}),
  goRegister:throttle(function(){
    app.method.navigateTo({
    url:'/case/pages/register/register'
    })
}),
  getCode(){
      let {mobile,captchaCode,captchaUuid,loginDevice,smsType}=this.data;

    if(!/^1[3456789]\d{9}$/.test(mobile)){
      wx.showToast({
        title: `请输入有效的手机号码！`,
        icon: 'none',
      });
      return false;    
    };
    if(!captchaCode){
        wx.showToast({
            title: `图形验证码不能为空`,
            icon: 'none',
          });
          return false;   
      }
    sendSms({
      mobile,
      smsType,
      captchaCode,
      captchaUuid,
      loginDevice
    }).then((res)=>{
      let timer=setInterval(() => {
        if (this.data.time == 0) {   
          clearInterval(this.data.timer);
          this.setData({
            time:59,
            msg:'重新获取验证码',
            isActive:false,
            codeActive:true,
          })
        } else {
          let msg= this.data.time + " s 后重新发送";
          this.setData({
            isActive:true,
            msg:msg,
            codeActive:false,
          })
          let time=this.data.time--;
          this.setData({
           msg:time + " s 后重新发送"
          })
        }
      }, 1000);
  
      this.setData({
        timer:timer
      })
  
    }).catch(()=>{
        this.handleGetCaptcha();
    });
    
  },
  goLogin(){
    let THIS=this;
    if(!this.data.check){
      wx.showToast({
        title: '请同意《隐私协议》!',
        icon:'none'
      })
      return false
    };
    if(!/^1[3456789]\d{9}$/.test(this.data.mobile)){
      wx.showToast({
        title: `请输入有效的手机号码！`,
        icon: 'none',
      });
      return false;    
    };
    if(!this.data.sms){
      wx.showToast({
        title: `请输入验证码！`,
        icon: 'none',
      });
      return false;   
    }

   
    wx.getSetting({
      success(res) {
        // 判断它是否为true
        if (res.authSetting["scope.userInfo"]) {
          THIS.handlelogin();
        } else {
          THIS.setData({
            show:true
          })
        }
      }
    });
  },
  
  handlelogin:throttle(function(){
    let {sms,mobile }=this.data;
    smsLogin({
        sms:sms,
        mobile
      }).then((data)=>{
        const { envVersion } = wx.getAccountInfoSync().miniProgram;
        let token=''
        if(envVersion=="develop" || envVersion=="trial"){
            token="DEV_CASE_TOKEN"
        }else{
            token="PROD_CASE_TOKEN"
        }
       wx.setStorageSync(token, data.token);
        let url=this.data.redirectUrl?this.data.redirectUrl:'/pages/index/index';
        console.log(url)
        if(url.indexOf('login')!=-1 || url.indexOf('mobileLogin')!=-1 ){
            console.log(1)
            wx.reLaunch({
                url:'/pages/index/index'
              })
         
         }else{
            console.log(2)
            wx.reLaunch({
                url:url
              })
        }
      }).catch(error=>{
        if(error.code==10007){
            this.setData({
              showSuccess:true,
              message:error.msg,
              mobile:error.data
            })
         }else{
            this.handleGetCaptcha();
         }
      })
  }),
  goAgreement:throttle(function(event){
    app.method.navigateTo({
      url:"/case/pages/privacy/privacy"
    })
  }),
  inputChange(e){
    this.setData({
      [e.target.dataset.id]: e.detail.value
  });
    if(e.target.dataset.id=="sms"){
      if(e.detail.value.trim()){
          this.setData({
            disabled: false
        });
      }else{
        this.setData({
          disabled: true
      });
      }
       
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.handleGetCaptcha();
    if(options.redirectUrl){ 
      this.setData({
        redirectUrl:"/"+decodeURIComponent(options.redirectUrl)
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.getPrivacySetting({
        success: res => {
          console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            this.setData({
              showEntryTip:true
            })
          } else {
            this.setData({
              showEntryTip:false
            })
            // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私
          }
        },
        fail: () => {},
        complete: () => {}
      })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer);

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  
})