<template>
  <div class="box">
    <div class="login-container">
      <div class="contain">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          class="login-form"
        >
          <div class="title-container">
            <h3 class="title">智慧校园公寓管理端</h3>
          </div>

          <el-form-item prop="user">
            <!-- <span class="svg-container">
              <div class="user"></div>
            </span> -->
            <!-- <el-input v-model="ruleForm.user" placeholder="用户名" type="text" /> -->
            <el-input v-model="ruleForm.user" placeholder="用户名">
              <template #prefix>
                <img src="../../assets/items/user.png" alt="" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="pass">
            <!-- <span class="svg-container">
              <div class="password"></div>
            </span>
            <el-input ref="password" v-model="ruleForm.pass" :type="passwordType" placeholder="密码"
              @keyup.enter.native="handleLogin" />
            <span class="show-pwd" @click="showPwd">
              <div :class="passwordType === 'password' ? 'eye_close' : 'eye'"></div>
            </span> -->
            <el-input
              v-model="ruleForm.pass"
              placeholder="密码"
              :type="passwordType"
            >
              <template #prefix>
                <img src="../../assets/items/password.png" alt="" />
              </template>
              <template #suffix>
                <span class="show-pwd" @click="showPwd">
                  <div
                    :class="passwordType === 'password' ? 'eye_close' : 'eye'"
                  ></div>
                </span>
              </template>
            </el-input>
          </el-form-item>

          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%; margin-bottom: 30px; height: 42px"
            @click="handleLogin(ruleFormRef)"
            >登录</el-button
          >
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { JSEncrypt } from "jsencrypt";
import adminApi from "@/api/admin.js";
import { useStore } from "vuex";
import axios from "axios";

const router = useRouter();
const api = ref("");
const store = useStore();
const loading = ref(false);
const ruleFormRef = ref();
const ruleForm = reactive({
  user: "",
  pass: "",
});
const passwordType = ref("password");
const checked = ref(false); // 记住密码

const rules = reactive({
  user: [{ required: true, message: "请填写用户名", trigger: "blur" }],
  pass: [{ required: true, message: "请填写密码", trigger: "blur" }],
});

const showPwd = () => {
  if (passwordType.value === "password") {
    passwordType.value = "";
  } else {
    passwordType.value = "password";
  }
  // 重新渲染后使密码框聚焦
  // this.$nextTick(() => {
  //   this.$refs.password.focus();
  // });
};

const handleLogin = (formEl) => {
  // router.push({
  //   path: `/seniorCelebrity/order`,
  // });
  // sessionStorage.setItem("sidevarItem", 1);
  // store.commit("indexUp", 1);
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      let publicKey =
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMOcPB06u5yKyQsPjfVWiWgbEIrd14kiXNNihciaVKb6HnkQvq7zpQuZ80WEX94spnUMI3iOAl/GmIvHrpGwcbB4hJbznm+PajiwnUSPuCCXA68YJF640cJKb/8KeM7WVz69OFkIEPHhVxOy4FFF5QWe/kt6zOZ19HmE+ak+5x/QIDAQAB";
      let encryptor = new JSEncrypt(); // 新建JSEncrypt对象
      encryptor.setPublicKey(publicKey); // 设置公钥
      let rsaPassWord = encryptor.encrypt(ruleForm.pass); // 对密码进行加密
      let data = {
        account: ruleForm.user,
        password: rsaPassWord,
      };
      console.log(data);

      let res;
      try {
        res = await store.dispatch("login", data);
      } catch (e) {
        console.log(e);
      }
      console.log(res,'登录');
      // // sessionStorage.setItem("name", ruleForm.pass);
      if (res == "success") {
        let roleList = JSON.parse(sessionStorage.getItem("roleList"));
        let ind=roleList[0].route
        router.push({ path: ind });
        // store.commit("indexUp", "/seniorCelebrity/order");
        // sessionStorage.setItem("username", ruleForm.user);
        sessionStorage.setItem("sidevarItem", ind);
        ElMessage({
          type: "success",
          showClose: true,
          message: "登录成功",
          center: true,
        });
        loading.value = false;
      } else {
        loading.value = false;
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.data.message,
          center: true,
        });
      }
    } else {
      return false;
    }
  });
};
const Enters = (e) => {
  // console.log("按键:", e.key);
  if (e.key == "Enter") {
    handleLogin(ruleFormRef.value);
  }
};
onMounted(() => {
  api.value = store.state.user.api;
  if (localStorage.getItem("pass") && localStorage.getItem("user")) {
    ruleForm.user = localStorage.getItem("user");
    ruleForm.pass = localStorage.getItem("pass");
    checked.value = true;
  }
  if (localStorage.getItem("user")) {
    ruleForm.user = localStorage.getItem("user");
  }
  document.addEventListener("keyup", Enters);
});
onUnmounted(() => {
  document.removeEventListener("keyup", Enters);
});
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;

.box {
  width: 100%;
  height: 100vh;
  // background: url(@/assets/login.png);
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;

  .login-container {
    width: 100vw;
    height: 100vh;
    min-width: 1280px;
    min-height: 800px;
    background: url(../../assets/items/bg.png);
    background-size: 100% 100%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;

    .contain {
      width: 71%;
      height: 65%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }

    .login-form {
      width: 37%;
      // margin-top: 310px;
      // margin-left: 600px;
      margin-right: 36px;
    }

    .el-form-item {
      // border: 1px solid rgba(255, 255, 255, 0.1);
      // background: rgba(0, 0, 0, 0.1);
      // border-radius: 5px;
      // color: #454545;

      .el-input {
        // display: inline-block;
        // border: 1px solid red;

        :deep(.el-input__wrapper) {
          width: 92%;
          height: 42px;
          background: rgba(0, 0, 0, 0.1);
          box-shadow: none;
        }

        img {
          width: 25px;
        }

        .el-input__suffix {
          img {
            cursor: pointer;
          }
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      vertical-align: middle;
      width: 30px;
      color: $bg;
      display: inline-block;

      .user {
        width: 20px;
        height: 20px;
        background: url(../../assets/items/user.png);
        background-size: 100% 100%;
      }

      .password {
        width: 20px;
        height: 20px;
        background: url(../../assets/items/password.png);
        background-size: 100% 100%;
      }
    }

    .title-container {
      position: relative;

      .title {
        font-size: 28px;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      cursor: pointer;
      user-select: none;
      color: $bg;

      .eye_close {
        margin-top: 7px;
        width: 20px;
        height: 20px;
        background: url(../../assets/items/eye_close.png);
        background-size: 100% 100%;
      }

      .eye {
        margin-top: 7px;
        width: 20px;
        height: 20px;
        background: url(../../assets/items/eye.png);
        background-size: 100% 100%;
      }
    }
  }
}
</style>
