// pages/mobileLogin/mobileLogin.js
import { mobileLogin, phoneCode} from "../../../api/login.js"
const app = getApp();
import {
  auth
} from "../../../api/index.js"
import {throttle} from "../../../utils/util"
let urlHost=app.hostConfig().agreehost;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
   check:0,
   code:'',
   disabled:true,
   isActive:false,
   codeActive:true,
   phone:'',
   redirecUrl:'',
   timer:null,
   time:59,
   msg:'获取验证码',
   img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static'
  },
  checkboxChange(e) {
    this.setData({
      check:e.detail.value.length
    })
  
  },
  getUserInfo(event) {
    this.handlelogin();
  },
  onClose() {
    this.setData({ show: false });
  },
  handleThrottle:throttle(function(){
    this.getCode()
  }),
  getCode(){
    if(!/^1[3456789]\d{9}$/.test(this.data.phone)){
      wx.showToast({
        title: `请输入有效的手机号码！`,
        icon: 'none',
      });
      return false;    
    };
    phoneCode({
      phone:this.data.phone,
      scene:1
    }).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
      })
  
    });
    
  },
  goLogin(){
    let THIS=this;
    if(!this.data.check){
      wx.showToast({
        title: '请同意《肝胆相照用户服务协议》!',
        icon:'none'
      })
      return false
    };
    if(!/^1[3456789]\d{9}$/.test(this.data.phone)){
      wx.showToast({
        title: `请输入有效的手机号码！`,
        icon: 'none',
      });
      return false;    
    };
    if(!this.data.code){
      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 {code,phone }=this.data;
    auth().then(res => {
      mobileLogin({
        code:code,
        phone:phone,
        user_type:1,
        wx_code:res
      }).then((data)=>{
        const { envVersion } = wx.getAccountInfoSync().miniProgram;
        if(envVersion=='release'){
             wx.setStorageSync('AUTH_TOKEN', data.token);
        }else{
             wx.setStorageSync('DEV_AUTH_TOKEN', data.token); 
        }
         wx.setStorageSync('CLIENT_USER_ID',data.client_user_id);
         wx.setStorageSync('USER_ID',data.user_id);
        let url=this.data.redirectUrl?this.data.redirectUrl:'/pages/index/index';
        let handleGO=null;
        if(url.indexOf('login')!=-1 || url.indexOf('mobileLogin')!=-1 ){
          handleGO=function(){
            wx.reLaunch({
              url:'/pages/index/index'
            })
          }
         
         }else{
          handleGO=function(){
            wx.reLaunch({
              url:url
            })
          }
        }
         app.imLogin({path:'pages/mobileLogin/mobileLogin'},1,handleGO);
    
      })
    });
  }),
  goAgreement:throttle(function(event){
    let id=event.currentTarget.dataset.id;
    app.method.navigateTo({
      url:"/patient/pages/linkPage/linkPage?url="+encodeURIComponent(urlHost+'/basic/file/agreement.htm?id='+id)
    })
  }),
  inputChange(e){
    this.setData({
      [e.target.dataset.id]: e.detail.value
  });
    if(e.target.dataset.id=="code"){
      if(e.detail.value.trim()){
          this.setData({
            disabled: false
        });
      }else{
        this.setData({
          disabled: true
      });
      }
       
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log("redirectUrl-----------");
    //console.log(options.redirectUrl)
    if(options.redirectUrl){
      this.setData({
        redirectUrl:decodeURIComponent(options.redirectUrl)
      })
    };
   
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      img_host:app.hostConfig().imghost
    });
  },

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

  },

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

  },

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

  },

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

  },

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