<template>
  <div class="container">
    <n-form ref="formRef" label-placement="left" :label-width="100" :model="form" :rules="rules" size="large" require-mark-placement="left">
      <n-form-item path="loginCode">
        <n-input v-model:value="form.loginCode" :placeholder="t('common.login.usernameTip')">
          <template #prefix>
            <span class="bqfl-iconfont icon-yonghuming"></span>
          </template>
        </n-input>
      </n-form-item>
      <n-form-item path="password">
        <n-input v-model:value="form.password" type="password" show-password-on="click" :placeholder="t('common.login.passwordTip')">
          <template #prefix>
            <span class="bqfl-iconfont icon-mima"></span> </template></n-input>
        <a href="#" class="forgot" @click="handleForgot"> {{t('common.login.forgetPassword')}}</a>
      </n-form-item>
      <n-form-item path="validCode">
        <n-input v-model:value="form.validCode" :placeholder="t('common.login.validCodeTip')">
          <template #prefix>
            <span class="bqfl-iconfont icon-yanzhengma"></span>
          </template>
          <template #suffix>
            <img :src="getValidCodeImg" @click="refreshValidCodeImg" class="cursor-pointer" width="100" />
          </template>
        </n-input>
      </n-form-item>
    </n-form>
    <n-button class="login-btn" attr-type="button" type="info" color="#18A058" :disabled="submitLoading" @click="handleLogin">
      {{ submitLoading ? t('common.login.submitting') : t('common.login.title') }}
    </n-button>
    <p class="register-btn">
      {{t('common.login.noAccount')}}
      <span @click="handleRegister">{{t('common.login.register')}}</span>
    </p>
  </div>
</template>

<script lang="ts" setup>
import { useI18n } from "#imports";
import { ref, reactive, onMounted } from "vue";
import { createDiscreteApi } from "naive-ui";
import { useUserStore } from "@/store/user";
const config = useRuntimeConfig();
const baseUrl = ref(config.public.apiBase);
const emit = defineEmits(["closeSginDialog"]);
const userStore = useUserStore();
const { t, locale, setLocale } = useI18n();
const temptime = ref();

const formRef = ref();
const submitLoading = ref(false);

const form: Login = reactive({
  loginCode: "",
  password: "",
});

const rules: FormRules = {
  loginCode: [
    {
      required: true,
      message: t("common.login.usernameTip"),
      trigger: ["input", "blur"],
    },
  ],
  password: [
    {
      required: true,
      message: t("common.login.passwordTip"),
      trigger: ["input", "blur"],
    },
  ],
  validCode: [
    {
      required: true,
      message: t("common.login.validCodeTip"),
      trigger: ["input", "blur"],
    },
  ],
};

const getValidCodeImg = ref<string>("");

const refreshValidCodeImg = () => {
  temptime.value = +new Date().getTime();
  getValidCodeImg.value =
    baseUrl.value + `/report/websiteUser/getValidCode?unTime=${temptime.value}`;
};

refreshValidCodeImg();

const message = createDiscreteApi(["message"]);

const handleLogin = () => {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      submitLoading.value = true;
      const params = JSON.parse(JSON.stringify(form));
      params.loginCode = encryptByBase64(params.loginCode);
      params.password = encryptByBase64(params.password);
      params.unTime = temptime.value;
      try {
        const { code, data } = await login_Api(params);
        if (code === 200) {
          userStore.setToken(data?.token);
          userStore.setUserInfo(data?.user);
          emit("closeSginDialog", "success");
          message.message.success(t("common.login.success"));
        } else {
          refreshValidCodeImg();
          form.validCode = "";
        }
        submitLoading.value = false;
      } catch (error) {
        submitLoading.value = false;
      }
    }
  });
};

const handleForgot = () => {
  emit("closeSginDialog", "forgot");
};

const handleRegister = () => {
  emit("closeSginDialog", "register");
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  padding: 30px 20px;

  .login-btn {
    width: 100%;
    height: 50px;
    color: #fff;
    font-size: 18px;
    border-radius: 8px;
  }
  .register-btn {
    font-size: 18px;
    color: #808080;
    text-align: center;

    span {
      color: #f0a226;
      cursor: pointer;
    }
  }

  .forgot {
    margin-left: 10px;
    font-size: 14px;
    color: #00c2ff;
    text-decoration: underline;
    flex-shrink: 0;
  }

  .cursor-pointer {
    cursor: pointer;
  }

  :deep(input::-ms-reveal) {
    display: none;
  }
}
</style>
