<script setup lang="ts">
import { computed, reactive, ref } from 'vue';

import { I18N_COMMON } from '@/enum/i18n';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { changePassword, fetchLogout } from '@/service/api';
import { useAuthStore } from '@/store/modules/auth';

defineOptions({
  name: 'ChangePassword',
});

const authStore = useAuthStore();

// 是否请求中
const loading = ref(false);
const adminLoading = ref(false); // 添加单独的加载状态

const { formRef } = useAntdForm();
const adminFormRef = useAntdForm(); // 添加第二个表单的ref

// 主表单model（修改当前用户密码）
const model: Api.SystemManage.EditPassword = reactive({
  oldPassword: '',
  password: '',
  confirmPassword: '',
});

// 管理员修改密码表单model - 分开两个独立的表单
const admin2Model = reactive({
  newPassword: '',
  confirmPassword: '',
});

const admin3Model = reactive({
  newPassword: '',
  confirmPassword: '',
});

// 表单校验的 key
type RuleKey = Extract<keyof Api.SystemManage.EditPassword, 'oldPassword' | 'password' | 'confirmPassword'>;

const rules = computed<Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]>>(() => {
  const { createConfirmPwdRule, formRules } = useFormRules();

  return {
    oldPassword: formRules.oldPwd,
    password: formRules.pwd,
    confirmPassword: createConfirmPwdRule(model.password || ''),
  };
});

// 管理员密码表单规则
const createAdminRules = (password: string) => {
  const { createConfirmPwdRule, formRules } = useFormRules();

  return {
    newPassword: formRules.pwd, // 使用密码规则
    confirmPassword: createConfirmPwdRule(password || ''),
  };
};

// 更新 model 的值
const updateModel = (args: Partial<Api.SystemManage.SaveUserManage>) => {
  Object.assign(model, args);
};

// 提交当前用户密码修改
async function handleSubmit(values: Api.SystemManage.EditPassword) {
  loading.value = true;
  // 请求接口
  const { error } = await changePassword({
    password: values.oldPassword,
    newPassword: values.password,
  });
  if (!error) {
    window.$message?.success($t(`common.editSuccess`));
    // 退出重新登录
    await fetchLogout();
    authStore.resetStore();
  }
  loading.value = false;
}

// 提交admin2密码修改
async function handleAdmin2Submit() {
  try {
    adminLoading.value = true;
    // 调用修改admin2密码的接口
    // 这里假设可以直接修改，需要根据实际接口调整
    const { error } = await changePassword({
      targetUserName: 'admin2', // 固定用户名为admin2
      newPassword: admin2Model.newPassword,
    });

    if (!error) {
      window.$message?.success('修改 admin2 密码成功');
      // 重置表单
      admin2Model.newPassword = '';
      admin2Model.confirmPassword = '';
    }
  } catch (error) {
    console.error('修改admin2密码失败:', error);
  } finally {
    adminLoading.value = false;
  }
}

// 提交admin3密码修改
async function handleAdmin3Submit() {
  try {
    adminLoading.value = true;
    // 调用修改admin3密码的接口
    const { error } = await changePassword({
      targetUserName: 'admin3', // 固定用户名为admin3
      newPassword: admin3Model.newPassword,
    });

    if (!error) {
      window.$message?.success('修改 admin3 密码成功');
      // 重置表单
      admin3Model.newPassword = '';
      admin3Model.confirmPassword = '';
    }
  } catch (error) {
    console.error('修改admin3密码失败:', error);
  } finally {
    adminLoading.value = false;
  }
}
</script>

<template>
  <!-- 第一部分：修改当前用户密码 -->
  <AForm ref="formRef" layout="vertical" :model="model" :rules="rules" @finish="handleSubmit">
    <h3 class="text-lg font-medium mb-4">{{ $t('form.changeCurrentPwd') || '修改当前用户密码' }}</h3>
    <ACol :span="24">
      <AFormItem name="oldPassword" :label="$t('form.oldPwd.label')">
        <AInputPassword v-model:value="model.oldPassword" size="large" :placeholder="$t('form.oldPwd.required')" />
      </AFormItem>
    </ACol>
    <StrengthMeter v-model:form-data="model" @update:model="updateModel" />
    <ARow justify="center" class="mt-2">
      <AButton type="primary" html-type="submit" :loading="loading" block>
        {{ $t(I18N_COMMON.COMMIT) }}
      </AButton>
    </ARow>
  </AForm>

  <ADivider />

  <!-- 第二部分：修改admin2密码 -->
  <AForm layout="vertical" :model="admin2Model" :rules="createAdminRules(admin2Model.newPassword)" @finish="handleAdmin2Submit">
    <h3 class="text-lg font-medium mb-4">修改 admin2 密码</h3>
    <ACol :span="24">
      <AFormItem name="newPassword" label="新密码">
        <AInputPassword
          v-model:value="admin2Model.newPassword"
          size="large"
          placeholder="请输入admin2新密码"
        />
      </AFormItem>
    </ACol>
    <ACol :span="24">
      <AFormItem name="confirmPassword" label="确认密码">
        <AInputPassword
          v-model:value="admin2Model.confirmPassword"
          size="large"
          placeholder="请确认admin2密码"
        />
      </AFormItem>
    </ACol>
    <ARow justify="center" class="mt-2">
      <AButton type="primary" html-type="submit" :loading="adminLoading" block>
        修改 admin2 密码
      </AButton>
    </ARow>
  </AForm>

  <ADivider />

  <!-- 第三部分：修改admin3密码 -->
  <AForm layout="vertical" :model="admin3Model" :rules="createAdminRules(admin3Model.newPassword)" @finish="handleAdmin3Submit">
    <h3 class="text-lg font-medium mb-4">修改 admin3 密码</h3>
    <ACol :span="24">
      <AFormItem name="newPassword" label="新密码">
        <AInputPassword
          v-model:value="admin3Model.newPassword"
          size="large"
          placeholder="请输入admin3新密码"
        />
      </AFormItem>
    </ACol>
    <ACol :span="24">
      <AFormItem name="confirmPassword" label="确认密码">
        <AInputPassword
          v-model:value="admin3Model.confirmPassword"
          size="large"
          placeholder="请确认admin3密码"
        />
      </AFormItem>
    </ACol>
    <ARow justify="center" class="mt-2">
      <AButton type="primary" html-type="submit" :loading="adminLoading" block>
        修改 admin3 密码
      </AButton>
    </ARow>
  </AForm>
</template>
