<template>
  <el-form
    ref="formRef"
    :show-label="false"
    :show-require-mark="false"
    size="large"
    :model="formInline"
    :rules="rules"
  >
    <el-form-item prop="username">
      <el-input v-model="formInline.username" placeholder="请输入登录账号">
        <template #prefix>
          <el-icon class="el-input__icon" size="18" color="#808695">
            <PersonOutline />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="formInline.password"
        type="password"
        show-password
        placeholder="请输入登录密码"
        @keyup.enter="handleSubmit"
      >
        <template #prefix>
          <el-icon class="el-input__icon" size="18" color="#808695">
            <Lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <div style="display: flex">
        <el-input @keyup.enter="handleSubmit" v-model.trim="formInline.code" placeholder="验证码">
          <template #prefix>
            <el-icon class="el-input__icon" size="18" color="#808695">
              <SafetyCertificateOutlined />
            </el-icon>
          </template>
        </el-input>
        <img
          style="
            width: 108px;
            height: 40px;
            border-radius: 4px;
            margin-left: 8px;
            border: 2px solid var(--el-border-color);
            cursor: pointer;
          "
          @click="getCaptcha"
          v-if="captchaImg"
          :src="captchaImg"
        />
      </div>
    </el-form-item>

    <div class="flex items-center justify-between forget">
      <div class="flex-initial">
        <el-checkbox v-model:checked="autoLogin">记住密码</el-checkbox>
      </div>
    </div>

    <el-form-item :show-label="false">
      <el-button
        class="w-full"
        type="primary"
        @click="handleSubmit"
        size="large"
        :loading="loading"
      >
        登录
      </el-button>
    </el-form-item>
  </el-form>
  <div class="flex items-center justify-between">
    <div class="flex items-center">
      <span>其他登录方式</span>
      <el-icon
        class="el-input__icon"
        size="22"
        color="#165DFF"
        style="margin: 0 10px 0 10px; cursor: pointer"
      >
        <GithubFilled />
      </el-icon>
      <el-icon class="el-input__icon" size="22" color="#165DFF" style="cursor: pointer">
        <AlipayCircleFilled />
      </el-icon>
    </div>
    <div style="cursor: pointer" @click="goRegister">注册账号</div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { ElMessage } from 'element-plus';
  import { ResultEnum } from '@/enums/httpEnum';
  import { getInfoCaptcha } from '@/api/system/user';
  import { PageEnum } from '@/enums/pageEnum';
  import { PersonOutline } from '@vicons/ionicons5';
  import { SafetyCertificateOutlined, GithubFilled, AlipayCircleFilled } from '@vicons/antd';
  const captchaImg = ref('');
  // 动态加载滑块验证码组件

  /**
   * 定义表单接口
   */
  interface FormState {
    username: string;
    password: string;
    code: string;
    key: string;
  }

  /**
   * 定义参数
   */
  const emit = defineEmits(['backLogin']);
  const formRef = ref();
  const loading = ref(false);
  const autoLogin = ref(true);
  const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;

  /**
   * 定义表单参数
   */
  const formInline = reactive({
    username: '',
    password: '',
    code: '',
    key: '',
  });

  /**
   * 定义验证规则
   */
  const rules = {
    username: { required: true, message: '请输入登录账号', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' },
    code: { required: true, message: '请输入验证码', trigger: 'blur' },
  };

  /**
   * 执行提交表单
   */
  const userStore = useUserStore();
  const router = useRouter();
  const route = useRoute();
  const handleSubmit = () => {
    if (!formRef.value) return;
    formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        const params: FormState = {
          username: formInline.username,
          password: formInline.password,
          code: formInline.code,
          key: formInline.key,
          // grant_type:"password"
        };
        try {
          const { code, msg } = await userStore.login(params);
          if (code == ResultEnum.SUCCESS) {
            const toPath = decodeURIComponent((route.query?.redirect || '/') as string);
            ElMessage.success('登录成功，即将进入系统');
            if (route.name === LOGIN_NAME) {
              router.replace('/');
            } else router.replace(toPath);
          } else {
            getCaptcha();
            ElMessage.error(msg || '登录失败');
          }
        } finally {
          loading.value = false;
        }
      } else {
        ElMessage({
          message: '请填写完整信息',
          type: 'error',
        });
      }
    });
  };

  /**
   * 获取验证码
   */
  const getCaptcha = async () => {
    let { key, captcha } = await getInfoCaptcha();
    formInline.key = key;
    captchaImg.value = captcha;
  };

  /**
   * 定义去注册
   */
  const goRegister = () => {
    emit('backLogin', false);
  };

  /**
   * 调用获取验证码方法
   */
  getCaptcha();
</script>

<style lang="scss" scoped>
  .forget {
    margin-bottom: 16px;
    margin-top: -10px;
  }
</style>
<style lang="scss">
  input:-webkit-autofill,
  textarea:-webkit-autofill,
  select:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px transparent inset !important;
    background-color: transparent !important;
    background-image: none;
    transition: background-color 50000s ease-in-out 0s;
  }
</style>
