<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { Crypto } from '@sa/utils';
import { fetchGetCaptcha } from '@/service/api/common';
import { fetchGetTenantOptions } from '@/service/api/auth';
import { useAuthStore } from '@/store/modules/auth';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { localStg } from '@/utils/storage';
import { $t } from '@/locales';
defineOptions({
  name: 'PwdLogin'
});
const pd = new Crypto<{ data: string }>('zhongshuweilai');

const authStore = useAuthStore();
const { formRef, validate } = useNaiveForm();
const isRememberMe = ref(false);
const imgPath = ref('');

// 租户选项
const tenantOptions = ref<{ label: string; value: string }[]>([]);
const selectedTenantCode = ref<string | null>(null);

async function loadTenantOptions() {
  const { data } = await fetchGetTenantOptions();
  if (data) {
    tenantOptions.value = (data as any[]).map((item: any) => ({
      label: item.tenantName,
      value: item.tenantCode
    }));
  }
}
loadTenantOptions();

interface FormModel {
  userName: string;
  password: string;
  captchaCode: string;
}

const model: FormModel = reactive({
  userName: '',
  password: '',
  captchaCode: ''
});

onMounted(() => {
  const userName = localStg.get('userName');
  const password = localStg.get('password');
  const obj = pd.decrypt(String(password));
  if (userName && password && obj) {
    model.userName = userName;
    model.password = obj.data;
    isRememberMe.value = true;
  }
});

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  // inside computed to make locale reactive, if not apply i18n, you can define it without computed
  const { formRules } = useFormRules();

  return {
    userName: formRules.userName,
    password: formRules.pwd,
    captchaCode: formRules.captchaCode
  };
});
const captchaKey = ref('');
async function handleSubmit() {
  await validate();
  if (!selectedTenantCode.value) {
    window.$message?.error('请选择租户');
    return;
  }
  if (isRememberMe.value) {
    const pwd = pd.encrypt({ data: model.password });
    localStg.set('userName', model.userName);
    localStg.set('password', pwd);
  }
  await authStore.login({ ...model, captchaKey: captchaKey.value, tenantCode: selectedTenantCode.value || undefined });
}
async function getDataCode() {
  const { data } = await fetchGetCaptcha();
  imgPath.value = String(data?.captchaBase64);
  captchaKey.value = String(data?.captchaId);
  model.captchaCode = '';
}
getDataCode();
watch(
  () => authStore.loginLoading,
  () => {
    if (!authStore.loginLoading) {
      getDataCode();
    }
  }
);
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
    <NFormItem :rule="{ required: true, message: '请选择租户', trigger: 'change' }">
      <NSelect v-model:value="selectedTenantCode" :options="tenantOptions" placeholder="请选择租户" />
    </NFormItem>
    <NFormItem path="userName">
      <NInput v-model:value="model.userName" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NFormItem path="imageCode">
      <NInput v-model:value="model.captchaCode" placeholder="请输入验证码" />
      <img :src="imgPath" alt="" class="ml20px h40px w220px cursor-pointer" @click="getDataCode" />
    </NFormItem>
    <NSpace vertical :size="24">
      <div class="flex-y-center justify-between">
        <NCheckbox v-model:checked="isRememberMe">{{ $t('page.login.pwdLogin.rememberMe') }}</NCheckbox>
      </div>
      <NButton type="primary" size="large" round block :loading="authStore.loginLoading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
    </NSpace>
  </NForm>
</template>

<style scoped></style>
