<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="signTime"
        required
      >
        <a-date-picker
          v-model:value="formData.signTime"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择时间"
          style="width: 100%"
        />
      </a-form-item>

      <!-- 代签入原因 -->
      <a-form-item
        label="代签入原因"
        name="reason"
        required
      >
        <a-textarea
          v-model:value="formData.reason"
          placeholder="请填写1-100字的原因"
          :maxlength="100"
          :auto-size="{ minRows: 4, maxRows: 6 }"
        />
      </a-form-item>

      <!-- 代签入图片 -->
      <a-form-item
        label="代签入图片"
        name="images"
      >
        <a-upload
          v-model:file-list="fileList"
          list-type="picture-card"
          :before-upload="beforeUpload"
          :custom-request="dummyRequest"
          :multiple="true"
          accept="image/*"
        >
          <div>
            <PlusOutlined />
            <div style="margin-top: 8px">选择图片</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useForm } from '@/hooks'
import { useModal } from '@/hooks'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

const emit = defineEmits(['ok'])

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

// 文件列表
const fileList = ref([])

// 表单数据初始化
formData.value = reactive({
  signTime: null,
  reason: '',
  images: [] // 存储 File 对象或 URL
})

// 表单校验规则
formRules.value = {
  signTime: [
    { required: true, message: '请选择签入时间' }
  ],
  reason: [
    { required: true, message: '请填写代签入原因' },
    { max: 100, message: '原因不能超过100字' }
  ]
}

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

// 当前工单记录（可选）
const currentRecord = ref(null)

// 显示弹窗方法（供父组件调用）
function showCheckModal(record) {
  currentRecord.value = record
  showModal({
    type: 'cancel',
    title: '代签入工单'
  })
  formData.value.signTime = null
  formData.value.reason = ''
  fileList.value = []
}

// 图片上传前校验（限制大小、类型等）
function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type.startsWith('image/')
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 等图片文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB!')
    return false
  }
  // 将文件加入 fileList（Ant Upload 会自动处理，但这里确保能拿到）
  return true
}

// 阻止 Ant Design 自动上传（因为我们可能只收集文件，由父组件或 API 处理）
function dummyRequest(options) {
  const { onSuccess, file } = options
  setTimeout(() => {
    onSuccess('ok', file)
  }, 0)
}

// 确定提交
async function handleOk() {
  try {
    const values = await formRef.value.validateFields()
    showLoading()

    // 收集文件（如果需要传给父组件）
    const files = fileList.value
      .filter(f => f.status === 'done')
      .map(f => f.originFileObj || f)

    // 此处可调用 API 提交：签入时间、原因、图片
    // await apis.workOrder.proxySignIn({
    //   id: currentRecord.value?.id,
    //   signTime: dayjs(formData.value.signTime).format('YYYY-MM-DD HH:mm:ss'),
    //   reason: formData.value.reason,
    //   images: files
    // })

    hideLoading()
    hideModal()
    emit('ok', {
      signTime: formData.value.signTime,
      reason: formData.value.reason,
      images: files
    })
  } catch (error) {
    hideLoading()
    console.error('表单验证失败:', error)
  }
}

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

// 关闭后重置
function onAfterClose() {
  resetForm()
  fileList.value = []
}

// 暴露方法
defineExpose({
  showCheckModal
})
</script>

<style scoped>
/* 可选：调整上传区域样式 */
:deep(.ant-upload-select-picture-card) {
  width: 104px;
  height: 104px;
}
</style>