<template>
  <div class="login-page">
    <!-- 登陆表单 -->
    <el-form :model="loginForm" :rules="rules" status-icon ref="ruleForm" class="my-login-form">
      <!-- logo -->
      <el-row type="flex" class="login-logo" justify="center">
        <!-- <img src="../assets/images/jvchat.png" alt srcset /> -->
        <span>企聊客服系统</span>
      </el-row>
      <!-- type -->
      <div class="client-server">
        <div
          class="client-server-item radius-left"
          :class="{ 'client-chose': clientOrServer === 'client' }"
          @click="setCurrentClient('client')"
        >
          客户端登陆
        </div>
        <div
          class="client-server-item radius-right"
          :class="{ 'client-chose': clientOrServer === 'server' }"
          @click="setCurrentClient('server')"
        >
          管理端登陆
        </div>
      </div>
      <!-- 用户名 -->
      <el-form-item prop="name">
        <el-input
          v-model="loginForm.name"
          :maxlength="'20'"
          placeholder="输入用户名"
          prefix-icon="el-icon-user"
          @input="changeName()"
        ></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="pass">
        <el-input
          type="password"
          v-model="loginForm.pass"
          autocomplete="off"
          show-password
          placeholder="输入密码"
          :maxlength="20"
          prefix-icon="el-icon-unlock"
        ></el-input>
      </el-form-item>
      <!-- 记住密码 && 本地调试 -->
      <el-row type="flex" justify="space-around">
        <el-checkbox v-model="rememberPwd">记住密码</el-checkbox>
      </el-row>
      <!-- 登录 -->
      <el-form-item class="login_btn_box">
        <el-button
          style="width: 300px"
          type="primary"
          :loading="loading"
          :disabled="loading"
          class="login-btn"
          @click="submitForm('ruleForm')"
        >
          登 录
        </el-button>
      </el-form-item>
      <!-- version -->
      <span class="login-logo-version">v-{{ version }}</span>
    </el-form>
    <!-- electron 关闭按钮 -->
    <div style="-webkit-app-region: drag" v-if="currentMode === 'electron'" class="close-title">
      <el-button
        style="-webkit-app-region: no-drag"
        class="el-icon-close"
        type="text"
        @click="closeElectron"
      ></el-button>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import { deviceAuthReq } from '../api/webSocketApi'
import { login } from '../api/httpApiAdmin' // 管理端登录

