<!-- src/components/DispatchDrawer.vue -->
<template>
  <a-drawer title="派单" :open="open" :width="600" @close="handleCancel" :destroy-on-close="true">
    <a-form :rules="rules" ref="formRef" layout="vertical" class="form-mode" :model="formModel">
      <!-- 服务对象 -->
      <a-row :gutter="16">
        <a-col :xs="12">
          <a-form-item label="服务对象">
            <a-input v-model:value="formModel.serviceTarget" placeholder="请输入服务对象名称" disabled />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 服务项目和服务费用 -->
      <a-row :gutter="16">
        <a-col :xs="12">
          <a-form-item label="服务项目" name="serviceItem">
            <a-select v-model:value="formModel.serviceItem" placeholder="请选择服务项目" mode="multiple">
              <a-select-option value="兴趣活动">兴趣活动</a-select-option>
              <a-select-option value="居家照护">居家照护</a-select-option>
              <a-select-option value="医疗护理">医疗护理</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xs="12">
          <a-form-item label="服务费用">
            <a-input-number v-model:value="formModel.serviceFee" placeholder="由关联服务项目计算得出" style="width: 100%"
              :min="0" />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 服务人员 -->
      <a-row :gutter="16">
        <a-col :xs="12">
          <a-form-item label="服务人员" name="serviceStaff">
            <a-select v-model:value="formModel.serviceStaff" placeholder="请选择服务人员">
              <a-select-option v-for="user in assignees" :key="user.id" :value="user.id">
                {{ user.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 计划日期 -->
      <a-row :gutter="16">
        <a-col :xs="24">
          <a-form-item label="计划日期" name="plannedDate">
            <a-range-picker v-model:value="formModel.plannedDate" style="width: 100%" :placeholder="['开始日期', '结束日期']" />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 计划开始时间和要求工单时长 -->
      <a-row :gutter="16">
        <a-col :xs="12">
          <a-form-item label="计划开始时间" name="plannedStartTime">
            <a-time-picker v-model:value="formModel.plannedStartTime" placeholder="请选择计划开始时间" style="width: 100%"
              format="HH:mm" :minute-step="5" />
          </a-form-item>
        </a-col>
        <a-col :xs="12">
          <a-form-item label="要求工单时长" name="requiredDuration">
            <a-input v-model:value="formModel.requiredDuration" placeholder="请输入要求工单时长">
              <template #suffix>分钟</template>
            </a-input>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 服务地址 -->
      <a-row :gutter="16">
        <a-col :xs="24">
          <a-form-item label="服务地址" name="serviceArea">
            <AreaCascader v-model:value="formModel.serviceArea" style="width: 100%; margin-bottom: 8px;" />
            <a-input v-model:value="formModel.detailedAddress" placeholder="详细地址" />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 服务内容 -->
      <a-row :gutter="16">
        <a-col :xs="24">
          <a-form-item label="服务内容">
            <a-input v-model:value="formModel.serviceContent" placeholder="填写服务内容，充当备注作用，此字段数据会在app工单中显示" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <div class="select-btn" style="display: flex; justify-content: flex-end; gap: 8px;">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleOk" :loading="confirmLoading">确定</a-button>
      </div>
    </template>
  </a-drawer>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import AreaCascader from '@/components/AreaCascader/index.vue'
import { message } from 'ant-design-vue'
import apis from '@/apis'
import dayjs from 'dayjs'

// 定义 props
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  assignees: {
    type: Array,
    default: () => []
  },
  initialValues: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['close', 'submit'])

// 响应式数据
const formRef = ref()
const confirmLoading = ref(false)

// 使用 formModel 替代 formData，保持与模板一致
const formModel = reactive({
  serviceTarget: '',
  serviceItem: [],
  serviceFee: undefined,
  serviceStaff: undefined,
  serviceStaffId: undefined,
  plannedDate: [],
  plannedStartTime: null,
  requiredDuration: '',
  serviceArea: [],
  detailedAddress: '',
  serviceContent: ''
})

// 表单验证规则
const rules = {
  serviceItem: [{ required: true, message: '请选择服务项目', trigger: 'change' }],
  serviceStaff: [{ required: true, message: '请选择服务人员', trigger: 'change' }],
  plannedDate: [{ required: true, message: '请选择计划日期', trigger: 'change' }],
  plannedStartTime: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }],
  requiredDuration: [{ required: true, message: '请输入要求工单时长', trigger: 'blur' }],
  serviceArea: [{ required: true, message: '请选择服务区域', trigger: 'change' }],
  detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

// ================== Methods ==================

/**
 * 确认提交
 */
