// pages/login/login.js
var app = getApp();
var getInvite = require("../../mybehaviors/getInvite/getInvite");
var int = app.globalData.statusBarHeight * 2 + 40;
const menuButtonObject = wx.getMenuButtonBoundingClientRect().height;
Page({
  behaviors: [getInvite],
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: int + menuButtonObject,
    yzredirect: "",
    logintap: false,
    // 平台协议
    PlatformAgreement: '',
    openPlatformAgreement: false,
    tapSelectAgreement: true,
    agreement_name: '平台协议',
    // end
    // 兼容登录
    canIUseGetUserProfile:false,
    showAutoBindPhone: false, // 首次授权登录自动绑定手机号(PS：新会员！！！首次)
    showChangeID: false,
    changidInfo: {
      uid: null,
      change_uid: null,
    },
    AuthorizedPhone: '',
    // 用户信息编辑
    is_show_user_info_edit_popup: false,
    user_info: {
      'nickName': '',
      'avatarUrl': '',
      'gender': ''
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.yzredirect = app.getyzredirect();
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }

    try {
      let showinfo = wx.getStorageSync("yz_basic_info");
      console.log(showinfo);
      this.setData({
        agreement_name: app._isTextEmpty(showinfo.home.register_setting.agreement_name) ? this.data.agreement_name : showinfo.home.register_setting.agreement_name,
        PlatformAgreement: showinfo.home.register_setting.new_agreement
      });
    } catch (error) {
      try {
        let showinfo = wx.getStorageSync("new_agreement");
        this.setData({
          agreement_name: app._isTextEmpty(showinfo.agreement_name) ? this.data.agreement_name : showinfo.agreement_name,
          PlatformAgreement: showinfo.new_agreement
        });
      } catch (error) {
        console.log(error);
      }
    }

  },
  PlatformAgreementTap() {
    this.setData({
      openPlatformAgreement: true
    });
  },
  PlatformAgreementClose() {
    this.setData({
      openPlatformAgreement: false
    });
  },
  PlatformAgreementOnChange(e) {
    this.setData({
      tapSelectAgreement: e.detail
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},


  /*************** 用户登录 START ***************************/
  getUserProfileTap() {
    let that = this;
    that.setData({
      is_show_user_info_edit_popup: true,
      lsgow: false
    });
    /* wx.getUserProfile({
       desc: '获取用户信息',
       success: function (_info) {
         that.setData({
           user_info:{
             'nickName': _info.userInfo.nickName,
             'avatarUrl': _info.userInfo.avatarUrl,
             'gender': _info.userInfo.gender
           },
           is_show_user_info_edit_popup: true
         });
         console.log('===== 获取用户信息 ======',that.user_info);
         // that.loginbtn(info);
       }
     });*/
  },
  loginbtn(_info) {
    if (this.data.logintap) return;
    this.setData({
      logintap: true
    });
    var that = this;
    console.log("=======  登录中...   ===============");
    wx.login({
      success: function (_json) {
        console.log("=========== login登录成功，获取用户info ==============",_json);
        if (_json.code) {
          // 请求登录接口
          wx.request({
            url: app.getNetAddresss("member.login.index"),
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
            },
            data: {
              code: _json.code,
              info: _info,
              ver: '2'
            },
            success: function (res) {
              var _data = res.data;
              console.log("登录接口", res);
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              if (_data.result == 1) {
                // 存储key
                if (_data.msg.session) {
                  wx.setStorageSync('session', _data.msg.session);
                }
                // wx.setStorage({
                // 	key: "session",
                // 	data: _data.msg.session
                // })
                wx.setStorage({
                  key: "openid",
                  data: _data.data.openid
                });
                if (_data.msg.wx_token) {
                  wx.setStorageSync('wx_token', _data.msg.wx_token);
                }
                // wx.setStorage({
                // 	key: "wx_token",
                // 	data: _data.msg.wx_token
                // })
                if (_info) {
                  wx.setStorageSync('userInfo', _info);
                }
                //that.globalData.uid = _data.msg.uid;
                wx.setStorage({
                  key: "yz_uid",
                  data: _data.msg.uid
                });

                if( _data.data.is_first_time_bind){
                  // 首次授权登录自动绑定手机号
                  that.setData({
                    showAutoBindPhone: true
                  });
                }else{
                  that.getInvite();
                }
                wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
              } else {
                wx.showModal({
                  title: '提示',
                  content: _data.msg,
                  success(res) {
                    console.log(res);
                  }
                });
                // wx.showToast({
                // 	title: _data.msg,
                // 	icon: 'loading',
                // 	duration: 2000,
                // 	mask: true,
                // })
                console.log("第三方登录数据错误" + res.errMsg);
              }
            },
            fail: function (res) {
              that.setData({
                logintap: false
              });
              console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
            }
          });
        } else {
          that.setData({
            logintap: false
          });
          console.log("获取用户登录态失败！" + res.errMsg);
        }
      },
      fail: function (res) {
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      },
    });
  },

/*  getUserProfileTap(e) {
    if(this.data.PlatformAgreement){
      if(!this.data.tapSelectAgreement){
        wx.showToast({
          title: '请勾选平台协议',
          duration:1000,
          icon:'none'
        });
        return;
      }
    }

    if (this.data.logintap) {
      // 正在请求 return
      console.log('正在请求');
      return;
    }
    this.setData({
      logintap: true
    });
    wx.showLoading({
      title: '登录中',
    });
    if(this.data.canIUseGetUserProfile){
      wx.getUserProfile({
        desc: '获取用户信息',
        success: (_info)=> {
          let info = {
            'nickName': _info.userInfo.nickName,
            'avatarUrl': _info.userInfo.avatarUrl,
            'gender': _info.userInfo.gender
          };
          console.log("info:", info);
          this.loginbtn(info);
        },fail:(err)=>{
          wx.hideLoading({
            success: (res) => {},
          });
        }
      });
    }else{
      let _info = e.detail;
      let info = {
        'nickName': _info.userInfo.nickName,
        'avatarUrl': _info.userInfo.avatarUrl,
        'gender': _info.userInfo.gender
      };
      console.log("info:兼容登录", info);
      this.loginbtn(info);
    }

  },
  loginbtn(_info) {
    console.log(this.data.logintap, '状态');
    var that = this;
    wx.login({
      success: (_json)=> {
        console.log(_info, _json.code,"login登录成功，获取用户info");
        if (_json.code) {
          // 请求登录接口
          wx.request({
            url: app.getNetAddresss("member.login.index"),
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
            },
            data: {
              code: _json.code,
              info: _info,
              ver: '2'
            },
            success: (res)=> {
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              var _data = res.data;
              console.log("登录接口", res);
              if (_data.result == 1) {
                try {
                  // 存储key
                  if (_data.data.user_info) {
                    wx.setStorageSync("nickname", _data.data.user_info.nickname);
                  }
                  if(_data.data.session){
                    wx.setStorageSync('session', _data.data.session);
                  }
                  if(_data.data.openid) {
                    wx.setStorageSync('openid', _data.data.openid);
                  }
                  if(_data.data.wx_token){
                    wx.setStorageSync('wx_token', _data.data.wx_token);
                  }
                  if(_info){
                    wx.setStorageSync('userInfo', _info);
                  }
                  if(_data.data.uid){
                    wx.setStorageSync('yz_uid', _data.data.uid);
                  }

                  wx.hideLoading();
                  if( _data.data.is_first_time_bind){
                    // 首次授权登录自动绑定手机号
                    that.setData({
                      showAutoBindPhone: true
                    });
                  }else{
                    that.getInviteData();
                  }

                  wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
                } catch (e) {
                  wx.reLaunch({
                    url: "/packageG/index/index",
                  });
                }

              } else {
                wx.hideLoading();
                wx.showModal({
                  title: '提示',
                  content: _data.msg,
                  success(res) {
                    console.log(res);
                    // if (res.confirm) {
                    // } else if (res.cancel) {
                    // }
                  }
                });
                console.log("第三方登录数据错误" + res.errMsg);
              }
            },
            fail: (res)=> {
              wx.hideLoading();
              wx.showToast({
                title: "第三方登录失败session、wx_token获取失败" + res.errMsg,
                duration:3000,
                icon:'none'
              });
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
            }
          });
        } else {
          this.setData({
            logintap: false
          });
          wx.showToast({
            title: "获取用户登录态失败！" + res.errMsg,
            duration:3000,
            icon:'none'
          });
          console.log("获取用户登录态失败！" + res.errMsg);
        }
      },
      fail: (res)=> {
        wx.hideLoading();
        this.setData({
          logintap: false
        });
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      }
    });
  },*/

  onChooseAvatar(e){
    const { avatarUrl } = e.detail
    let that = this;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.uploadFile({
      url: urlStr,
      filePath: avatarUrl,
      name: 'file',
      formData: null,
      success(resdata) {
        var res = JSON.parse(resdata.data);
        console.log(res.data.img_url);
        that.setData({
          avatar_image:res.data.img_url,
          'user_info.avatarUrl': res.data.img_url
        })
      }
    });
  },
  nicknameblur(e){
    let val = e.detail.value;
    console.log(e)
    this.setData({
      nickname: val,
      'user_info.nickName': val
    });
  },
  closeNickAvatar(){
    this.setData({
      is_show_user_info_edit_popup: false
    });
  },
  updateInfo() {
    let that = this;
    // 判断是否存在信息
    if(!that.data.user_info.avatarUrl){
      wx.showModal({
        title: "提示",
        content: '头像必须填写!',
        success(res) {},
      });
      return false;
    }
    // 用户信息存储
    that.setData({
      is_show_user_info_edit_popup: false
    },function(){
      that.loginbtn(that.data.user_info);
    });



  },

  /*************** 用户登录 END ***************************/
  getInviteData() {
    this.getInvite();
  },
  //是否开启邀请页面
  getInvite() {
    let urlStr = app.getNetAddresss("member.member.isValidatePage");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            this.checktoInvite(data);
          } catch (e) {
            wx.reLaunch({
              url: "/packageG/index/index",
            });
          }

        }
        wx.hideLoading();
      },
      fail: (res)=> {
        console.log(res);
      },
    });
  },
  //初始化语言设置
  initLanguage() {
    let urlStr = app.getNetAddresss("setting.get-lang-setting");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            wx.setStorageSync("mailLanguage", JSON.stringify(data));
          } catch (e) {
            console.log(e);
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  // behaviors有相同处理函数
  // gotourl() {
  //   try {
  //     if (!this.data.yzredirect) {
  //       this.gomember();
  //     } else {
  //       if (this.data.yzredirect.indexOf("login/login") > 0) {
  //         this.gomember();
  //       } else {
  //         wx.reLaunch({
  //           url: "/" + this.data.yzredirect,
  //           fail:function(err){
  //             // 防止跳转不了 尝试直接指向会员中心
  //             wx.reLaunch({
  //               url: '/packageG/member_v2/member_v2',
  //             });
  //           }
  //         });
  //       }
  //     }
  //   } catch (e) {
  //     wx.reLaunch({
  //       url: "/packageG/index/index",
  //     });
  //   }
  // },

  gomember() {
    wx.reLaunch({
      url: "/packageG/member_v2/member_v2",
    });
  },
  // 获取授权手机号
  async getPhoneNumber(e) {
    let info = e.detail;
    if(info.errMsg == 'getPhoneNumber:ok') {
      await this.getPhoneM(info);
      let keys = await this.getSessionKey(info);
      let mobile = await this.getPhone_index(info, keys);
      this.data.AuthorizedPhone = mobile;
      await this.getPrepBind(mobile);
      await this.setBindPhone();
      this.getInviteData();
    }else{
      this.getInviteData();
    }
  },
  getPhoneM() {
    return new Promise((resolve,reject) => {
      wx.checkSession({
        success: (res) => {
          console.log(res, 'checkSession');
          resolve();
        },
        fail:err => {
          reject(err);
        }
      });
    });
  },
  getSessionKey() {
    let key = wx.getStorageSync('session');
    console.log(key, '缓存的session');
    let urlStr = app.getNetAddresss('member.mini-decrypt.getSessionKey');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          session_key_id: key,
          not_validate_page: '0'
        },
        showToastIn: false,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res, '获取session_key');
            if (res.result == 1) {
              let keys = res.data.session_key_data.session_key;
              resolve(keys);
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  getPhone_index(info, keys) {
    wx.showLoading({
      title: '加载中',
    });
    let arr = {
      info: info,
      session_key: keys
    };
    let urlStr = app.getNetAddresss('member.mini-decrypt.index');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          para_arr: arr,
          not_validate_page: '0'
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            resolve(res.data.purePhoneNumber);
          } else {
            wx.hideLoading({
              success: (res) => { },
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  setBindPhone(mobile){
    let urlStr = app.getNetAddresss('member.member.bindMobile');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          mobile: mobile
        },
        success: function (resdata) {
          var res = resdata.data;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          resolve();
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  closeChangeId() {
    this.setData({
      showChangeID: false
    });
  },
  //先验证是否导致会员id变更
  getPrepBind(mobile) {
    let urlStr = app.getNetAddresss("member.member.prepBind");
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          mobile: mobile
        },
        validateBol: 2,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.is_show) {
              // 显示 导致会员id变更 弹窗
              this.setData({
                showChangeID: true,
                changidInfo: {
                  uid: res.data.uid,
                  change_uid: res.data.change_uid
                }
              });
            } else {
              resolve();
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject(res);
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
});
