<!-- @format -->

<template>
  <div class="login">
    <div
      style="max-width: 58.333333%"
      class="login-forget-password"
      v-if="isForgetPas"
    >
      <el-form
        ref="forgetPasswordFormRef"
        :model="forgetPasswordForm"
        :rules="forgetPasswordRules"
        class="login-form"
      >
        <h3 class="title">账号密码邮箱找回</h3>
        <el-form-item prop="userName">
          <el-input
            v-model="forgetPasswordForm.userName"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="用户名"
          >
            <template #prefix
              ><svg-icon icon-class="user" class="el-input__icon input-icon"
            /></template>
          </el-input>
          <span class="remark">请填写注册用的用户名</span>
        </el-form-item>
        <el-form-item prop="eMail">
          <el-input
            v-model="forgetPasswordForm.eMail"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="邮箱"
          >
            <template #prefix
              ><svg-icon icon-class="user" class="el-input__icon input-icon"
            /></template>
          </el-input>
          <span class="remark">请填写注册用的邮箱，密码轻松找回。</span>
        </el-form-item>
        <el-form-item>
          <el-button
            size="large"
            type="primary"
            style="width: 100%"
            round
            :loading-icon="Eleme"
            :loading="isSend"
            @click="handleResetPassword(forgetPasswordFormRef)"
          >
            <span v-if="!isSend">发 送</span>
            <span v-else>{{ loadingTime }}秒后可重新发送</span>
          </el-button>
        </el-form-item>
        <div @click="handleForgetPassword" class="back-login">
          <p>返回登录</p>
        </div>
      </el-form>
    </div>

    <div class="login-box" v-else>
      <div class="left-icon" style="width: 500px">
        <div class="titleLog">公告公示</div>
        <!--  <img :src="bnnerUrl" alt="" /> -->
        <div class="message-list">
          <div
            class="message-list-title"
            v-for="item in noticeList"
            :key="item.id"
          >
            <span class="blue-dot"></span>
            <div class="title">{{ item.noticeTitle }}</div>
            <div class="time">
              {{ dayjs(item.createTime).format("MM-DD") }}
            </div>
          </div>
        </div>
      </div>
      <div style="width: 400px">
        <el-form
          ref="loginRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
        >
          <h3 class="title">英才卡申请平台</h3>
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
              size="large"
              auto-complete="off"
              placeholder="账号"
            >
              <template #prefix
                ><svg-icon icon-class="user" class="el-input__icon input-icon"
              /></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              size="large"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter="handleLogin"
            >
              <template #prefix
                ><svg-icon
                  icon-class="password"
                  class="el-input__icon input-icon"
              /></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input
              v-model="loginForm.code"
              size="large"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter="handleLogin"
            >
              <template #prefix
                ><svg-icon
                  icon-class="validCode"
                  class="el-input__icon input-icon"
              /></template>
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </el-form-item>
          <div class="password-state">
            <el-checkbox
              v-model="loginForm.rememberMe"
              style="margin: 0px 0px 25px 0px"
              >记住密码</el-checkbox
            >
            <p class="forget-password" @click="handleForgetPassword">
              忘记密码？
            </p>
          </div>

          <el-form-item style="width: 100%; margin-bottom: 0">
            <el-button
              :loading="loading"
              size="large"
              type="primary"
              style="width: 100%"
              round
              @click.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right" v-if="register"></div>
          </el-form-item>

          <div class="register-password">
            <p>没有账户？</p>
            <p class="now">
              <router-link :to="'/register'">立即注册</router-link>
            </p>
          </div>
        </el-form>
      </div>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup>
import dayjs from "dayjs";
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";
import bnnerUrl from "@/assets/images/login-banner.png?url";
import { onUnmounted } from "vue";
import { Eleme } from "@element-plus/icons-vue";
import { ElNotification } from "element-plus";
import { sendEmail, getNotice } from "@/api/login";

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const forgetPasswordForm = reactive({
  userName: "",
  eMail: "",
});
const forgetPasswordRules = {
  userName: [
    {
      required: true,
      message: "请填写注册时的用户名",
      trigger: "blur",
    },
  ],
  eMail: [
    {
      required: true,
      message: "请填写邮箱地址",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: "请检查邮箱是否正确",
      trigger: "blur",
    },
  ],
};
const codeUrl = ref("");

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: "",
});
const forgetPasswordFormRef = ref(null);
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};
const noticeList = ref([]);
const isSend = ref(false);
const loadingTime = ref(60);