async function handleOk() {
  try {
    confirmLoading.value = true
    await formRef.value.validate()

    // 构建日期时间
    let plannedStart = null
    let plannedEnd = null
    if (formModel.plannedDate[0] && formModel.plannedStartTime) {
      const datePart = formModel.plannedDate[0].format('YYYY-MM-DD')
      const timePart = formModel.plannedStartTime.format('HH:mm')
      plannedStart = dayjs(`${datePart} ${timePart}`)
      plannedEnd = plannedStart.add(Number(formModel.requiredDuration) || 0, 'minute')
    }

    const submitData = {
      customerId: props.initialValues.id,
      projects: formModel.serviceItem,
      price: formModel.serviceFee,
      servicePerson: formModel.serviceStaff,
      servicePersonId: formModel.serviceStaffId,
      plannedStartDate: plannedStart?.toISOString() || null,
      plannedEndDate: plannedEnd?.toISOString() || null,
      plannedServiceStartDate: Number(formModel.requiredDuration) || 0,
      areaLabels: formModel.serviceArea,
      areaCodes: formModel.serviceArea.join(','),
      detailAddress: formModel.detailedAddress,
      content: formModel.serviceContent
    }

    console.log('提交数据:', submitData)

    const { success } = await apis.workOrder.sendWorkOrder(submitData)
    if (success) {
      message.success('派单成功')
      emit('submit', submitData)
    }
  } catch (error) {
    console.log('表单校验或提交失败:', error)
    // 可选：message.error('派单失败')
  } finally {
    confirmLoading.value = false
  }
}

/**
 * 取消/关闭弹框
 */
function handleCancel() {
  resetFormModel()
  emit('close')
}

/**
 * 重置表单数据
 */
function resetFormModel() {
  Object.keys(formModel).forEach(key => {
    if (Array.isArray(formModel[key])) {
      formModel[key] = []
    } else if (typeof formModel[key] === 'string') {
      formModel[key] = ''
    } else {
      formModel[key] = undefined
    }
  })

  // 使用 clearValidate 而不是 resetFields
  if (formRef.value?.clearValidate) {
    formRef.value.clearValidate()
  }
}

/**
 * 设置表单字段值
 */
function setFormFields(values) {
  // 逐个字段赋值，确保响应式系统能追踪
  for (const key in formModel) {
    if (key in values) {
      formModel[key] = values[key]
    } else {
      // 重置为默认值（可选）
      formModel[key] = Array.isArray(formModel[key]) ? [] : typeof formModel[key] === 'string' ? '' : undefined
    }
  }

  nextTick(() => {
    if (formRef.value?.clearValidate) {
      formRef.value.clearValidate()
    }
  })
}

/**
 * 加载工单详情并填充表单
 * @param {string} id - 工单ID
 */
async function loadWorkOrderDetail(id) {
  console.log('开始加载工单详情，ID:', id)
  try {
    const { success, data } = await apis.workOrder.getWorkOrderDetail(id)
    console.log('工单详情接口响应:', { success, data })

    if (success && data) {
      const detailData = data
      console.log('工单详情数据:', detailData)
      let projects = detailData.projects.map(item => item.name)

      // 构建表单数据
      const formData = {
        serviceTarget: detailData.customer.name || '',
        serviceItem: projects,
        serviceFee: detailData.price,
        serviceStaff: detailData.servicePerson || undefined,
        servicePersonId: detailData.servicePersonId,  
        plannedDate: detailData.plannedEndDate ? [
          dayjs(detailData.plannedEndDate),
          dayjs(detailData.plannedEndDate)
        ] : [],
        // ✅ 修复：直接用完整时间字符串构造 Day.js 对象
        plannedStartTime: detailData.plannedStartDate
          ? dayjs(detailData.plannedStartDate)
          : null,
        requiredDuration: detailData.plannedServiceStartDate ?
          String(detailData.plannedServiceStartDate) : '',
        serviceArea: (detailData.areaLabels || []).join('/'),
        detailedAddress: detailData.detailAddress || '',
        serviceContent: detailData.content || ''
      }
      console.log('构建的表单数据:', formData)

      // 设置表单字段
      setFormFields(formData)

      console.log('设置后的 formModel:', formModel)

    } else {
      message.error('获取工单详情失败')
    }
  } catch (error) {
    console.error('获取工单详情失败:', error)
    // message.error('加载工单信息失败')
  }
}

/**
 * 辅助函数：将区域字符串转换为数组格式
 * @param {string} areaString - 区域字符串
 * @returns {Array} 区域数组
 */
function parseAreaToArray(areaString) {
  if (!areaString) return []
  return areaString.split('/') || []
}

// 监听 open 变化，初始化表单
watch(
  () => props.open,
  async (newVal) => {
    if (newVal) {
      console.log('抽屉打开，重置表单')
      resetFormModel()

      // 等待 DOM 更新完成
      await nextTick()

      if (props.initialValues && props.initialValues.id) {
        console.log('加载工单详情，ID:', props.initialValues.id)
        await loadWorkOrderDetail(props.initialValues.id)
      } else {
        console.log('新建派单，无初始值')
        // 设置测试数据
        setFormFields({
          serviceTarget: '新建测试数据',
          serviceItem: ['兴趣活动'],
          serviceFee: 100,
          requiredDuration: '60'
        })
      }
    }
  }
)

</script>

<style scoped>
.form-mode {
  padding: 0 16px;
}

.select-btn {
  margin-top: 16px;
  text-align: right;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>