<template>
  <div class="login">
    <div class="login-bg">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <i class="el-icon-setting"
           @click="editHostEvent"
           style="float: right; margin-top: -17px; margin-right: -10px; cursor: pointer; display: none;"></i>
        <h3 class="title">{{ applicationName }}</h3>
        <div class="title-bg"></div>
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              type="text"
              auto-complete="off"
              placeholder="帐号"
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
              v-model="loginForm.code"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <el-form-item prop="ip">
          <el-input
              v-model="loginForm.ip"
              type="text"
              auto-complete="off"
              placeholder="IP地址"
          >
            <svg-icon slot="prefix" icon-class="ip" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="port">
          <el-input
              v-model="loginForm.port"
              type="text"
              auto-complete="off"
              placeholder="端口号"
          >
            <svg-icon slot="prefix" icon-class="port" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" v-if="rememberMeView" style="margin:0px 0px 25px 0px;">记住帐号
        </el-checkbox>
        <el-form-item style="width:100%;">
          <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登录中</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © {{ copyrightDate }} 重庆川仪控制系统有限公司版权所有</span>
    </div>

  </div>
</template>

<script>
import cqcyCode from '@/utils/cqcyCode'
import {getCode} from '@/api/user'
import {showAlertMsgWin, showAlertWin, showLoading, showPromptWin, testHost} from '@/utils/cqcy'

export default {
  name: "Login",
  inject: ['getWebSocket'],
  data() {
    /** 表单验证判断：空格 */
    let testKeyBySpace = (rule, value, callback) => {
      if (!value || !value.trim()) {
        if (rule.field === 'username') {
          callback(new Error('帐号不能为空'))
        } else {
          callback(new Error('验证码不能为空'))
        }
      } else {
        callback()
      }
    }
    return {
      codeUrl: "",
      publicKey: "",
      loginForm: {
        username: "",
        password: "",
        ip: "127.0.0.1",
        port: "8081",
        rememberMe: false,
        code: "",
        uid: "",
        publicKey: ""
      },
      loginRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的帐号"},
          {validator: testKeyBySpace}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [
          {required: true, trigger: "change", message: "请输入验证码"},
          {validator: testKeyBySpace}
        ],
        ip: [
          {required: true, message: '请输入IP地址', trigger: 'blur'},
          {validator: this.testKeyByIp}
        ],
        port: [
          {required: true, message: '请输入端口号', trigger: 'blur'},
          {validator: this.testKeyByPort}
        ],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: false,
      // 注册开关
      register: false,
      // 记住帐号开关
      rememberMeView: true,
      // 版权信息
      copyrightDate: new Date().getFullYear(),
      applicationName: '',
      dialogServerVisible: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        // this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    // this.getCode();
    this.getCookie();
    this.applicationName = process.env.VUE_APP_SOFTWARENAME
  },
  methods: {
    /** 表单验证判断：IP */
    testKeyByIp(rule, value, callback) {
      const key = /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/
      if (!key.test(value)) {
        callback(new Error('IP 地址不合法'))
      } else {
        callback()
      }
    },
    /** 表单验证判断：端口 */
    testKeyByPort(rule, value, callback) {
      const key = /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/
      if (!key.test(value)) {
        callback(new Error('端口号不合法'))
      } else {
        callback()
      }
    },
    /** 获取验证码 */
    getCode(callback) {
      const loading = showLoading(this, '正在初始化环境···')
      getCode(true).then(res => {
        loading.close()
        this.captchaEnabled = res.captchaEnabled === undefined ? this.captchaEnabled : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + data.verifyCode;
        }
        let data = res.data;
        this.loginForm.uid = data.uid;
        this.loginForm.publicKey = data.publicKey;
        if (callback) callback(true)
      }).catch((e) => {
        loading.close()
        showAlertWin(this, null, e)
        if (callback) callback(false)
      })
    },
    /** 获取记住的帐号信息 */
    getCookie() {
      const username = localStorage.getItem('J_USER_NAME')
      const rememberMe = localStorage.getItem('J_BTN')
      const ip = localStorage.getItem('REQ_IP')
      const port = localStorage.getItem('REQ_PORT')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        ip: ip ? ip : this.loginForm.ip,
        port: port ? port : this.loginForm.port
      };
    },
    /** 登录 */
    handleLogin() {
      let _this = this
      _this.$refs.loginForm.validate(valid => {
        if (valid) {
          localStorage.setItem('REQ_IP', _this.loginForm.ip)
          localStorage.setItem('REQ_PORT', _this.loginForm.port)
          let h = _this.loginForm.ip + ':' + _this.loginForm.port
          localStorage.setItem('SYS_HOST', cqcyCode['protocol'] + h)
          localStorage.setItem('SYS_HOST_BASE', h)
          if (_this.loginForm.rememberMe) {
            localStorage.setItem('J_USER_NAME', _this.loginForm.username)
            localStorage.setItem('J_BTN', 'true')
          } else {
            localStorage.removeItem('J_USER_NAME')
            localStorage.removeItem('J_BTN')
          }
          if (!_this.loginForm.publicKey) {
            _this.getCode((result) => {
              if (!result) {
                // const msg = cqcyCode[900];
                // Message.error(msg)
                return
              }
              _this.withLogin()
            })
            return
          }
          _this.withLogin()
        }
      });
    },
    withLogin() {
      this.loading = true;
      this.$store.dispatch('user/Login', this.loginForm).then(() => {
        this.getWebSocket.initWebSocket()
        this.$router.push({path: this.redirect || '/', query: {}})
        this.loading = false
      }).catch((e) => {
        showAlertWin(this, null, e)
        this.loading = false
        if (this.captchaEnabled) {
          this.getCode()
        }
      })
    },
    /** 设置服务端请求地址 */
    editHostEvent() {
      let sysHost = localStorage.getItem('SYS_HOST')
      showPromptWin(this, null, '请输入服务端地址', sysHost, (val) => {
        if (!testHost(val)) {
          return '请输入合法的地址信息'
        }
      }, (value) => {
        localStorage.setItem('SYS_HOST', value)
        // localStorage.setItem('SYS_HOST_BASE', value)
        showAlertMsgWin(this, null, '设置成功！')
        setTimeout(() => {
          window.location.reload()
        }, 500)
      })
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  height: 100%;
  background-image: url("../assets/images/cqcybg.png");
  background-size: cover;
}

.title {
  margin: 0px auto 5px auto;
  text-align: center;
  font-weight: 600;
  color: black;
}

.title-bg {
  height: 4px;
  width: 35px;
  background: #1890ff;
  margin: auto auto 25px;
}

.login-bg {
  display: flex;
  justify-content: flex-end;
  height: 100%;
  align-items: center;
  margin-right: 10%;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  height: 425px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #4a4a4a;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
</style>
