<template>
  <a-modal
    v-model:visible="visible"
    :title="'修改密码'"
    :width="400"
    @cancel="handleClose"
    @ok="handleSavePassword"
    :ok-text="'保存'"
    :cancel-text="'取消'"
    :confirm-loading="loading"
  >
    <a-form :model="form" layout="vertical">
      <a-form-item :label="'新密码'" field="newPassword" :required="true">
        <a-input-password
          v-model="form.newPassword"
          :placeholder="'请输入新密码'"
          allow-clear
        />
      </a-form-item>
      
      <a-form-item :label="'确认密码'" field="confirmPassword" :required="true">
        <a-input-password
          v-model="form.confirmPassword"
          :placeholder="'请再次输入新密码'"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import { resetUserPassword } from '@/api/module/user';
import SafeStorage, { AppStorageKey } from '@/utils/safeStorage';

interface Props {
  open: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  (e: 'update:open', value: boolean): void;
}>();

const loading = ref(false);
const visible = ref(props.open);

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

// 监听 props.open 变化
watch(() => props.open, (val) => {
  visible.value = val;
});

// 监听 visible 变化，同步到父组件
watch(visible, (val) => {
  emit('update:open', val);
});

// 保存密码
const handleSavePassword = async () => {
  // 表单验证
  if (!form.value.newPassword || !form.value.confirmPassword) {
    Message.error('请填写新密码和确认密码');
    return;
  }
  
  if (form.value.newPassword.length < 6) {
    Message.error('密码至少需要6个字符');
    return;
  }
  
  if (form.value.newPassword !== form.value.confirmPassword) {
    Message.error('两次输入的密码不一致');
    return;
  }
  
  loading.value = true;
  
  try {
    // 从 SafeStorage 获取登录用户信息
    const userInfo = SafeStorage.get(AppStorageKey.USER_INFO) || {};
    const res = await resetUserPassword({
      account: userInfo.account || '',
      code: '123456', // 暂时没校验，随便传
      password: form.value.newPassword,
      phone: userInfo.phone || '13800138000' // 暂时没校验，随便传
    });
    
    if (res.code === 0) {
      Message.success('密码修改成功');
      handleClose();
    } else {
      Message.error(res.message || '密码修改失败');
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    Message.error('密码修改失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  form.value = {
    newPassword: '',
    confirmPassword: ''
  };
  visible.value = false;
};
</script>