<template>
  <a-modal v-model:visible="visible" title="修改用户密码" :mask-closable="false" :width="500" @cancel="handleClose">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-form-item label="用户账号">
        <a-input :model-value="user?.account" disabled />
      </a-form-item>

      <a-form-item field="password" label="新密码">
        <a-input-password v-model="formData.password" placeholder="请输入密码" allow-clear />
      </a-form-item>

      <a-form-item field="confirmPassword" label="确认新密码">
        <a-input-password v-model="formData.confirmPassword" placeholder="请确认密码" allow-clear />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="handleClose">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleSubmit">确定</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { resetUserPassword } from '@/api/module/user'
import type { UserItem } from '@/api/types'

const props = defineProps<{
  user: UserItem | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}>()

const visible = computed({
  get: () => !!props.user,
  set: (val) => emit('update:visible', val),
})

const formRef = ref()
const loading = ref(false)

const formData = reactive({
  password: '',
  confirmPassword: '',
})

const rules = {
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码至少6个字符' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码' },
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if (value !== formData.password) {
          callback('两次密码输入不一致')
        } else {
          callback()
        }
      },
    },
  ],
}

// 重置表单
watch(
  () => props.user,
  (val) => {
    if (val) {
      formData.password = ''
      formData.confirmPassword = ''
    }
  }
)

const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (valid) return

    loading.value = true
    const res = await resetUserPassword({
      account: props.user!.account || '',
      code: '123456', // 暂时没校验，随便传
      password: formData.password,
      phone: props.user!.phone || '13800138000', // 暂时没校验，随便传
    })

    if (res.code === 0) {
      Message.success(res.message || '密码修改成功')
      handleClose()
      emit('success')
    }
  } catch (error) {
    console.error('修改密码失败', error)
  } finally {
    loading.value = false
  }
}
</script>

<script lang="ts">
export default {
  name: 'PasswordChangeDialog',
}
</script>