const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);
const isForgetPas = ref(false);
let timer = null;

watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

const handleLoadingTime = () => {
  if (timer) {
    clearInterval(timer);
  }
  timer = setInterval(() => {
    if (loadingTime.value <= 1) {
      isSend.value = false;
      clearInterval(timer);
    } else {
      loadingTime.value--;
    }
  }, 1000);
};

onUnmounted(() => {
  clearInterval(timer);
});

//忘记密码的函数处理
const handleForgetPassword = () => {
  isForgetPas.value = !isForgetPas.value;
};

function getCode() {
  getCodeImg().then((res) => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}
//找回密码的处理函数
const handleResetPassword = (formRef) => {
  formRef.validate((valid) => {
    if (valid) {
      sendEmail(forgetPasswordForm).then((res) => {
        isSend.value = true;
        handleLoadingTime();
        ElNotification({
          title: "提示",
          message: "我们已往您的邮箱地址中发送一封邮件，请到邮箱中查看该邮件。",
          type: "success",
        });
      });
    }
  });
};

function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore
        .login(loginForm.value)
        .then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          // router.push({ path: redirect.value || "/", query: otherQueryParams });
          router.push({
            path: "/application",
          });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
    }
  });
}

//获取公告公示
const getNoticeList = () => {
  getNotice().then((res) => {
    noticeList.value = res.rows;
  });
};

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password:
      password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}
getCode();
getCookie();
getNoticeList();
</script>

<style lang="scss" scoped>
.titleLog {
  font-size: 18px;
  color: #333;
  margin: 0;
  text-align: center;
  margin: 20px 0;
  font-weight: bold;
}
.message-list-title:hover {
  cursor: pointer;
}
.message-list-title:hover .title {
  color: #5288f4;
  text-decoration: underline;
}
.message-list-title:hover .time {
}
.message-list {
  margin-top: 20px;
  margin-left: 40px;
}
.message-list-title {
  margin: 10px 0;
  display: flex;
  align-items: center;
  position: relative;
  height: 30px;
  .blue-dot {
    display: inline-block;
    position: absolute;
    left: 5px;
    transform: translateY(-50%);
    top: 50%;
    width: 8px;
    height: 8px;
    background-color: #5288f4;
    border-radius: 50%;
    margin-right: 10px;
  }

  .title {
    color: #333;
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 75%;
    font-size: 15px;
    color: #333;
  }
}

.message-list {
  text-align: left;

  .message-item {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;

    .message-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-bottom: 5px;
    }

    .message-content {
      font-size: 14px;
      color: #666;
    }

    .message-time {
      font-size: 12px;
      color: #999;
      text-align: right;
      margin-top: 5px;
    }
  }
}

.back-login {
  cursor: pointer;
  color: #5288f4 !important;
  font-size: 0.9rem;
  &:hover {
    opacity: 0.7;
  }
}
.login-forget-password {
  width: 24%;
  height: 46%;
  background: #fff;
  box-shadow: 1.5px 3.99px 27px 0px rgba(0, 0, 0, 0.1);
  transition: 0.3s;
}
.login-box {
  display: flex;
  background: #fff;
  box-shadow: 1.5px 3.99px 27px 0px rgba(0, 0, 0, 0.1);
  transition: 0.3s;
}
.left-icon {
  border-right: 1px solid #cccccc5e;
  text-align: center;
  .time {
    font-size: 13px;
    color: #999;
    margin-top: 3px;
    margin-left: 50px;
  }
}
.register-password {
  display: flex;
  font-family: arimo;
  color: #6a6a6a;
  font-size: 0.9rem;
  margin-top: 15px;
  .now {
    cursor: pointer;
    color: #5288f4 !important;
    padding-left: 3px;
    text-decoration: underline;
    &:hover {
      opacity: 0.7;
    }
  }
}
.remark {
  color: #999;
  font-size: 12px;
}
.password-state {
  display: flex;
  height: 25px;
  justify-content: space-between;
  align-items: center;
  .forget-password {
    cursor: pointer;
    margin: 0px 0px 25px;
    font-size: 0.9rem;
    float: right;
    color: #5288f4;
    &:hover {
      opacity: 0.7;
    }
  }
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-bg.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
  font-family: "montserrat";
}

.login-form {
  padding: 60px 50px;
  border-left: 1px solid #cccccc5e;
  margin: auto;

  background-color: rgba(255, 255, 255, 0.72);
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  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: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
