<!--suppress ALL -->
<template>
  <div class="login-container columnCC">
    <el-form ref="refloginForm" class="login-form" :model="formInline" :rules="formRules">
      <div class="title-container rowSS">
        <el-avatar class="appNav-avatar" :size="36" :src="imgUrl" @error="errorHandler">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
        </el-avatar>
        <h3 class="title">{{ title }}</h3>
      </div>
      <el-form-item prop="username" :rules="formRules.isNotNull">
        <el-input size="large" v-model="formInline.username" placeholder="用户名" />
      </el-form-item>
      <!--<el-form-item prop="password" :rules="formRules.passwordValid">-->
      <el-form-item prop="password" :rules="formRules.isNotNull">
        <el-input size="large" show-password ref="refPassword" v-model="formInline.password" type="password" name="password" placeholder="密码" />
      </el-form-item>
      <div class="rowSS">
        <el-form-item prop="verificationCode" :rules="formRules.isNotNull">
          <el-input size="large" @keyup.enter="handleLogin" v-model="formInline.verificationCode" placeholder="请输入验证码" />
        </el-form-item>
        <Identify :identifyCode="identifyCode" @changeCode="changeCode" style="margin-left:18px" />
      </div>
      <div class="tip-message">{{ tipMessage }}</div>
      <el-button :loading="loading" type="primary" class="login-btn" size="large" @click.prevent="handleLogin">
        登录
      </el-button>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount } from "vue";
import { GetCheckCode, gettoken, GetSystemSet } from "@/api/newLogin";
import { setCodeToken, getCodeToken } from "@/utils/auth";
import Identify from "./identify.vue";
import { ElMessage } from "element-plus";
import { ObjTy } from "~/common";
import { useUserStore } from "@/store/user";
import MD5 from "blueimp-md5";
//element valid
const formRules = useElement().formRules;
//form
let formInline = reactive({
  username: "",
  password: "",
  verificationCode: "",
});
const identifyCode = ref("");
let state: ObjTy = reactive({
  otherQuery: {},
  redirect: undefined,
});
const title = ref("系统名称");
const imgUrl = ref("https://cube.elemecdn.com/");
/* listen router change  */
const route = useRoute();
let getOtherQuery = (query: any) => {
  return Object.keys(query).reduce((acc: any, cur: any) => {
    if (cur !== "redirect") {
      acc[cur] = query[cur];
    }
    return acc;
  }, {});
};
const errorHandler = () => true;
watch(
  () => route.query,
  (query) => {
    if (query) {
      state.redirect = query.redirect;
      state.otherQuery = getOtherQuery(query);
    }
  },
  { immediate: true }
);

//获取token
onBeforeMount(() => {
  getToken();
});

const getToken = async () => {
  const { code, returnData, message } = await gettoken({
    appid: PLATFROM_CONFIG.appId,
    appSecret: PLATFROM_CONFIG.appKeyString,
  });
  if (code == 0 && returnData) {
    setCodeToken(returnData.appToken);
    getCheckCode();
    //getSystemSet();
  } else {
    ElMessage.error(message);
  }
};

//获取动态验证码
const getCheckCode = async () => {
  const { code, message, returnData } = await GetCheckCode({
    appToken: getCodeToken(),
  });
  if (code == 0) {
    identifyCode.value = returnData;
  } else {
    ElMessage.error(message);
  }
};

//切换验证码
const changeCode = () => {
  getCheckCode();
};

//获取系统设置
const getSystemSet = async () => {
  const { code, message } = await GetSystemSet({});
  if (code == 0) {
    ElMessage.success(message);
  } else {
    ElMessage.error(message);
  }
};
/*
 *  login relative
 * */
let loading = ref(false);
let tipMessage = ref("");

const refloginForm: any = ref(null);
let handleLogin = () => {
  refloginForm.value.validate((valid: any) => {
    if (valid) {
      loginReq();
    } else {
      return false;
    }
  });
};

//use the auto import from vite.config.js of AutoImport
const router = useRouter();
let loginReq = () => {
  loading.value = true;
  const params = {
    username: formInline.username.replace(/\s+/g, ""),
    password: MD5(formInline.password.replace(/\s+/g, "")),
    // password: this.loginForm.password.replace(/\s+/g, ""),
    verificationCode: formInline.verificationCode.replace(/\s+/g, ""),
  };
  const userStore = useUserStore();
  userStore
    .login(params)
    .then(() => {
      ElMessage({ message: "登录成功", type: "success" });
      sessionStorage.setItem("userName", params.username);
      router.push({ path: state.redirect || "/", query: state.otherQuery });
    })
    .catch((res) => {
      console.log(res);
      tipMessage.value = res.msg;
      useCommon()
        .sleep(30)
        .then(() => {
          getCheckCode();
          loading.value = false;
        });
    });
};
/*
 *  password show or hidden
 * */
let passwordType = ref("password");
const refPassword: any = ref(null);
let showPwd = () => {
  if (passwordType.value === "password") {
    passwordType.value = "";
  } else {
    passwordType.value = "password";
  }
  nextTick(() => {
    refPassword.value.focus();
  });
};
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-container {
  height: 100vh;
  width: 100%;
  background-image: url("../../assets/login/bg.jpg");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  .login-form {
    width: 416px;
    height: 400px;
    background: #ffffff;
    box-shadow: 0px 7px 18px 0px rgba(0, 0, 0, 0.5);
    border-radius: 8px;
    padding: 38px 46px 46px 46px;
  }
  .title-container {
    margin-bottom: 37px;
    .title {
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #303133;
      margin-left: 15px;
      line-height: 36px;
    }
  }
}

.svg-container {
  padding-left: 6px;
  color: $dark_gray;
  text-align: center;
  width: 30px;
}

//错误提示信息
.tip-message {
  color: #e4393c;
  height: 30px;
  margin-top: -12px;
  font-size: 12px;
}

//登录按钮
.login-btn {
  width: 100%;
  background-color: #ac014d;
  border-color: #ac014d;
}
.show-pwd {
  width: 50px;
  font-size: 16px;
  color: $dark_gray;
  cursor: pointer;
  text-align: center;
}
</style>

