// pages/loginv2/loginv2.js
import JSEncrypt from '../../utils/jsencrypt.min.js'
const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n' +
  '2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ=='

const privateKey = 'MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEA0vfvyTdGJkdbHkB8\n' +
  'mp0f3FE0GYP3AYPaJF7jUd1M0XxFSE2ceK3k2kw20YvQ09NJKk+OMjWQl9WitG9p\n' +
  'B6tSCQIDAQABAkA2SimBrWC2/wvauBuYqjCFwLvYiRYqZKThUS3MZlebXJiLB+Ue\n' +
  '/gUifAAKIg1avttUZsHBHrop4qfJCwAI0+YRAiEA+W3NK/RaXtnRqmoUUkb59zsZ\n' +
  'UBLpvZgQPfj1MhyHDz0CIQDYhsAhPJ3mgS64NbUZmGWuuNKp5coY2GIj/zYDMJp6\n' +
  'vQIgUueLFXv/eZ1ekgz2Oi67MNCk5jeTF2BurZqNLR3MSmUCIFT3Q6uHMtsB9Eha\n' +
  '4u7hS31tj1UWE+D+ADzp59MGnoftAiBeHT7gDMuqeJHPL4b+kC+gzV4FGTfhR9q3\n' +
  'tTbklZkD2A=='

// 加密
function encrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对需要加密的数据进行加密 
}