export default {
  name: 'LoginPage',
  data() {
    let checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      } else {
        callback()
      }
    }
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      rememberPwd: false,
      clientOrServer: 'client',
      version: require('../../package.json').version,
      loginForm: {
        name: '',
        pass: ''
      },
      rules: {
        name: [{ validator: checkName, trigger: 'blur' }],
        pass: [{ validator: validatePass, trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapState({
      currentMode: 'currentMode', // 是pc还是web
      webSocketState: 'webSocketState' // websocket连接状态
    }),
    ...mapGetters({
      loading: 'websocket/loginLoading'
    }),
    localName() {
      if (localStorage.getItem('localNameOfJuboChat')) {
        return localStorage.getItem('localNameOfJuboChat')
      }
      return ''
    },
    localPwd() {
      if (localStorage.getItem('localPwdOfJuboChat')) {
        return localStorage.getItem('localPwdOfJuboChat')
      }
      return ''
    }
  },
  methods: {
    // 如果改变用户名 清空密码
    changeName() {
      this.loginForm.pass = ''
    },
    // 登陆
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 表单验证通过，可以登陆
          // 记住密码
          if (this.rememberPwd) {
            localStorage.setItem('localNameOfJuboChat', this.loginForm.name)
            localStorage.setItem('localPwdOfJuboChat', this.loginForm.pass)
          }
          // 显示loading
          this.$store.commit('websocket/SET_LOGIN_LOADING', true)

          if (this.clientOrServer === 'client') {
            switch (this.webSocketState) {
              case 0:
                this.$alert('websocket正在连接，请稍后再试！', '提示', { type: 'info' })
                this.$store.commit('websocket/SET_LOGIN_LOADING', false)
                break
              case 1:
                {
                  let dat = setTimeout(() => {
                    deviceAuthReq(this.loginForm.name, this.loginForm.pass)
                    clearTimeout(dat)
                    dat = null
                  }, 500)
                }
                break
              default:
                this.$alert('websocket连接失败！', '提示', { type: 'warning' })
                this.$store.commit('websocket/SET_LOGIN_LOADING', false)
                break
            }
          } else {
            login(this.loginForm.name, this.loginForm.pass)
              .then((res) => {
                console.log(res)
                this.$store.commit('websocket/SET_LOGIN_LOADING', false)
                if (res.code === 0) {
                  // if (process.env.VUE_APP_CURRENTMODE === 'electron') {
                  //   const { ipcRenderer } = window.require('electron')
                  //   ipcRenderer.send('operations', 'login')
                  // }
                  // 设置用户信息
                  this.$store.commit('SET_ADMIN_INO', res.data)
                  // 设置token
                  this.$store.commit('SET_HTTP_TOKEN', res.data.token)
                  // 跳转到后台管理页面
                  this.$router.replace({ name: 'admin' })
                }
              })
              .catch(() => {
                this.$store.commit('websocket/SET_LOGIN_LOADING', false)
              })
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 退出electron
    closeElectron() {
      this.$ipcRenderer.send('operations', 'exit')
    },
    // 设置管理端还是客服端
    setCurrentClient(flag) {
      this.clientOrServer = flag
      this.$store.commit('SET_CLIENT_OR_SERVER', flag)
    }
  },
  watch: {
    rememberPwd(val) {
      if (val) {
        localStorage.setItem('remarkPwdOfJuboChat', 1)
      } else {
        localStorage.removeItem('remarkPwdOfJuboChat')
        localStorage.removeItem('localNameOfJuboChat')
        localStorage.removeItem('localPwdOfJuboChat')
      }
    }
  },
  created() {
    // 记住密码
    if (localStorage.getItem('remarkPwdOfJuboChat')) {
      this.rememberPwd = true
      if (this.localName && this.localPwd) {
        this.loginForm.name = this.localName
        this.loginForm.pass = this.localPwd
      }
    }
    // 防抖
    this.changeName = this._.debounce(this.changeName, 300)
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  width: 100%;
  height: 100%;
  background: no-repeat;
  //   background-image: url(~@/../public/images/kdd_big_bg.png);
  background-image: url(~@/assets/images/kdd_big_bg.png);
  background-size: cover;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.my-login-form {
  float: right;
  width: 400px;
  height: 400px;
  margin-right: 10%;
  background: #fff;
  padding: 10px 50px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .client-server {
    height: 40px;
    width: 300px;
    display: flex;
    margin-bottom: 15px;
    .client-server-item {
      width: 150px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      //   border-radius: 5px;
      cursor: pointer;
      border: solid #dcdfe6 1px;
    }
    .radius-left {
      border-radius: 5px 0 0 5px;
    }
    .radius-right {
      border-radius: 0 5px 5px 0;
    }
    .client-chose {
      color: #fff;
      background-color: #409eff;
      border: solid #409eff 1px;
    }
  }

  .login-logo {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    height: 50px;

    span {
      margin-left: 20px;
      font-size: 30px;
      font-weight: 500;
    }
  }

  .login_btn_box {
    margin-bottom: 0;
    display: flex;
    justify-content: center;
    .login-btn {
      width: 150px;
    }
  }

  .login-logo-version {
    margin-top: 5px;
    color: $font-color-2;
    text-align: center;
  }

  ::v-deep .el-input-group__prepend {
    padding: 0 10px;
  }
}

.close-title {
  position: absolute;
  top: 0;
  width: 700px;
  height: 30px;
  display: flex;
  justify-content: flex-end;
  border-radius: 5px;
  .el-icon-close {
    font-size: 16px;
    padding: 0;
    margin-right: 10px;
    color: white;
    &:hover {
      color: $danger-color-base;
      font-weight: 600;
    }
  }
}

@media only screen and (max-width: 700px) {
  .login-page {
    border-radius: 5px;
    .my-login-form {
      margin-right: 10px;
      height: 350px;
      width: 350px;
      padding: 5px 20px;
      .client-server,
      .login-logo {
        margin-bottom: 5px;
      }
    }
  }
}
</style>
