// pages/login/login.ts
import { postAction, getAction, setToken } from '../../api/base';
import Base64 from '../../utils/base64.js';
const CryptoJS = require('crypto-js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userName: '',
    password: '',
    isEye: false,
    loading: false,
    encrypt: {} as any // AES密钥
  },

  getAccount(e: any) {
    this.setData({
      userName: e.detail.value
    });
  },
  getPassword(e: any) {
    this.setData({
      password: e.detail.value
    });
  },
  clearValue(e: any) {
    let type = e.currentTarget.dataset.type;
    if (type == 0) {
      this.setData({
        userName: ''
      });
    } else {
      this.setData({
        password: ''
      });
    }
  },
  changeShow() {
    let type = this.data.isEye;
    if (!type) {
      this.setData({
        isEye: true
      });
    } else {
      this.setData({
        isEye: false
      });
    }
  },
  toLoginIn() {
    let { userName, password } = this.data;
    if (!userName || !password) {
      wx.showToast({
        title: '请输入账号和密码',
        icon: 'none'
      });
      return;
    }
    if (this.data.loading) {
      return;
    }
    let base64 = new Base64();
    //加密base64.encode
    // let jiami=base64.encode(str.toString())
    //解密base64.decode
    // let jiemi=base64.decode(str.toString())

    let encryptedPassword = this.aesEncrypt(password);
    let parms = {
      userName: this.data.userName,
      password: encryptedPassword,
      code: ''
    };
    wx.login({
      timeout: 3000,
      success: res => {
        if (!res.code) {
          wx.showToast({
            title: '登录凭证获取失败，请重试！',
            icon: 'none'
          });
          return;
        } else {
          parms.code = res.code;
          console.log('登录凭证（code）', parms.code);
        }
        wx.showLoading({
          title: '加载中'
        });
        this.setData({
          loading: true
        });
        postAction('api/user/login', parms)
          .then((res: any) => {
            wx.hideLoading();
            if (res.code == 200) {
              // 存缓存然后跳转到对应角色的首页
              let temp = res.result;
              wx.setStorageSync('token', temp.token);
              wx.setStorageSync('userInfo', temp);
              setToken(temp.token);
              wx.showToast({
                title: '登录成功',
                icon: 'none'
              });
              setTimeout(() => {
                // this.setData({
                //   loading: false
                // })
                wx.reLaunch({
                  url: '../index/index',
                  fail: e => {
                    console.log(e);
                  }
                });
              }, 500);
            } else {
              this.setData({
                loading: false
              });
              wx.showToast({
                title: res.message,
                icon: 'none'
              });
            }
          })
          .catch(err => {
            this.setData({
              loading: false
            });
            wx.showToast({
              title: err.message,
              icon: 'none'
            });
          });
      }
    });
  },

  toWechatLogin() {
    let that = this;
    if (this.data.loading) {
      return;
    }
    //点击微信登录
    wx.login({
      timeout: 3000,
      success: (res: any) => {
        let sendData = {
          code: res.code
        };
        this.setData({
          loading: true
        });
        getAction('api/user/wxlogin', sendData)
          .then((res: any) => {
            if (res.code == 200 || res.code == 0) {
              let temp = res.result;
              wx.setStorageSync('token', temp.token);
              wx.setStorageSync('userInfo', temp);

              wx.showToast({
                title: '登录成功',
                icon: 'none'
              });
              setTimeout(() => {
                // this.setData({
                //   loading: false
                // })
                wx.reLaunch({
                  url: '../index/index',
                  fail: e => {
                    console.log(e);
                  }
                });
              }, 500);
            } else {
              this.setData({
                loading: false
              });
              if (res.message == '获取用户信息失败') {
                wx.showToast({
                  title: '当前微信用户未绑定调度员账户',
                  duration: 1000,
                  icon: 'none'
                });
              } else {
                wx.showToast({
                  title: res.message,
                  duration: 1000,
                  icon: 'none'
                });
              }
            }
          })
          .catch(function (err) {
            that.setData({
              loading: false
            });
            console.log(err);
          });
      }
    });
  },
  // 获取密钥
  getEncrypt() {
    getAction('api/user/getEncryptedString').then((res: any) => {
      if (res.success) {
        this.setData({
          encrypt: res.result
        });
      } else {
        wx.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none'
        });
      }
    });
  },
  // 加密
  aesEncrypt(text: string) {
    let encrypt = this.data.encrypt;
    const keyWordArray = CryptoJS.enc.Utf8.parse(encrypt.key);
    const ivWordArray = CryptoJS.enc.Utf8.parse(encrypt.iv);
    const secret = CryptoJS.enc.Utf8.parse(text);
    const cipherParams = CryptoJS.AES.encrypt(secret, keyWordArray, {
      iv: ivWordArray
    });
    return CryptoJS.enc.Base64.stringify(cipherParams.ciphertext);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getEncrypt();
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
