<template>
<div class="login" id="login">
  <div class="limiter">
    <div class="container-login100">
      <div class="wrap-login100">
					<span class="login100-form-title p-b-26">{{$t('title')}}</span>
          <span class="login100-form-title p-b-48">
						<i class="fa fa-video-camera"></i>
					</span>

          <div class="wrap-input100 validate-input" data-validate = "Valid email is: a@b.c">
            <input :class="'input100 ' + (username==''?'':'has-val')" type="text" v-model="username" name="username">
            <span class="focus-input100" :data-placeholder="$t('username')"></span>
          </div>

          <div class="wrap-input100 validate-input" data-validate="Enter password">
						<span class="btn-show-pass">
							<i :class="'fa ' + (!showPassword?'fa-eye':'fa-eye-slash')" @click="showPassword = !showPassword"></i>
						</span>
            <input :class="'input100 ' + (password==''?'':'has-val')" :type="(!showPassword?'password':'text')" v-model="password" name="password">
            <span class="focus-input100" :data-placeholder="$t('password')"></span>
          </div>

          <div class="container-login100-form-btn">
            <div class="wrap-login100-form-btn" :class="{'login-loading': isLoging}" v-loading="isLoging"
                 element-loading-background="rgb(0 0 0 / 0%);" element-loading-custom-class="login-loading-class">
              <div class="login100-form-bgbtn"></div>
              <button class="login100-form-btn" @click="handleClick">
                {{ isDefault ? $t("register") : $t('login')  }}
              </button>
            </div>
          </div>
        <div class="text-center p-t-10">
          <el-dropdown class="dropdown-lang mt-2">
            <span>
              <svg-icon class="text-xl" icon-class="global"></svg-icon>
              <span class="ml-1">{{$t('lang')}}</span>
            </span>

            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                  v-for="lang in langList() "
                  :key="lang.value"
                  @click.native="changeLang(lang.value)">
                {{lang.label}}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
<!--          下拉菜单选择语言-->

      </div>
    </div>
  </div>
</div>
</template>

<script>
import crypto from 'crypto'
import api_user from "@/apiStore/api_user";
import userService from "./service/UserService";
import handle from "@/until/handle";
import querystring from "querystring";
import {langList, loadLanguageAsync} from "../assets/i18/i18n";

export default {
  name: 'Login',
  data() {
    return {
      isLoging: false,
      showPassword: false,
      loginLoading: false,
      username: '',
      password: '',
      isDefault: false,
    }
  },
  created() {
    var that = this;
    document.onkeydown = function (e) {
      var key = window.event.keyCode;
      if (key == 13) {
        that.handleClick();
      }
    }
  },
  beforeMount() {
    this.executeIsDefault()
  },
  methods: {
    langList() {
      return langList
    },
    changeLang(lang) {
      loadLanguageAsync(lang)
    },

    async executeIsDefault() {
      let url = "/api/user/default"
      let [err, res] = await handle(
          this.$axios.get(url)
      )
      if (err) {
        this.$message.error(`获取服务器信息失败`);
        return;
      }
      let response = res.data
      if (response.code !== 0) {
        this.$message.error(`获取服务器信息失败 ${response.msg}`);
        return;
      }
      if (response.data) {
        this.$message.success("没有管理员账户, 开始注册管理员账户")
        this.$notify({
          title: '提示',
          message: '没有管理员账户, 请先注册账户',
          duration: 0
        });
        this.isDefault = true;
      }
    },
    //登录请求
    async toLogin() {
      //需要想后端发送的登录参数
      let loginParam = {
        username: this.username,
        password: crypto.createHash('md5').update(this.password, "utf8").digest('hex')
      }
      let that = this;
      //设置在登录状态
      this.isLoging = true;
      let timeoutTask = setTimeout(()=>{
        this.$message.error("登录超时");
        this.isLoging = false;
      }, 2000)
      let [error,res] = await api_user.login(this,loginParam);
      this.isLoging = false;
      if(error){
        console.log(error)
        window.clearTimeout(timeoutTask)
        that.$message.error(error.response.data.msg);
        return;
      }
      window.clearTimeout(timeoutTask)
      console.log(JSON.stringify(res));
      if (res.data.code === 0 ) {
         userService.setUser(res.data.data)
        //登录成功后
        that.cancelEnterkeyDefaultAction();
        await that.$router.push('/');
      } else {
        that.isLoging = false;
        that.$message({
          showClose: true,
          message: '登录失败，用户名或密码错误',
          type: 'error'
        });
      }
    },
    async executeRegister() {
      let url = "/api/user/register"
      let loginParam = {
        username: this.username,
        password: crypto.createHash('md5').update(this.password, "utf8").digest('hex')
      }
      loginParam = querystring.stringify(loginParam)
      let [err, res] = await handle(
          this.$axios.post(url, loginParam))
      if (err) {
        this.$message.error(`注册账户失败`);
        console.log(err);
        return;
      }
      let response = res.data
      if (response.code !== 0) {
        this.$message.error(`注册账户失败 ${response.msg}`);
        return;
      }
      this.$message.success("管理员账户注册成功")
      this.isDefault = false;
    },
    handleClick() {
      if (this.username == '' || this.password == '') {
        this.$message.warning("请输入账号密码");
        return;
      }
      if (this.isDefault) {
        this.executeRegister()
      } else {
        this.toLogin()
      }
    },
    setCookie: function (cname, cvalue, exdays) {
      let d = new Date();
      d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
      let expires = "expires=" + d.toUTCString();
      console.info(cname + "=" + cvalue + "; " + expires);
      document.cookie = cname + "=" + cvalue + "; " + expires;
      console.info(document.cookie);
    },
    cancelEnterkeyDefaultAction: function () {
        document.onkeydown = function(e) {
        let key = window.event.keyCode;
        if (key == 13) {
          return false;
        }
      }
    }
  }
}
</script>