// 解密
function decrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey)
  return encryptor.decrypt(txt)
}
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    iconImgUrl: 'http://39.102.232.151:8030/cover/tianhongicon.png',
    enterImgUrl: 'http://39.102.232.151:8030/cover/企业icon.png',
    nameImgUrl: 'http://39.102.232.151:8030/cover/姓名用户名昵称icon.png',
    nickNameImgUrl: 'http://39.102.232.151:8030/cover/座席姓名icon.png',
    wxImgUrl: 'http://39.102.232.151:8030/cover/微信icon.png',
    passwordImgUrl: 'http://39.102.232.151:8030/cover/密码icon.png',
    phoneImgUrl: 'http://39.102.232.151:8030/cover/手机号icon.png',
    validCodeImgUrl: 'http://39.102.232.151:8030/cover/验证码icon.png',

    imgurl: '',
    hasSearchResult: false,
    curregisterorlogin: false,
    userpassorphone: true,

    enterpriseId: '',
    username: '',
    password: '',
    repeatPassword: '',
    wechat: '',
    phone: '',
    nickname: '',
    entries: [],
    entryName: '',
    curIdentity: '企业管理',
    isRegisterLoading: false,

    login1Username: '',
    login1Password: '',
    login1Code: '',
    isLogin1Loading: false,
    isLogin2Loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCode()
    wx.request({
      url: app.globalData.appBaseUrl + '/api/thCompany/query',
      method: 'get',
      data: {
        companyId: app.globalData.companyId
      },
      success: (res) =>{
        console.log(res.data, 'thCompany/query')
        if (res.data && res.data.length > 0) {
          console.log(this.data, 'this.data')
          this.setData({
            companyName: res.data[0].companyName
          })
          wx.request({
            url: app.globalData.appBaseUrlV2 + '/api/enterpriseCertificate/pageEnterprise',
            method: 'get',
            header: {
              Authorization: app.globalData.Authorization
            },
            data: {
              companyName: res.data[0].companyName
            },
            success: (res1)=> {
              console.log(res1, 'api/enterpriseCertificate/apgeEnterprise')
              this.setData({
                enters: [...res1.data.content.map(item => {
                  return {
                    companyName: item.enterpriseName,
                    companyId: item.enterpriseId,
                    emergencyPlan: item.emergencyPlanNum,
                    dualSystem: item.dualSystemNum,
                    standardization: item.standardizationNum
                  }
                })]
              })
            }
          })
        }
      }
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /*搜索企业1*/
  confirmEntryName(event) {
    console.log(event, 'hehehe')
    wx.request({
      url: app.globalData.appBaseUrl + '/api/thCompany',
      method: 'GET',
      data: {
        page: 0,
        size: 2,
        companyName: event.detail.value
      },
      success: (res) => {
        this.setData({
          entries: res.data.content,
          hasSearchResult: true
        })
      }
    })
  },
  chosenEntry(event) {
    this.setData({
      enterpriseId: event.currentTarget.dataset.id,
      entryName: event.currentTarget.dataset.name,
      hasSearchResult: false
    })
    console.log(event.currentTarget.dataset.id, 'event.currentTarget.dataset.id')
    console.log(event.currentTarget.dataset.name, 'this.currentTarget.dataset.name')
  },
  closeSearch(event) {
    this.setData({
      hasSearchResult: false
    })
  },
  /*
   * 搜索企业 
  */
  searchEntries(event) {
    // this.isShowSearchEntries = true
    this.setData({
      isShowSearchEntries: true
    })
    wx.request({
      url: app.globalData.appBaseUrl + '/api/thCompany',
      method: 'GET',
      data: {
        page: 0,
        size: 3,
        companyName: this.data.entryName
      },
      success: (res) => {
        // console.log(res, 'hehexixihaha')
        this.setData({
          entries: res.data.content
        })
      }
    })
  },
  /**
   * 选中搜索的企业
   */
  selectSearchgEntry(event) {
    if (event.currentTarget.dataset && event.currentTarget.dataset.entry) {
      this.setData({
        entryName: event.currentTarget.dataset.entry,
        isShowSearchEntries: false
      })
      this.data.entryId = event.currentTarget.dataset.id
    }
  },
  changeSelectIdentity(event) {
    if (event.detail.value === '企业管理') {
      this.data.identityOptions[0].checked = true
      this.data.identityOptions[1].checked = false
    }
    if (event.detail.value === '企业员工'){
      this.data.identityOptions[0].checked = false
      this.data.identityOptions[1].checked = true
    }
  },
  /**
   * 注册按钮
   */
  registerUser() {
    if (!this.data.userName || !this.data.passWord || !this.data.wxNumber || !this.data.PhoneNum || this.entryId === -1) {
      wx.showToast({
        title: "请输入正确信息",
        icon: "error"
      })
    }
    if (this.data.identityOptions[0].checked) {
      wx.request({
        url: app.globalData.appBaseUrlV2 + '/api/thUser/signUp' ,
        method: 'POST',
        data: {
          companyId: this.data.entryId,
          username: this.data.userName,
          password: this.data.passWord,
          phone: this.data.PhoneNum,
          wechat: this.data.wxNumber,
          roles: [
            {
              id: this.data.enterManagerId,
              roleName: '企业管理'
            }
          ]
        },
        success: (res) => {
          if (res.statusCode === 201) {
            wx.showToast({
              title: '注册已提交',
            })
          } else if (res.statusCode === 400) {
            wx.showToast({
              title: '用户名已存在',
              icon: 'error'
            })
          }
        }
      })
    } else {
      wx.request({
        url: app.globalData.appBaseUrlV2 + '/api/thUser/signUp' ,
        method: 'POST',
        data: {
          companyId: this.data.entryId,
          username: this.data.userName,
          password: this.data.passWord,
          phone: this.data.PhoneNum,
          wechat: this.data.wxNumber,
          roles: [
            {
              id: this.data.enterstaffId,
              roleName: '企业员工'
            }
          ]
        },
        success: (res) => {
          if (res.statusCode === 201) {
            wx.showToast({
              title: '注册已提交',
            })
          }
        }
      })
    }
  },
  /**
   * 
   */
  jumptouserpass() {
    this.setData({
      curLoginOption: "用户\\密码登录"
    })
  },
  jumptophone() {
    this.setData({
      curLoginOption: "手机号登录"
    })
  },
  getCode() {
    wx.showLoading({
      title: '正在获取验证码',
    })
    wx.request({
      url: app.globalData.appBaseUrlV2 + '/auth/code',
      method: 'GET',
      success: (res) => {
        this.uuid = res.data.uuid
        this.setData({
          imgurl: res.data.img
        }, () => {
          wx.hideLoading()
        })
      },
      fail: () => {
        wx.hideLoading()
      }
    })
  },
  loginInputUserName(event) {
    this.data.loginUserName = event.detail.value
  },
  loginInputPassWord(event) {
    console.log(event.detail.value)
    this.data.loginPassWord = event.detail.value
  },
  loginInputCode(event) {
    this.data.loginCode = event.detail.value
  },
  loginByUserPass() {
    console.log(this.data.loginUserName)
    console.log(this.data.loginPassWord)
    console.log(this.data.loginCode)
    if (!this.data.loginUserName || !this.data.loginPassWord || !this.data.loginCode) {
      wx.showToast({
        title: "请输入正确的信息",
        icon: "error"
      })
      return
    }
    wx.request({
      url: app.globalData.appBaseUrl + '/auth/login',
      method: 'POST',
      data: {
        username: this.data.loginUserName,
        password: encrypt(this.data.loginPassWord),
        code: this.data.loginCode,
        uuid: this.uuid
      },
      success: (res) => {
        console.log(res, '前面传过来的 res')
        if ((res.statusCode >=200 && res.statusCode <=300) || res.statusCode === 304) {
          wx.redirectTo({
            url: '/pages/home/home',
            success: () => {
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1000
              })
            }
          })
        } else if (res.statusCode === 401 || res.statusCode === 400){
          wx.showToast({
            title: '验证码过期',
            icon: 'error',
            duration: 2000
          })
          this.getCode()
        } else {
          wx.showToast({
            title: '发生错误',
            icon: 'error',
            duration: 2000
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: "请输入正确的信息",
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  jumpToLogin() {
    
    this.setData({
      curregisterorlogin: false
    })
  },
  jumpToRegister() {
    this.setData({
      curregisterorlogin: true
    })
  },
  jumpToUserPass() {
    this.setData({
      userpassorphone: true
    })
  },
  jumpToPhoneCode() {
    this.setData({
      userpassorphone: false
    })
  },
  gotoStaff() {
    this.setData({
      curIdentity: '企业员工'
    })
  },
  gotoManager() {
    this.setData({
      curIdentity: '企业管理'
    })
  },
  inputUsername(event) {
    this.data.username = event.detail.value
  },
  inputPassword(event) {
    this.data.password = event.detail.value
  },
  inputRepeatPassword(event) {
    this.data.repeatPassword = event.detail.value
  },
  inputWeChat(event) {
    this.data.wechat = event.detail.value
  },
  inputPhoneNumber(event) {
    this.data.phone = event.detail.value
  },
  inputNickName(event) {
    this.data.nickname = event.detail.value
  },
  registerToEntry(event) {
    if (!this.data.entryName) {
      wx.showToast({
        title: '请选择企业',
        icon: 'error'
      })
      return
    }
    if (!this.data.username) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'error'
      })
      return
    }
    if (!this.data.password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'error'
      })
      return
    }
    if (!this.data.wechat) {
      wx.showToast({
        title: '请输入微信号',
        icon: 'error'
      })
      return
    }
    if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'error'
      })
      return
    }
    if (!this.data.nickname) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'error'
      })
      return
    }
    if (this.data.password !== this.data.repeatPassword) {
      wx.showToast({
        title: '密码不一致',
        icon: 'error'
      })
      return
    }
    if (!new RegExp("\\d{11}").test(this.data.phone)) {
      wx.showToast({
        title: '请输入正确的手机号格式',
        icon: 'error'
      })
      return
    }
    this.setData({
      isRegisterLoading: true
    })
    wx.request({
      url: app.globalData.appBaseUrlV2 + '/api/thUser/signUp',
      method: 'POST',
      data: {
        companyId: this.data.enterpriseId,
        username: this.data.username,
        password: this.data.password,
        wechat: this.data.wechat,
        phone: this.data.phone,
        nickName: this.data.nickname,
        tag: this.data.curIdentity
      },
      success: (res) => {
        if (res.statusCode === 201) {
          wx.showToast({
            title: '注册已提交，请勿重复提交',
            icon: 'error'
          })
        } else {
          wx.showToast({
            title: '发生错误，请稍后再试',
            icon: 'error'
          })
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '发生错误，请稍后再试',
          icon: 'error'
        })
      },
      complete: () => {
        this.setData({
          isRegisterLoading: false
        })
      }
    })
  },
  getNewCode() {
    this.getCode()
  },
  inputLogin1UserName(event) {
    this.data.login1Username = event.detail.value
  },
  inputLogin1PassWord(event) {
    this.data.login1Password = event.detail.value
  },
  inputLogin1Code(event) {
    this.data.login1Code = event.detail.value
  },
  ClickToLogin1() {
    if (!this.data.login1Username) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'error'
      })
      return
    }
    if (!this.data.login1Password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'error'
      })
      return
    }
    if (!this.data.login1Code) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'error'
      })
      return
    }
    this.setData({
      isLogin1Loading: true
    })
    wx.request({
      url: app.globalData.appBaseUrlV2 + '/api/auth/login',
      method: 'POST',
      data: {
        username: this.data.login1Username,
        password: encrypt(this.data.login1Password),
        code: this.data.login1Code,
        uuid: this.uuid
      },
      success: (res) => {
        console.log(res, 'hehehhehe9xixixixixi')
        if ((res.statusCode >=200 && res.statusCode <=300) || res.statusCode === 304 ) {
          console.log(res, 'login res')
          // 保存 token
          app.globalData.Authorization = res.data.token
          app.globalData.companyId = res.data.user.user.companyId
          app.globalData.userInfo = res.data.user.user
          const myRoles = ['政府', '运营商', '企业管理', '企业员工', '超级管理员']
          let curRole = ''
          for (const item of res.data.user.user.roles) {
            const tempIndex = myRoles.indexOf(item.name)
            if (tempIndex > -1) {
              curRole = myRoles[tempIndex]
            }
          }
          app.globalData.curRole = curRole
          if (curRole === '企业管理' || curRole === '企业员工') {
            wx.request({
              url: app.globalData.appBaseUrl + '/api/thCompany/query',
              method: 'get',
              header: {
                Authorization: app.globalData.Authorization
              },
              data: {
                companyId: app.globalData.companyId
              },
              success: (res) =>{
                console.log(res.data, 'thCompany/query')
                if (res.data && res.data.length > 0) {
                  console.log(this.data, 'this.data')
                  app.globalData.companyName = res.data[0].companyName
                }
              }
            })
          }
          // 保存 用户名 密码
          // wx.setStorageSync('username', this.data.login1Username)
          // wx.setStorageSync('password', encrypt(this.data.login1Password))
          // 
          wx.redirectTo({
            url: '/pages/home/home',
            success: () => {
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1000
              })
            }
          })
        } else if (res.statusCode === 401 || res.statusCode === 400){
          if (res.statusCode === 400 && (res.data.message.indexOf('用户名或密码错误') > -1)) {
            wx.showToast({
              title: '用户名密码错误',
              icon: 'error',
              duration: 2000
            })
            return
          } 
          wx.showToast({
            title: '验证码过期',
            icon: 'error',
            duration: 2000
          })
          this.getCode()
        } else {
          wx.showToast({
            title: '发生错误',
            icon: 'error',
            duration: 2000
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: "请输入错误的信息",
          icon: 'error',
          duration: 2000
        })
      },
      complete: () => {
        this.setData({
          isLogin1Loading: false
        })
      }
    })
  }
})