<template>
  <el-dialog
    v-model="dialogVisible"
    title="发货"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="ship-form"
    >
      <el-form-item label="物流公司" prop="courierName">
        <el-select
          v-model="formData.courierName"
          placeholder="请选择物流公司"
          filterable
          allow-create
          style="width: 100%"
          @change="handleCourierChange"
        >
          <el-option
            v-for="item in courierOptions"
            :key="item.code"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="快递单号" prop="courierNumber">
        <el-input
          v-model="formData.courierNumber"
          placeholder="请输入快递单号"
          clearable
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        确认发货
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { shipOrder, type ShipOrderRequest } from '@/api/business/order'

interface Props {
  modelValue: boolean
  sendId: number | null
}

const props = defineProps<Props>()

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

const dialogVisible = ref(props.modelValue)
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 表单数据
const formData = reactive<ShipOrderRequest>({
  courierName: '',
  courierNumber: '',
  courierCode: ''
})

// 常用物流公司选项
const courierOptions = [
  { code: 'SF', name: '顺丰速运' },
  { code: 'YTO', name: '圆通速递' },
  { code: 'ZTO', name: '中通快递' },
  { code: 'STO', name: '申通快递' },
  { code: 'YD', name: '韵达快递' },
  { code: 'HTKY', name: '百世快递' },
  { code: 'JD', name: '京东物流' },
  { code: 'EMS', name: 'EMS' },
  { code: 'YZPY', name: '邮政包裹' },
  { code: 'DBL', name: '德邦快递' },
  { code: 'JTSD', name: '极兔速递' },
  { code: 'ZJS', name: '宅急送' }
]

// 表单验证规则
const formRules: FormRules = {
  courierName: [
    { required: true, message: '请选择或输入物流公司', trigger: ['change', 'blur'] },
    {
      validator: (_rule, value, callback) => {
        if (!value || (typeof value === 'string' && value.trim() === '')) {
          callback(new Error('物流公司不能为空或纯空白字符'))
        } else {
          callback()
        }
      },
      trigger: ['change', 'blur']
    }
  ],
  courierNumber: [
    { required: true, message: '请输入快递单号', trigger: ['change', 'blur'] },
    {
      validator: (_rule, value, callback) => {
        if (!value || (typeof value === 'string' && value.trim() === '')) {
          callback(new Error('快递单号不能为空或纯空白字符'))
        } else {
          callback()
        }
      },
      trigger: ['change', 'blur']
    }
  ]
}

watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    // 重置表单
    formData.courierName = ''
    formData.courierNumber = ''
    formData.courierCode = ''
    formRef.value?.resetFields()
  }
})

watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 物流公司选择变化时，自动设置物流编码
const handleCourierChange = (value: string) => {
  const courier = courierOptions.find(item => item.name === value)
  formData.courierCode = courier?.code || ''
}

const handleSubmit = async () => {
  if (!props.sendId) return
  
  try {
    await formRef.value?.validate()
  } catch {
    return
  }
  
  submitting.value = true
  try {
    await shipOrder(props.sendId, {
      courierName: formData.courierName.trim(),
      courierNumber: formData.courierNumber.trim(),
      courierCode: formData.courierCode || undefined
    })
    
    ElMessage.success('发货成功')
    dialogVisible.value = false
    emit('success')
  } catch (error: any) {
    console.error('发货失败:', error)
    ElMessage.error(error.message || '发货失败')
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
  emit('close')
}
</script>

<style scoped>
.ship-form {
  padding: 20px 20px 0;
}
</style>
