<template>
  <div class="login-wrap">
    <!-- <img
      class="login-wrap-icon"
      src="../assets/img/login-wrap-icon.png"
      draggable="false"
    /> -->
    <div class="login-content">
      <div class="ms-title">
        <div style="margin-bottom: 20px">综合报警系统</div>
        <div style="padding-bottom: 40px; font-size: 24px">
          Integrated alarm system
        </div>
      </div>
      <div class="ms-login">
        <div class="ms-login-title">欢迎登录</div>
        <el-form
          :model="userInfo"
          :rules="rules"
          ref="login"
          label-width="0px"
          class="ms-content"
        >
          <el-form-item prop="username" style="margin-bottom: 30px">
            <el-input
              v-model="userInfo.username"
              size="large"
              placeholder="请输入用户名"
            >
              <template #prepend>
                <el-button icon="el-icon-user"></el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password" style="margin-bottom: 30px">
            <el-input
              type="password"
              placeholder="请输入密码"
              size="large"
              v-model="userInfo.password"
              @keyup.enter="submitForm()"
            >
              <template #prepend>
                <el-button icon="el-icon-lock"></el-button>
              </template>
            </el-input>
          </el-form-item>
          <div class="login-btn">
            <el-button type="primary" size="large" @click="submitForm()"
              >登录</el-button
            >
          </div>
          <!-- <p class="login-tips">初始账号密码为admin</p> -->
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { JSEncrypt } from "jsencrypt";
import { loginRequest, getPublickey, Login, getUserinfo } from "/@/api/api.js";
const router = useRouter();
const login = ref(null);
const store = useStore();
const userInfo = reactive({
  username: "",
  password: "",
});

const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

onMounted(async () => {
  store.commit("emptyWarning");
  await getkey();
  store.commit("clearTags");
  //使用
  const locationHeBei = await GetQueryString("u");
  console.warn(locationHeBei);
  if (locationHeBei) {
    userInfo.username = "admin";
    userInfo.password = "admin";
    loginFun();
  }
});
// 截取URL字段属性
const GetQueryString = (name) => {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
};
// 获取公钥
const getkey = async () => {
  const key = await getPublickey();
  sessionStorage.setItem("publicKey", key);
};
// 利用jsencrypt.js进行RSA加密
const encryptionByPublickey = (formData) => {
  let key = sessionStorage.getItem("publicKey");
  var encrypt = new JSEncrypt();
  encrypt.setPublicKey(key);

  var result = encrypt.encrypt(JSON.stringify(formData));
  return result;
};

const toUtf8 = (str) => {
  return new TextEncoder("utf8").encode(str);
};

const submitForm = () => {
  login.value.validate((valid) => {
    if (valid) {
      loginFun();
    } else {
      ElMessage.error("请输入账号和密码");
      return false;
    }
  });
};
const loginFun = async () => {
  //   let requestWrapper = {
  //     publicKey: sessionStorage.getItem("publicKey"),
  //     data: encryptionByPublickey(userInfo),
  //   };
  const { data: res, msg, code } = await loginRequest({ ...userInfo });
  if (code == 0) {
    // sessionStorage.setItem("ms_username", res.data.userName);
    // sessionStorage.setItem("ms_chinesename", res.data.chineseName);
    store.commit("user/SET_TOKEN", res);
    // sessionStorage.setItem("ms_id", res.userId);
    // sessionStorage.setItem("token", res.token);
    Login({ userId: res.userId, token: res.accessToken }).then((res) => {
      if (res.code == 200) {
        ElMessage.success("登录成功");
      }
    });
  } else {
    ElMessage.error(msg);
  }
  router.push("/");
};
</script>

<style lang="scss" scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url("../assets/img/bg.png");
  background-size: 100%;
  .login-content {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .ms-title {
      flex: 1;
      margin-left: 20vw;
      font-size: 50px;
      color: #dadada;
      padding: 10px;
      padding-left: 20px;
      border-left: 4px solid #fff;
      align-self: flex-start;
      margin-top: 36vh;
    }
    .ms-login {
      margin-right: 22vw;
      width: 20vw;
      border-radius: 20px;
      background-color: #1a1a1aa1;
      overflow: hidden;
      .ms-login-title {
        font-size: 24px;
        color: #fff;
        padding: 10px;
        width: 100%;
        text-align: center;
        border-bottom: 2px solid rgb(31, 31, 31);
      }
    }
    .ms-content {
      padding: 30px 30px;
    }
    .login-btn {
      text-align: center;
    }
    .login-btn button {
      width: 100%;
      height: 36px;
      margin-bottom: 20px;
    }
  }
}
</style>
