// pages/userLogin/userLogin.js
//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    spashTextValue: '- 智慧服务  智创未来 -',
    splashImageUrl: '/images/rbg.jpg',
    splashImageUrl2: '/images/zi.png',
    code: '',
    phone: '13838379499',
    name: '',
    pass: '',
    depNames: ['部门1','部门2'],
    depIds: [1,2],
    depIdx: 0,
    depId: 0,
    depName: '请选择部门'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      phone: options.phone
    })
    this.getDeps();
  },

  getDeps(){
    let that = this;
    let orgId = wx.getStorageSync("orgId");
    wx.request({
      url: app.globalData.serverUrl + 'common/deps',
      data: {
        orgId: orgId
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.code == 0) {
          let deps = res.data.data;
          let ids = [];
          let names = [];
          deps.forEach((item) => {
            ids.push(item.id);
            names.push(item.title);
          });

          that.setData({
            depNames: names,
            depIds: ids
          });
        }else{
    
        }
      },
      fail:function(){
        
      }
    })
  },

  getCode(){
    let that = this;
    wx.login({
      success: function (ret) {
        that.code = ret.code;
      }
    });
  },

  bindDepChange(e){
    let idx = Number(e.detail.value);

    console.log(idx,this.data.depIds);
    this.setData({
      depIdx: idx,
      depId: this.data.depIds[idx],
      depName: this.data.depNames[idx]
    })
  },

  getNameValue: function(data){
    this.setData({
      name: data.detail.value
    })
  },
  getPassValue: function(data){
    this.setData({
      pass: data.detail.value
    })
  },

  getPhoneNumber(e){
    console.log(e);
  },

  getUserInfo(){
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (e) => {
        wx.showLoading({
          title: '加载中',
          mask: true
        });
        let orgId = wx.getStorageSync("orgId");
        wx.request({
          url: app.globalData.serverUrl + 'login/wxLogin',
          data: {
            orgId: orgId,
            code: this.code,
            iv: e.iv,
            encryptedData: e.encryptedData
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            console.log(res);
            wx.hideLoading();
            if (res.data.code == 0) {
              try {
                app.logout();
                wx.setStorageSync("userId", res.data.data.userId);
                wx.setStorageSync("token", res.data.data.token);
              } catch (e) { };

              var userinfo = {
                userId: res.data.data.userId,
                token: res.data.data.token,
              };

              app.globalData.userinfo = userinfo;

              wx.switchTab({
                url: '/pages/index/index'
              });
            }else{
              wx.showModal({
                title: '提示',
                content: res.data.message,
                showCancel: false
              })
            }
          },
          fail:function(){
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '登录失败,请重试',
              showCancel: false
            })
          }
        })
      }
    });
  },

  
  //提交
  onSubmit: function(){
    var phone = this.data.phone;
    var pass = this.data.pass;
    var name = this.data.name;
    let orgId = wx.getStorageSync("orgId");
    //去除开始结尾空格
    if (name.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, '') && pass){
      wx.showLoading({
        title: '注册中',
        mask: true
      });
      wx.request({
        url: app.globalData.serverUrl + 'login/wxRegister',
        data: {
          orgId: orgId,
          phone: phone,
          name: name,
          pass: pass,
          depId: this.data.depId
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading();
          if (res.data.code == 0) {
            try {
              app.logout();
              wx.setStorageSync("userId", res.data.data.userId);
              wx.setStorageSync("token", res.data.data.token);
              wx.setStorageSync("orgId", res.data.data.orgId);
            } catch (e) { };
  
            var userinfo = {
              userId: res.data.data.userId,
              token: res.data.data.token,
            };
  
            app.globalData.userinfo = userinfo;
  
            wx.switchTab({
              url: '/pages/index/index'
            });
          }else{
            wx.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false
            })
          }
        },
        fail:function(){
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: '登录失败,请重试',
            showCancel: false
          })
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '账号或密码为空！',
        showCancel: false
      })
    }
  },

  goYY(){
    var token = wx.getStorageSync("visitorToken");
    if (!token || token == undefined) { //未登录
      wx.login({
        success: function (loginRes) {
          var serverUrl = app.globalData.visitorServerUrl;
          if (loginRes) {
            wx.request({
              url: serverUrl + 'oauth/checkCode',
              data: {
                type: 2,
                code: loginRes.code//临时登录凭证
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                if (res.data.code == -101) {
                  wx.removeStorageSync("visitorToken");
                  wx.redirectTo({
                    url: '/pages/splash/splash?type=visitor'
                  })
                }else if (res.data.code == 0) {
                  try {
                    wx.setStorageSync("visitorToken", res.data.data.token);
                    wx.setStorageSync("visitorUserId", res.data.data.userId);
                  } catch (e) {
                    app.logout();
                    wx.showModal({
                      title: '提示',
                      content: '登录异常！',
                      showCancel: false
                    })
                    return false;
                  };
                  wx.redirectTo({
                    url: '/pages/visitor/index'
                  });
                }
              },
              fail: function (err) {
                wx.showModal({
                  title: '提示',
                  content: '登录异常！',
                  showCancel: false
                })
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '登录异常！',
              showCancel: false
            })
          }
        }
      })
    }else{
      wx.navigateTo({
        url: '/pages/visitor/index'
      });
    }

    
  },

})