<template>
  <div class="login-container">
    <div class="login-form">
      <img :src="exitIcon" alt="关闭" class="exit-icon" @click="emit('close')" />
      <header class="login-form__header">
        <span>{{ props.title }}</span>
      </header>
      <main class="login-form__main">
        <el-form
          ref="formRef"
          :model="formValue"
          label-width="auto"
          class="login-form__form"
          @keydown.enter="handleLogin"
        >
          <el-form-item prop="username" :rules="[{ required: true, message: '账号不能为空' }]">
            <el-input
              placeholder="请输入您的账号"
              v-model="formValue.username"
              type="text"
              autocomplete="off"
              clearable
              class="el-input--default"
            />
          </el-form-item>
          <el-form-item prop="password" :rules="[{ required: true, message: '密码不能为空' }]">
            <el-input
              :placeholder="'请输入您的密码'"
              v-model="formValue.password"
              type="password"
              autocomplete="off"
              show-password
              clearable
              class="el-input--default"
            />
          </el-form-item>

          <!-- <el-form-item
            prop="code"
            :rules="[{ required: true, message: '验证码不能为空' }]"
            v-if="type !== 'modifyPassword'"
          >
            <el-input placeholder="验证码" v-model="formValue.code" clearable class="el-input--default" />
          </el-form-item> -->
        </el-form>
      </main>
      <footer class="login-form__footer">
        <el-button class="login-form__button" @click="handleLogin">登录</el-button>
      </footer>
    </div>
    <SliderCaptcha
      v-if="showCaptcha"
      captchaType="blockPuzzle"
      mode="pop"
      @success="handleCaptchaPassed"
      ref="sliderCaptchaRef"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { FormInstance } from 'element-plus';
  import md5 from 'blueimp-md5';
  import exitIcon from 'assets/svg/exit.svg';
  import { useUserStore } from '@/store/modules/user';
  import { PWD_KEY } from '@/utils/pwd';
  import SliderCaptcha from '@/components/Login/components/slider-captcha/Verify.vue';
  import { useGlobSetting } from '@/hooks/setting';

  const props = defineProps<{ title: string }>();
  const { showCaptcha } = useGlobSetting();

  const userStore = useUserStore();

  const formValue = reactive({
    username: userStore.info.username,
    password: '',
    captchaVerification: '',
  });
  const sliderCaptchaRef = ref<InstanceType<typeof SliderCaptcha>>();

  const emit = defineEmits<{ (e: 'close'): unknown; (e: 'success'): unknown }>();
  const formRef = ref<FormInstance>();

  // const handleLogin = () => {
  //   if (!formRef.value) return;
  //   formRef.value.validate((valid: boolean) => {
  //     if (valid) {
  //       console.log('valid', formValue);
  //       formValue.password = md5(PWD_KEY + formValue.password);
  //       userStore
  //         .login(formValue)
  //         .then(() => {
  //           emit('success');
  //           // window.location.reload();
  //         })
  //         .catch((err) => {
  //           ElMessage.error(err.message || '登录失败');
  //         });
  //     }
  //   });
  // };

  const handleLogin = () => {
    if (!formRef.value) return;
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        if (showCaptcha) {
          sliderCaptchaRef.value?.show();
        } else {
          onLogin();
        }
      }
    });
  };

  const handleCaptchaPassed = ({ captchaVerification }: { captchaVerification: string }) => {
    onLogin(captchaVerification);
  };

  const onLogin = (vification?: string) => {
    console.log('valid', formValue);

    const encryptedPwd = md5(PWD_KEY + formValue.password);
    const loginParams = {
      ...formValue,
      captchaVerification: vification || undefined,
      password: encryptedPwd, // 替换为加密后的密码
    };
    userStore
      .login(loginParams)
      .then(() => {
        emit('success');
      })
      .catch((err) => {
        ElMessage.error(err.message || '登录失败');
      });
  };
</script>

<style lang="scss" scoped>
  .login-container {
    @include flex-center;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.42);
    z-index: 1000;
  }
  .login-form {
    position: relative;
    width: 420px;
    padding: 0 20px;
    background: $white-color;
    border-radius: 14px;
    &__header {
      width: 100%;
      height: 80px;
      font-size: 16px;
      font-weight: 550;
      color: #333;
      text-align: center;
      line-height: 80px;
      letter-spacing: 5px;
    }
    &__main {
      @include flex-center;
      flex-direction: column;
      gap: 20px;
    }
    &__code {
      @include flex-center;
      justify-content: space-between;
      width: 100%;
      height: 44px;
      .el-input--default {
        width: 50%;
      }
    }
    &__footer {
      width: 100%;
      height: 66px;
      margin-top: 18px;
      .login-form__button {
        width: 100%;
        height: 44px;
        font-size: 16px;
        color: $white-color;
        background-color: $primary-color;
        border-radius: 5px;
        cursor: pointer;
      }
    }
    .exit-icon {
      position: absolute;
      top: 15px;
      right: 16px;
      width: 24px;
      height: 24px;
      cursor: pointer;
    }
  }
  .login-form__form {
    display: flex;
    flex-direction: column;
    gap: 2px;
    width: 100%;
  }
  .el-input--default {
    width: 100%;
    height: 44px;
    :deep(.el-input__inner) {
      font-size: 14px;
      color: #999;
    }
  }
</style>
