<template>
  <a-modal
    :width="520"
    :open="modal.open"
    :title="modal.title"
    :confirm-loading="modal.confirmLoading"
    :after-close="onAfterClose"
    :cancel-text="cancelText"
    :ok-text="okText"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form layout="vertical" ref="formRef" :model="formData" :rules="formRules">
      <a-form-item
        :label="'作废原因'"
        name="reason"
        required
      >
        <a-textarea
          v-model:value="formData.reason"
          :placeholder="'请填写作废原因'"
          :auto-size="{ minRows: 4, maxRows: 6 }"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref } from 'vue'
import { useForm } from '@/hooks'
import { useModal } from '@/hooks'
import { useI18n } from 'vue-i18n'

const emit = defineEmits(['ok'])

const { t } = useI18n()
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formData, formRef, formRules, resetForm } = useForm()

// 表单规则
formRules.value = {
  reason: [
    { required: true, message: '请填写作废原因' },
    { max: 500, message:'请填写作废原因' }
  ]
}

// 按钮文案
const cancelText = ref('取消')
const okText = ref('确定')

// 添加 props 或内部状态来保存当前工单
const currentRecord = ref(null)

// 修改 showCancelModal 方法，接收 record
function showCancelModal(record) {
  currentRecord.value = record // 保存当前工单
  showModal({
    type: 'cancel',
    title:'作废工单'
  })
  formData.value.reason = ''
}


// 确定
async function handleOk() {
  try {
    await formRef.value.validateFields()
    showLoading()

    // 此处可调用 API 提交作废原因
    // await apis.workOrder.cancelWorkOrder({ id: props.workOrderId, reason: formData.value.reason })

    hideLoading()
    hideModal()
    emit('ok', formData.value.reason) // 可选：将原因传回父组件
  } catch (error) {
    hideLoading()
  }
}

// 取消
function handleCancel() {
  hideModal()
}

// 关闭后重置
function onAfterClose() {
  resetForm()
}

// 暴露方法给父组件
defineExpose({
  showCancelModal
})
</script>