<template>
  <el-dialog
      :model-value="visible"
      title="修改密码"
      width="400px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" type="password" show-password autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password" show-password autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" show-password autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>

  <!-- 验证码弹窗 -->
  <CaptchaDialog
    v-model="captchaVisible"
    description="修改密码需要安全验证"
    @confirm="handleCaptchaConfirm"
    @cancel="handleCaptchaCancel"
  />
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { updatePassword } from '@/api/CommonApi.js';
import { useUserStore } from '@/stores/user';
import { useRouter } from 'vue-router';
import CaptchaDialog from '@/components/CaptchaDialog.vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['update:visible', 'password-updated']);
const userStore = useUserStore();
const router = useRouter();

const formRef = ref(null);
const loading = ref(false);
const captchaVisible = ref(false);
const pendingFormData = ref(null);

const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'));
  } else if (value !== form.value.newPassword) {
    callback(new Error("两次输入的新密码不一致"));
  } else {
    callback();
  }
};

const rules = ref({
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }, { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }],
  confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: 'blur' }],
});

watch(() => props.visible, (newVal) => {
  if (!newVal && formRef.value) {
    formRef.value.resetFields();
    pendingFormData.value = null;
  }
});

const handleClose = () => {
  emit('update:visible', false);
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 保存表单数据，显示验证码弹窗
      pendingFormData.value = {
        oldPassword: form.value.oldPassword,
        newPassword: form.value.newPassword,
      };
      captchaVisible.value = true;
    }
  });
};

// 验证码确认
const handleCaptchaConfirm = async ({ captchaId, captchaCode }) => {
  if (!pendingFormData.value) return;
  
  loading.value = true;
  try {
    await updatePassword(pendingFormData.value, captchaId, captchaCode);
    ElMessage.success('密码修改成功，请重新登录');
    captchaVisible.value = false;
    emit('password-updated');
    handleClose();
  } catch (error) {
    // 错误已在 axios 拦截器中显示，这里不再重复显示
    console.error('密码修改失败:', error);
  } finally {
    loading.value = false;
  }
};

// 验证码取消
const handleCaptchaCancel = () => {
  pendingFormData.value = null;
};
</script>
