const app = getApp();
//引用封装好的加密解密js
// var Dec = require('../../utils/publicAES.js');
// console.log(Dec.Encrypt("需要加密的字符串"));
// console.log(Dec.Decrypt("需要解密的字符串"));

var network = require("../../utils/net.js");

var that = this;
var openid;
var Phone;
var nickName;
var gender;
var province;
var city;
var country;
var avatarUrl;
var UnionId;
var code;

//获取openID 参数1、app.globalData.AppId  2、code
function getOpenId(successaction) {
  wx.login({
    success: function(res) {
      code = res.code;
      var method = '/MainSystem/B3WeChatMiniProgram/Rpcs/CommonRpc/GetMiniOpenIdByCode';
      var params = [app.globalData.AppId, code];
      network.previousRequestLoading(method, params, function(res) {
        app.globalData.OpenId = res.result;
        successaction(app.globalData.OpenId)
      })
    }
  })
}

//获取绑定的客户ID 参数1：appid, 参数2：openid 返回用户电话 客户ID 客户Name
function IsBind(openid, successaction) {
  var method = '/MainSystem/B3WeChatMiniProgram/Rpcs/CommonRpc/GetBindCustomer';
  var params = [app.globalData.AppId, openid];
  network.previousRequestLoading(method, params, function(res) {
    app.globalData.CustomerId = res.result.ID;
    successaction(res.result.WeixinUser_Phone)
  })
}

//绑定公众号 参数用户电话 返回true已关注 false未关注
function IsBindWeixinMP(phone) {
  let method = '/MainSystem/B3WeChatMiniProgram/Rpcs/CommonRpc/IsBindWeixinMP';
  let params = [phone];
  network.previousRequestLoading(method, params, function(res) {
    //添加假数据。方便登录测试，提交版本需更正注释
    // res.result = false;
    if (res.result == true) {
      wx.switchTab({
        url: '/pages/homePage/homePage',
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请关注公众号',
        showCancel: false,
      })
    }
  })
}

Page({
  data: {
    userInfo: "",
    array: [{
      ID: 0,
      Name: "请选择所属客户"
    }],
    index: 0,
    //根据customerID值判断是否隐藏选择框（默认显示）
    showCustomerChoise: true,
  },

  // 客户列表变更选项信息
  listenerPickerSelected: function(e) {
    this.setData({
      index: e.detail.value,
    });
  },

  // 电话输入框
  phoneNum: function(e) {
    Phone = e.detail.value
    app.globalData.Phone = Phone
  },

  // 获取所有客户列表
  choiceCustomer: function(succession) {
    var that = this;
    var method = '/MainSystem/B3WeChatMiniProgram/Rpcs/CustomerRpc/GetList';
    var params = [];
    network.previousRequestLoading(method, params, function(res) {
      succession();
      if (res.result.length > 0) {
        var lastArr = that.data.array.concat(res.result)
        that.setData({
          array: lastArr,
        })
      }
    })
  },

  // 用户绑定按钮操作
  getUserInfo: function(e) {
    var that = this;
    if (e.detail.userInfo != null) {
      app.globalData.userInfo = e.detail.userInfo;
      nickName = app.globalData.userInfo.nickName;
      gender = app.globalData.userInfo.gender;
      province = app.globalData.userInfo.province;
      city = app.globalData.userInfo.city;
      country = app.globalData.userInfo.country;
      avatarUrl = app.globalData.userInfo.avatarUrl;
      //判断用户是否获取绑定信息
      if (that.data.showCustomerChoise) {
        if (that.data.array[that.data.index].ID == 0) {
          wx.showToast({
            image: '/imgs/avatar.png',
            title: '请选择所属客户',
          })
          return false;
        }
      }
      if (app.globalData.Phone == "") {
        wx.showToast({
          image: '/imgs/avatar.png',
          title: '手机号码不能为空',
        })
        return false;
      } else if (!(/^1[34578]\d{9}$/.test(app.globalData.Phone))) {
        wx.showToast({
          image: '/imgs/avatar.png',
          title: '号码不正确',
        })
        return false;
      }
    } else {
      wx.showModal({
        title: '授权提示',
        content: '请给予权限，不涉及个人隐私',
        showCancel: false
      })
    }
    var method = '/MainSystem/B3WeChatMiniProgram/Rpcs/CommonRpc/Bind';
    var params = [{
      OpenId: openid,
      Phone: app.globalData.Phone,
      NickName: app.globalData.userInfo.nickName,
      Sex: app.globalData.userInfo.gender,
      Province: app.globalData.userInfo.province,
      City: app.globalData.userInfo.city,
      Country: app.globalData.userInfo.country,
      HeadImgUrl: app.globalData.userInfo.avatarUrl,
      UnionId: "",
      //请求新增参数
      AppId: app.globalData.AppId,
      CustomerId: that.data.array[that.data.index].ID,
    }];
    var storageCustomerID = that.data.array[that.data.index].ID;
    app.globalData.CustomerId = storageCustomerID;

    // 先绑定客户服务器
    that.bindCustomerPreviousURL(function(res) {
      // 再绑定中转服务器
      network.previousRequestLoading(method, params, function(res) {
        // 再判断是否关联公众号
        IsBindWeixinMP(app.globalData.Phone);

      });
    })
  },

  // 进入公众号绑定页面
  bindPublicNumber: function(event){
    wx.navigateTo({
      url: '/pages/first/first?code=' + code,
    })
  },

  // 绑定客户服务器
  bindCustomerPreviousURL: function(successaction) {
    var method = '/MainSystem/B3MiniProgramRpc/XuRpcs/Customer/AccountRpc/XuBindByPhone';
    var previousParams = [{
      OpenId: openid,
      Phone: app.globalData.Phone,
      NickName: app.globalData.userInfo.nickName,
      Sex: app.globalData.userInfo.gender,
      Province: app.globalData.userInfo.province,
      City: app.globalData.userInfo.city,
      Country: app.globalData.userInfo.country,
      HeadImgUrl: app.globalData.userInfo.avatarUrl,
      UnionId: "",
    }];
    network.requestLoading(method, previousParams, function(res) {
      successaction(res.result);
    })
  },

  // 页面初始化 静默登录相关判断
  onShow: function() {
    var that = this;
    this.choiceCustomer(function (res){
      getOpenId(function (res) {
        openid = res;
        IsBind(openid, function (res) {
          app.globalData.Phone = res;
          if (res == "") {

          } else {
            //跳转到指定页面
            IsBindWeixinMP(app.globalData.Phone)
          }
        })
      })
    });
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '分享页面的标题',
      path: "/pages/login/login",
      //分享成功后执行
      success: function(res) {
        console.log("--------------转发成功--------------------")
      },

      fail: function(res) {
        console.log("--------------转发失败--------------------")
      }
    }
  }



})