const util = require('../../utils/util.js');
const md = require('../../utils/md5.js');
const app = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    clickTimes: false,
    type: '',
    firstLogin: false,
    needRecomCode: 0,
    code: '',
    show: false,
    invitePrice: 0,
    flag: true,
    shareInfo: {},
    vouchers: [{
      price: 0,
      lowestPrice: 0,
      description: '0'
    }],
    avatarUrl: '',
    // 注册
    username: "",
    phoneNum: "",
    password: '',
    // passwordConfirmation: '',
    it: {},
    unionId: "",
    socialUid: '',
    authorization: true,//登录模式  为true是微信登录
    formData: {
      loginName: '',
      password: '',
    },
    quitLogin: false,//退出登录
    registeredShow: false//手机号已注册弹窗
  },
  // 页面加载 获取小程序码链接参数
  onLoad(options) {
    this.registerStatus()
    this.setData({
      quitLogin: options.quitLogin || false
    });
    let that = this;
    if (!util.isEmpty(options.scene)) {
      util.ajax({
        func: "params",
        data: {
          "code": options.scene.replace("urlcode%3D", "").replace("urlcode=", "")
        },
        load: false
      }, function (res) {
        if (res.code == 0) {
          wx.setStorageSync("WX-invite", res.data.code);
          that.setData({
            type: 'share'
          });
          if (!util.isObjEmpty(app.globalData.userInfo)) {
            wx.reLaunch({
              url: '/pages/home/index',
            });
          }
          that.isRecomCode();
        }
      });
    } else {
      this.setData({
        type: options.type || ''
      });
      that.isRecomCode();
    }
  },
  onShow() {
    wx.hideHomeButton()
  },
  // 获取用户注册情况
  registerStatus() {
    let that = this
    wx.login({
      success: res => {
        util.ajax({
          func: "v2/login/check_user_exist",
          data: {
            "code": res.code
          },
          method: 'POST'
        }, function (datas) {
          if (datas.code == 0) {
            that.setData({
              firstLogin: datas.data
            })
          } else {

          }
        });
      }
    });

  },
  // 获取邀请人信息
  isRecomCode() {
    let that = this,
      code = wx.getStorageSync("WX-invite");
    if (util.isEmpty(code)) return false;
    util.ajax({
      func: "inviter/info",
      data: {
        "code": code
      }
    }, function (res) {
      if (res.code == 0) {
        that.setData({
          needRecomCode: ((res.data.roleType == 'sharer' || res.data.roleType == 'organ') && res.data.roleTypeDisable == 0 ? 1 : 0),
          shareInfo: res.data
        });
      }
    });
  },
  back() {
    this.setData({
      show: false
    })
    // 退出登录
    if (this.data.quitLogin) {
      wx.reLaunch({
        url: '/pages/home/index'
      })
    } else {
      setTimeout(() => {
        wx.navigateBack();
      }, 200);
    }
  },
  // 切换登录
  toggleLogin() {
    this.setData({
      authorization: !this.data.authorization
    })
  },
  phoneNumInput(e) {
    this.setData({
      'formData.loginName': e.detail.value
    })
    if (this.data.formData.loginName.length == 11) {
      this.setData({
        passwordFocus: true
      })
    }
  },
  passwordInput(e) {
    this.setData({
      'formData.password': e.detail.value
    })
  },
  navigatorURl() {
    wx.navigateTo({
      url: '/pages/account/setting/password?noLogin=true',
    });
  },
  // 手机号密码登录
  accountLogin() {
    let that = this,
      data = that.data.formData
    if (util.isPhone(data.loginName)) {
      util.showTips("请输入正确的手机号。");
      return false;
    }
    if (util.isEmpty(data.password)) {
      util.showTips("请输入密码。");
      return false;
    }
    if (data.password < 6) {
      util.showTips("请输入至少6位密码。");
      return false;
    }
    data.password = md.hexMD5(data.password);
    wx.login({
      success: loginRes => {
        // 用于绑定微信
        data.code = loginRes.code
         // 生成时间戳做唯一值 用来获取openid
         let timestamp = new Date().getTime();
        data.payUserCode = Math.floor(timestamp / 1000)
        wx.setStorageSync("payUserCode", data.payUserCode);
        util.ajax({
          func: "v2/login/account",
          data: data
        }, function (res) {
          if (res.code == 0) {
            res.data.role = util.userRole(Math.round(res.data.score));
            // 强制退出登录
            res.data.VERSION = 9
            wx.setStorageSync("WXuserInfo", res.data);
            app.globalData.userInfo = res.data
            that.getOpenId()
            if (that.data.type == "share") {
              wx.reLaunch({
                url: '/pages/home/index',
              });
            } else {
              // 返回逻辑
              that.back();
            }
          } else {
            util.showTips(res.reason);
          }
          that.setData({
            clickTimes: false
          })
        });
      },
      fail(err) {
        util.showTips(err.errno + "微信授权失败，请刷新页面后重试");
      }
    });
  },
  getOpenId() {
    util.ajax({
      func: "v2/login/getPayUserOpenId",
      data: { payUserCode: wx.getStorageSync("payUserCode") }
    }, function (res) {
      if (res.code == 0) {
        // 将新获取的作为下单openid
        app.globalData.userInfo.socialUid = res.data
      } else {
        util.showTips(res.reason);
      }
    })
  },
  // 用户注册并登录
  registerLogin(e) {
    let that = this
    let data = {}
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      data.vcode = e.detail.code;
      wx.login({
        success: res => {
          data.code = res.code;
          data.channelId = util.config.channelInfo.channel //渠道标识
          util.ajax({
            func: "applet/regUser",
            data: data,
            method: 'POST'
          }, function (data) {
            if (data.code == 0) {
              console.log(676767)
              data.data.role = util.userRole(Math.round(data.data.score));
              wx.setStorageSync("WXuserInfo", data.data);
              app.globalData.userInfo = data.data
              if (that.data.type == "share") {
                wx.reLaunch({
                  url: '/pages/home/index',
                });
              } else {
                that.back();
              }
            } else
              util.showTips(data.reason);
          });
        }
      })
    }
  },
  // 用户登录
  getUserProfile() {
    let that = this;
    this.setData({
      clickTimes: true
    })
    wx.login({
      success: res => {
        that.setData({
          code: res.code
        })
      }
    });
    that.userProfile();
  },
  userProfile() {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中
      success: (res) => {
        let it = {};
        if (!res.encryptedData && !res.iv) {
          it.version = "applet_v1.0.0";
          it.code = that.data.code;
          it.target = 'app';
          it.phone = that.data.phoneNum
        } else {
          it.version = "applet_v1.0.0";
          it.code = that.data.code;
          it.target = 'app';
          it.encryptedData = res.encryptedData;
          it.iv = res.iv;
          it.phone = that.data.phoneNum
        }
        that.data.it = it
        util.ajax({
          func: "applet_login",
          data: it
        }, function (data) {
          if (data.code == 0) {
            that.setData({
              unionId: data.data.unionId,
              socialUid: data.data.socialUid
            })
            // todo：
            // data.data.firstLogin = 1
            // if (data.data.firstLogin == 1) {
            //   wx.setNavigationBarTitle({ title: '注册' })
            //   that.setData({
            //     flag: false
            //   })
            //   return
            // }
            data.data.role = util.userRole(Math.round(data.data.score));
            // 强制退出登录
            data.data.VERSION = 9
            wx.setStorageSync("WXuserInfo", data.data);
            app.globalData.userInfo = data.data
            if (that.data.type == "share") {
              wx.reLaunch({
                url: '/pages/home/index',
              });
            } else {
              that.back();
            }
          } else {
            util.showTips(data.reason);
          }
          that.setData({
            clickTimes: false
          })
        });
      },
      fail(rr) {
        console.log(67676767, rr)
      }
    });
  },

  // 用户注册绑定手机号
  getPhoneNumber(e) {
    let that = this
    let data = {};
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      data.code = e.detail.code;
      util.ajax({
        func: "getUserPhone",
        data: data,
      }, function (data) {
        if (data.code == 0) {
          that.setData({
            phoneNum: data.data
          })
          // 已注册
        } else if (data.code == 1007) {
          that.setData({
            phoneNum: data.data,
            registeredShow: true
          })
        } else
          util.showTips(data.reason);
      });
    }
  },
  // 注册
  signIn() {
    let that = this
    if (this.data.username == "" && this.data.avatarUrl == "") {
      util.showTips("昵称头像不能为空");
      return
    } else if (this.data.username == "") {
      util.showTips("昵称不能为空");
      return
    } else if (this.data.avatarUrl == "") {
      util.showTips("请点击上传一张属于您自己的头像 ~");
      return
    } else if (this.data.password == "") {
      util.showTips("密码不能为空");
      return
    } else if (this.data.password.length < 6) {
      util.showTips("请输入至少6位密码");
      return
    }
    //  else if (this.data.passwordConfirmation != this.data.password) {
    //   util.showTips("两次密码不一致");
    //   return
    // }
    let data = {};
    wx.login({
      success: res => {
        data.phone = that.data.phoneNum;
        data.code = res.code;
        data.nickname = that.data.username
        data.avatar = that.data.avatarUrl
        data.password = md.hexMD5(that.data.password)
        data.unionId = that.data.unionId
        data.socialUid = that.data.socialUid
        data.channelId = util.config.channelInfo.channel //渠道标识
        data.city = app.globalData.city.city
        // 非列表城市改为空
        let cityList = wx.getStorageSync("cityList");
        if (data.city && cityList) {
          data.city = cityList.indexOf(data.city) == -1 ? '' : data.city
        }
        util.ajax({
          func: "applet/regUser",
          data: data,
          method: 'POST'
        }, function (data) {
          if (data.code == 0) {
            data.data.role = util.userRole(Math.round(data.data.score));
            // 强制退出登录
            data.data.VERSION = 9
            app.globalData.userInfo = data.data;
            // that.data.phoneNum=data.phoneNum
            that.setData({
              phoneNum: data.data.phoneNum
            })
            wx.setStorageSync("WXuserInfo", data.data);
            if (that.data.needRecomCode == 1) {
              wx.navigateTo({
                url: '/pages/home/referre?type=' + that.data.type,
              });
              that.bindCode();
              return false
            }
            // wx.navigateBack()
            that.back();
          } else
            util.showTips(data.reason);
        });
      }
    })
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    let that = this
    console.log(that.data.unionId);
    // wx.showLoading({ title: '上传准备中' });
    // 直传头像
    util.uploadFile("oss/policy", avatarUrl, {
      unionId: that.data.unionId,
      type: "userAvatar"
    }, true).then((res) => {
      if (res.code == 0) {
        that.data.avatarUrl = res.url
        this.setData({
          avatarUrl: that.data.avatarUrl
        })
      }
    });
  },
  username(e) {
    // console.log(e.detail.value);
    this.data.username = e.detail.value
    this.setData({
      username: this.data.username
    })
  },
  pwSetting(e) {
    this.setData({
      password: e.detail.value
    })
  }, 
  // pwConfirmation(e) {
  //   this.setData({
  //     passwordConfirmation: e.detail.value
  //   })
  // },
  // 绑定邀请码
  bindCode() {
    let that = this,
      code = wx.getStorageSync("WX-invite");
    if (this.data.shareInfo.roleType == 'normal') {
      util.showTips("该用户不是分享家/机构,无法绑定邀请码。");
      return false;
    }
    if (this.data.shareInfo.roleTypeDisable == 1) {
      util.showTips("该分享家/机构未启用,无法绑定邀请码。");
      return false;
    }
    util.ajax({
      func: "user/savecode",
      data: {
        "code": code,
        receiveType: 1
      }
    }, function (res) {
      if (res.code == 0) {
        app.globalData.userInfo['recomCode'] = code;
        wx.setStorageSync("WXuserInfo", app.globalData.userInfo);
        // console.log(code, that.data.shareInfo.roleType)
        if (that.data.shareInfo.roleType == 'sharer' || that.data.shareInfo.roleType == 'organ') {
          that.setData({
            show: true,
            vouchers: res.vouchers,
            invitePrice: res.invitePrice
          });
          // console.log(that.data.show)
        } else {
          that.back();
        }
      } else
        util.showTips(res.reason);
    });
  },
})