<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';

import { computed, h, onMounted, onUnmounted, ref } from 'vue';

import { AuthenticationLogin, z } from '@vben/common-ui';
// import type { BasicOption } from '@vben/types';
import { $t } from '@vben/locales';
import { useStorage } from '@vben/utils';

import { v4 as uuidv4 } from 'uuid';

import { useAuthStore } from '#/store';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();

// const MOCK_USER_OPTIONS: BasicOption[] = [
//   {
//     label: 'Super',
//     value: 'vben',
//   },
//   {
//     label: 'Admin',
//     value: 'admin',
//   },
//   {
//     label: 'User',
//     value: 'jack',
//   },
// ];

// 图形验证码
const captchaUrl = ref('');
const uuidString = ref('');

const getCaptcha = async () => {
  try {
    const uuid = uuidv4();
    uuidString.value = uuid;
    const res = await authStore.getLoginCaptcha({ uuid });
    const blob = new Blob([res], { type: 'image/jpeg' });
    captchaUrl.value = URL.createObjectURL(blob);
  } catch (error) {
    console.error('Captcha error:', error);
  } finally {
    const storage = useStorage('captcha-uuid');
    storage.setItem(uuidString.value);

    // const key = useNamespace('captcha-uuid').b();
    // storage.setItem(key, {
    //   uuid: uuidString.value,
    // });
  }
};

onMounted(async () => {
  await getCaptcha();
});

onUnmounted(() => {
  if (captchaUrl.value) {
    URL.revokeObjectURL(captchaUrl.value);
  }
});

const formSchema = computed((): VbenFormSchema[] => {
  return [
    // {
    //   component: 'VbenSelect',
    //   componentProps: {
    //     options: MOCK_USER_OPTIONS,
    //     placeholder: $t('authentication.selectAccount'),
    //   },
    //   fieldName: 'selectAccount',
    //   label: $t('authentication.selectAccount'),
    //   rules: z
    //     .string()
    //     .min(1, { message: $t('authentication.selectAccount') })
    //     .optional()
    //     .default('vben'),
    // },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.username'),
      },
      // dependencies: {
      //   trigger(values, form) {
      //     if (values.selectAccount) {
      //       const findUser = MOCK_USER_OPTIONS.find(
      //         (item) => item.value === values.selectAccount,
      //       );
      //       if (findUser) {
      //         form.setValues({
      //           password: '123456',
      //           username: findUser.value,
      //         });
      //       }
      //     }
      //   },
      //   triggerFields: ['selectAccount'],
      // },
      fieldName: 'username',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.password'),
      },
      fieldName: 'password',
      label: $t('authentication.password'),
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
    },
    // 图形验证码
    {
      component: 'ElInput',
      componentProps: {
        placeholder: $t('authentication.captcha'),
        size: 'large',
        class: 'captcha-input-box',
      },
      fieldName: 'captcha',
      label: $t('authentication.captcha'),
      rules: z.string().min(4, { message: $t('authentication.captchaTip') }),
      renderComponentContent: () => ({
        suffix: () =>
          h('img', {
            src: captchaUrl.value,
            style: {
              width: '90px',
              height: '35px',
              marginLeft: '0px!important',
            },
            // 添加点击事件
            onClick: async (e) => {
              e.stopPropagation();
              e.preventDefault();
              await getCaptcha();
            },
          }),
      }),
    },
    // {
    //   component: markRaw(SliderCaptcha),
    //   fieldName: 'captcha',
    //   rules: z.boolean().refine((value) => value, {
    //     message: $t('authentication.verifyRequiredTip'),
    //   }),
    // },
  ];
});
</script>

<template>
  <AuthenticationLogin
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    @submit="authStore.authLogin"
  />
</template>

<style lang="scss" scoped>
:deep(.captcha-input-box) {
  .el-input__wrapper {
    padding-right: 2px !important;

    img {
      cursor: pointer;
      border-radius: 5px;
    }
  }
}
</style>
