<template>
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="550px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
  >
    <div class="password-change-content">
      <!-- 提示信息 -->
      <div class="password-alert">
        <el-alert :title="alertTitle" :type="alertType" :description="alertDescription" show-icon :closable="false" />
      </div>

      <!-- 密码修改表单 -->
      <el-form
        ref="pwdRef"
        :model="user"
        :rules="rules"
        label-width="100px"
        class="password-form"
        hide-required-asterisk
        :validate-on-rule-change="false"
        :show-message="true"
        :inline-message="false"
      >
        <!-- 只有管理员重置模式不需要旧密码，其他场景都需要 -->
        <el-form-item v-if="!props.isAdminReset" label="旧密码" prop="oldPassword">
          <el-input v-model="user.oldPassword" placeholder="请输入旧密码" type="password" show-password />
        </el-form-item>

        <!-- 管理员重置模式显示目标用户信息 -->
        <el-form-item v-if="props.isAdminReset" label="目标用户">
          <el-input :value="props.targetUserName" disabled />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="user.newPassword" placeholder="请输入新密码" type="password" show-password @input="handlePasswordInput" />

          <!-- 使用密码强度指示器组件 -->
          <PasswordStrengthIndicator
            :strength-score="strengthScore"
            :strength-level="strengthLevel"
            :strength-color="strengthColor"
            :password-rules="passwordRules"
            :current-password="user.newPassword"
            :config-loaded="configLoaded"
            :show-strength-meter="true"
            :show-rules="true"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="user.confirmPassword" placeholder="请确认新密码" type="password" show-password />
        </el-form-item>
      </el-form>

      <div class="form-footer">
        <el-button type="primary" @click="submitForm" :loading="loading" :disabled="!allBasicRulesMet || !configLoaded">
          {{ getSubmitButtonText }}
        </el-button>
        <!-- 超级管理员可以跳过修改（只在特定情况下显示） -->
        <el-button v-if="props.showSkipButton && !props.isAdminReset && !props.isForceChange" @click="skipChange"> 跳过 (系统管理员) </el-button>
        <!-- 管理员重置模式可以取消 -->
        <el-button v-if="props.isAdminReset" @click="cancelReset"> 取消 </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch, nextTick } from 'vue';
import { resetUserPassword, changePassword } from '@/api/system/security';
import type { PasswordChangeRequest } from '@/api/system/security/types';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import { usePasswordStrength } from '@/views/system/user/composables/usePasswordStrength';
import PasswordStrengthIndicator from '@/components/User/PasswordStrengthIndicator.vue';

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  isFirstLogin: {
    type: Boolean,
    default: false
  },
  isAdminReset: {
    type: Boolean,
    default: false
  },
  isForceChange: {
    type: Boolean,
    default: false
  },
  targetUserId: {
    type: [String],
    default: null
  },
  targetUserName: {
    type: String,
    default: ''
  },
  showSkipButton: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'success', 'cancel']);

// 更新对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

const userStore = useUserStore();
const pwdRef = ref();
const loading = ref(false);

