<script setup lang="ts">
import type {EasyFlowFormSchema} from '#/adapter/form';

import {computed, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';

import {ProfilePasswordSetting, z} from '@easyflow/common-ui';
import {preferences} from '@easyflow/preferences';
import {useUserStore} from '@easyflow/stores';

import {ElMessage} from 'element-plus';

import {getCredentialKeyApi} from '#/api';
import {api} from '#/api/request';
import {$t} from '#/locales';
import {useAuthStore} from '#/store';
import {encryptCredentialPayload} from '#/utils/credential-encryption';
import {isStrongPassword} from '#/utils/password-policy';

const profilePasswordSettingRef = ref();
const authStore = useAuthStore();
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const isForcedPasswordChange = computed(() => {
  return !!userStore.userInfo?.passwordResetRequired || route.query.force === '1';
});

const formSchema = computed((): EasyFlowFormSchema[] => {
  return [
    {
      fieldName: 'password',
      label: $t('sysAccount.oldPwd'),
      component: 'EasyFlowInputPassword',
      componentProps: {
        placeholder: $t('sysAccount.oldPwd') + $t('common.isRequired'),
      },
    },
    {
      fieldName: 'newPassword',
      label: $t('sysAccount.newPwd'),
      component: 'EasyFlowInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: $t('sysAccount.newPwd') + $t('common.isRequired'),
      },
      renderComponentContent() {
        return {
          strengthText: () => $t('sysAccount.passwordStrongTip'),
        };
      },
      rules: z
        .string({ required_error: $t('sysAccount.newPwd') + $t('common.isRequired') })
        .min(1, { message: $t('sysAccount.newPwd') + $t('common.isRequired') })
        .refine((value) => isStrongPassword(value), {
          message: $t('sysAccount.passwordStrongTip'),
        }),
    },
    {
      fieldName: 'confirmPassword',
      label: $t('sysAccount.confirmPwd'),
      component: 'EasyFlowInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: $t('sysAccount.repeatPwd'),
      },
      dependencies: {
        rules(values) {
          const { newPassword } = values;
          return z
            .string({ required_error: $t('sysAccount.repeatPwd') })
            .min(1, { message: $t('sysAccount.repeatPwd') })
            .refine((value) => value === newPassword, {
              message: $t('sysAccount.notSamePwd'),
            });
        },
        triggerFields: ['newPassword'],
      },
    },
  ];
});

const updateLoading = ref(false);
async function handleSubmit(values: any) {
  updateLoading.value = true;
  try {
    const encryptedPayload = await encryptCredentialPayload(
      getCredentialKeyApi,
      values,
    );
    const res = await api.post(
      '/userCenter/sysAccount/updatePassword',
      encryptedPayload,
    );
    if (res.errorCode === 0) {
      ElMessage.success($t('message.success'));
      const userInfo = await authStore.fetchUserInfo();
      if (isForcedPasswordChange.value) {
        await router.replace(
          userInfo?.homePath || preferences.app.defaultHomePath || '/',
        );
      }
    }
  } finally {
    updateLoading.value = false;
  }
}
</script>
<template>
  <ProfilePasswordSetting
    :button-loading="updateLoading"
    :button-text="$t('button.update')"
    ref="profilePasswordSettingRef"
    class="w-1/3"
    :form-schema="formSchema"
    @submit="handleSubmit"
  />
</template>
