// pages/login/login.js
const app = getApp()
import {
  wechatMobileLogin
} from "../../../api/login.js"
import {auth} from "../../../api/index.js"
import {throttle} from "../../../utils/util"
let urlHost=app.hostConfig().agreehost;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    check: 0,
    beforeClose(action){
    return new Promise((resolve) => {
      if (action === 'confirm') {
        resolve(true);
      } else {
        // 拦截取消操作
        resolve(false);
      }
  })
},
    showEntryTip:false,
    showEntryTip_second:false,
    redirecUrl:'',
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static'

  },
  handleAgree(){
    if(!this.data.check){
      wx.showToast({
        title: '请同意《肝胆相照用户服务协议》!',
        icon:'none'
      })
      return false
    };
  },

  onConfirmEntry(){
    this.setData({
      showEntryTip:false
    })
    //wx.setStorageSync('hasEntry', true);
  },
  onCloseEntry(){
    this.setData({
       showEntryTip:true,
      showEntryTip_second:true
    })
  },
  onConfirmEntry_second(){
    this.setData({
      showEntryTip_second:false,
    });
    //wx.setStorageSync('hasEntry', true);
   
  },
  onCloseEntry_second(){
     wx.exitMiniProgram({success: (res) => {}})
     this.setData({
      showEntryTip_second:false,
      showEntryTip:false,
    });
    
   },
  getPhoneNumber:throttle(function(e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok'){
        // if(!e.detail.code){
        //   wx.showToast({
        //     title: '当前微信版本过低,可能部分功能受影响',
        //     icon:'none'
        //   })
        //   return false
        // };
         auth().then(res => {
        wechatMobileLogin({
          phone_code: e.detail.code,
          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{
            wx.reLaunch({
              url:url
            })
          } 
           app.imLogin({path:'pages/login/login'},handleGo);
    
        })
      });
    }else if(e.detail.errMsg == 'getPhoneNumber:fail user deny'){
      console.log('您拒绝手机号授权')
    }else{
      wx.showToast({
        title: '手机号授权失败',
        icon:'none'
      })
    }
  }),
  goMobile(){
    let url='/patient/pages/mobileLogin/mobileLogin'; 
    let redirectUrl=this.data.redirectUrl?this.data.redirectUrl:'/pages/index/index';
    // console.log('222222');
    // console.log(redirectUrl)
    app.method.navigateTo({
      url: url+"?redirectUrl="+encodeURIComponent(redirectUrl)
    })
  },
  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)
    })
  }),
  checkboxChange(e) {
    this.setData({
      check: e.detail.value.length
    })

  },
  getRedirect(urlParams){
  
    let url=decodeURIComponent(urlParams);
    let index=url.indexOf("redirectUrl=");
    let cur_url=''
    if(index!=-1){
      cur_url=url.substring(index+12,index.length);
     // console.log(cur_url)
      this.getRedirect(cur_url);
    }else{
      cur_url=url;
    }   
    return decodeURIComponent(cur_url); 
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      beforeClose: this.data.beforeClose.bind(this),
  })
    if(options.redirectUrl){ 
      this.setData({
        redirectUrl:"/"+this.getRedirect(options.redirectUrl)
      })
    }
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      img_host:app.hostConfig().imghost
    });
    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() {

  },

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

  },

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

  },

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