const user = ref<{
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 动态标题和提示信息
const dialogTitle = computed(() => {
  if (props.isAdminReset) return '重置用户密码';
  if (props.isFirstLogin) return '首次登录修改密码';
  if (props.isForceChange) return '密码已被重置，请修改密码';
  return '密码已过期，请修改密码';
});

const alertTitle = computed(() => {
  if (props.isAdminReset) return `重置用户 "${props.targetUserName}" 的密码`;
  if (props.isFirstLogin) return '首次登录需要修改初始密码';
  if (props.isForceChange) return '管理员已重置您的密码';
  return '您的密码已超过90天未修改';
});

const alertType = computed(() => {
  if (props.isAdminReset) return 'info';
  if (props.isForceChange) return 'warning';
  return 'warning';
});

const alertDescription = computed(() => {
  if (props.isAdminReset) return '为目标用户设置一个符合安全要求的新密码。新密码需要满足复杂度要求。';
  if (props.isForceChange) return '管理员已重置您的密码，请先输入重置后的密码作为旧密码，然后设置新密码。新密码需要满足复杂度要求。';
  return '为了保障您的账户安全，请立即修改密码。新密码需要满足复杂度要求。';
});

// 提交按钮文字
const getSubmitButtonText = computed(() => {
  if (props.isAdminReset) return '重置密码';
  if (props.isForceChange) return '修改密码';
  return '确认修改';
});

// 使用统一的密码强度检查 composable
const {
  strengthScore,
  strengthLevel,
  strengthColor,
  passwordRules,
  allBasicRulesMet,
  configLoaded,
  checkPasswordStrengthForUI,
  createBasicPasswordRules,
  resetPasswordStrength
} = usePasswordStrength({
  username: computed(() => (props.isAdminReset ? props.targetUserName : userStore.name || '')),
  showStrengthMeter: true,
  showTooltip: false
});

// 处理密码输入
const handlePasswordInput = () => {
  // 只有当密码不为空时才进行强度检查，避免初始化时显示错误提示
  if (user.value.newPassword && user.value.newPassword.length > 0) {
    checkPasswordStrengthForUI(user.value.newPassword);
  } else {
    // 密码为空时重置强度检查状态
    resetPasswordStrength();
  }
};

// 监听密码变化
watch(
  () => user.value.newPassword,
  () => {
    handlePasswordInput();
  }
);

const equalToPassword = (rule: any, value: string, callback: any) => {
  if (user.value.newPassword !== value) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

// 动态规则，根据是否是管理员重置或强制修改调整
const rules = computed(() => {
  const baseRules = {
    newPassword: [{ required: true, message: '新密码不能为空', trigger: 'blur' }, ...createBasicPasswordRules({ fieldName: '新密码' })],
    confirmPassword: [
      { required: true, message: '确认密码不能为空', trigger: 'blur' },
      {
        validator: equalToPassword,
        trigger: 'blur'
      }
    ]
  };

  // 如果不是管理员重置且不是强制修改，需要旧密码验证
  if (!props.isAdminReset && !props.isForceChange) {
    return {
      oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
      ...baseRules
    };
  }

  return baseRules;
});

// 清空密码表单
const clearPasswordForm = () => {
  user.value.oldPassword = '';
  user.value.newPassword = '';
  user.value.confirmPassword = '';
  // 清空密码强度检查状态
  resetPasswordStrength();
  // 延迟清空表单验证状态，确保DOM更新完成
  nextTick(() => {
    pwdRef.value?.clearValidate();
  });
};

/** 提交密码修改 */
const submitForm = () => {
  pwdRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        if (props.isAdminReset) {
          // 管理员重置用户密码
          const resetRequest: PasswordChangeRequest = {
            userId: props.targetUserId,
            newPassword: user.value.newPassword,
            confirmPassword: user.value.confirmPassword,
            userName: props.targetUserName
          };
          await resetUserPassword(resetRequest);
          ElMessage.success(`用户 "${props.targetUserName}" 密码重置成功!`);
        } else {
          // 用户自己修改密码（包括首次登录、强制修改、过期修改）
          const changeRequest: PasswordChangeRequest = {
            newPassword: user.value.newPassword,
            confirmPassword: user.value.confirmPassword,
            oldPassword: user.value.oldPassword,
            // 强制修改密码时标记跳过旧密码验证
            isForceChange: props.isForceChange,
            userName: userStore.name
          };
          await changePassword(changeRequest);
          // 根据不同场景显示不同的成功消息
          if (props.isForceChange) {
            ElMessage.success('密码修改成功，您可以继续使用系统');
          } else if (props.isFirstLogin) {
            ElMessage.success('初始密码修改成功');
          } else {
            ElMessage.success('密码修改成功');
          }
          // 更新用户状态，标记密码已修改
          userStore.setPwdChanged();
        }
        // 密码修改成功后清空表单
        clearPasswordForm();
        emit('success');
        dialogVisible.value = false;
      } catch (error) {
        // 如果修改失败，不清空表单，方便用户重新尝试
      } finally {
        loading.value = false;
      }
    }
  });
};

/** 取消重置 */
const cancelReset = () => {
  clearPasswordForm();
  emit('cancel');
  dialogVisible.value = false;
};

/** 跳过修改（仅系统管理员可用） */
const skipChange = () => {
  userStore.setPwdChanged();
  emit('success');
  dialogVisible.value = false;
};

// 监听对话框显示状态，每次显示时清空表单
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      // 延迟清空表单，确保组件完全渲染后再清除状态
      nextTick(() => {
        clearPasswordForm();
        // 额外确保重置密码强度状态
        resetPasswordStrength();
      });
    }
  }
);

onMounted(() => {

});
</script>

<style scoped>
.password-change-content {
  padding: 0 15px;
}

.password-alert {
  margin-bottom: 20px;
}

.password-form {
  margin-top: 20px;
}

.form-footer {
  margin-top: 25px;
  text-align: center;
}

/* 移除了所有密码强度相关的样式，因为现在由组件提供 */
</style>
