<template>
  <el-drawer
    v-model="visible"
    title="工序执行情况"
    direction="rtl"
    size="100%"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    :append-to-body="true"
    class="mobile-form-drawer"
  >
    <div class="mobile-form" v-loading="loading">
      <!-- 工序进度统计 -->
      <div class="mobile-form__section">
        <div class="mobile-form__section-title">工序进度</div>
        <OperationProgressCard :progressData="progressData" />
      </div>

      <!-- 工序列表 -->
      <div class="mobile-form__section">
        <div class="mobile-form__section-title">工序列表</div>
        <div class="mobile-item-list" v-loading="tableLoading">
          <div
            v-for="(row, index) in operationList"
            :key="row.id"
            class="mobile-item-card"
          >
            <div class="mobile-item-card__header">
              <span class="mobile-item-card__index">#{{ index + 1 }}</span>
              <span class="mobile-item-card__name">{{ row.operationName || '未知工序' }}</span>
              <el-tag :type="getStatusType(row.status)" size="small">{{ getStatusText(row.status) }}</el-tag>
            </div>
            <div class="mobile-item-card__body">
              <div class="mobile-item-card__info-row">
                <span class="mobile-item-card__info-label">工序编码</span>
                <span class="mobile-item-card__info-value">{{ row.operationCode || '-' }}</span>
              </div>
              <div class="mobile-item-card__info-row">
                <span class="mobile-item-card__info-label">计划数量</span>
                <span class="mobile-item-card__info-value">{{ row.planQuantity }}</span>
              </div>
              <div class="mobile-item-card__info-row">
                <span class="mobile-item-card__info-label">完成数量</span>
                <span class="mobile-item-card__info-value">{{ row.completedQuantity }}</span>
              </div>
              <div class="mobile-item-card__info-row">
                <span class="mobile-item-card__info-label">合格/不合格</span>
                <span class="mobile-item-card__info-value">
                  <span style="color: #67c23a">{{ row.qualifiedQuantity }}</span>
                  <span style="color: #909399"> / </span>
                  <span style="color: #f56c6c">{{ row.unqualifiedQuantity }}</span>
                </span>
              </div>
              <div class="mobile-item-card__info-row">
                <span class="mobile-item-card__info-label">操作人</span>
                <span class="mobile-item-card__info-value">{{ getOperationExecution(row.id)?.workerName || '-' }}</span>
              </div>
              <div class="mobile-item-card__info-row">
                <span class="mobile-item-card__info-label">开始时间</span>
                <span class="mobile-item-card__info-value">{{ getOperationExecution(row.id)?.startTime || '未开始' }}</span>
              </div>
              <div class="mobile-item-card__info-row">
                <span class="mobile-item-card__info-label">结束时间</span>
                <span class="mobile-item-card__info-value">{{ getOperationExecution(row.id)?.endTime || '未结束' }}</span>
              </div>
            </div>
            <div class="mobile-item-card__footer">
              <el-button
                size="small"
                type="primary"
                @click="handleStart(row)"
                v-if="row.status === 0 && [2, 3].includes(workOrderStatus)"
                v-hasPermi="['mes:production-order:operations']"
              >开始</el-button>
              <el-button
                size="small"
                type="success"
                @click="handleComplete(row)"
                v-if="row.status === 1"
                v-hasPermi="['mes:production-order:operations']"
              >完成</el-button>
              <el-button
                size="small"
                type="warning"
                @click="handlePause(row)"
                v-if="row.status === 1"
                v-hasPermi="['mes:production-order:operations']"
              >暂停</el-button>
              <el-button
                size="small"
                type="primary"
                @click="handleResume(row)"
                v-if="row.status === 3"
                v-hasPermi="['mes:production-order:operations']"
              >恢复</el-button>
              <el-button
                size="small"
                @click="handleViewDetail(row)"
                v-if="row.status === 2"
                v-hasPermi="['mes:production-order:operations']"
              >详情</el-button>
              <el-button
                size="small"
                type="primary"
                @click="handleRecordProgress(row)"
                v-if="row.status === 1"
                v-hasPermi="['mes:production-order:operations']"
              >记录进度</el-button>
              <el-button
                size="small"
                @click="handleViewProgressHistory(row)"
                v-if="row.status === 1 || row.status === 2"
                v-hasPermi="['mes:production-order:operations']"
              >查看记录</el-button>
            </div>
          </div>
          <div v-if="operationList.length === 0 && !tableLoading" class="mobile-empty-tip">
            暂无工序数据
          </div>
        </div>
      </div>
    </div>
  </el-drawer>

  <!-- 开始工序弹窗 -->
  <OperationStartDialog
    v-model:visible="startDialogVisible"
    :equipment-options="equipmentOptions"
    :max-quantity="currentOperation?.planQuantity"
    :default-input-quantity="currentOperation?.planQuantity || 1"
    :submitting="startSubmitting"
    @submit="onStartSubmit"
  />

  <!-- 完成工序弹窗 -->
  <el-dialog v-model="completeDialogVisible" title="完成工序" width="400px" append-to-body>
    <el-form ref="completeFormRef" :model="completeForm" :rules="completeRules" label-width="120px">
      <!-- 动态工序字段 -->
      <template v-if="Object.keys(processFields).length > 0">
        <div class="mb-4">
          <div class="text-lg font-bold mb-2">工序参数</div>
          <template v-for="(field, key) in processFields" :key="key">
            <el-form-item :label="field.label" :prop="'processData.' + key">
              <!-- 选择器类型 -->
              <template v-if="field.type === 'select'">
                <el-select
                  v-model="completeForm.processData[key]"
                  :disabled="!field.editable"
                  :multiple="field.multiple"
                  style="width: 100%"
                  :placeholder="'请选择' + field.label"
                >
                  <el-option
                    v-for="option in field.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </template>

              <!-- 数字类型 -->
              <template v-else-if="field.type === 'number'">
                <div class="number-input-with-unit">
                  <el-input-number
                    v-model="completeForm.processData[key]"
                    :disabled="!field.editable"
                    :min="field.rules?.min"
                    :max="field.rules?.max"
                    :step="field.rules?.step"
                    :precision="2"
                    style="width: 100%"
                    :placeholder="'请输入' + field.label"
                  />
                  <span v-if="field.unit" class="unit-label">{{ field.unit }}</span>
                </div>
              </template>

              <!-- 字符串类型 -->
              <template v-else>
                <el-input
                  v-model="completeForm.processData[key]"
                  :disabled="!field.editable"
                  :placeholder="field.placeholder || '请输入' + field.label"
                />
              </template>
            </el-form-item>
          </template>
        </div>
      </template>

      <!-- 原有的完成数量相关字段 -->
      <el-form-item label="产出数量" prop="outputQuantity">
        <el-input-number
          v-model="completeForm.outputQuantity"
          :min="currentOperation?.planQuantity"
          :precision="2"
          :step="0.01"
          class="!w-240px"
          @change="handleOutputChange"
        />
      </el-form-item>
      <el-form-item label="合格数量" prop="qualifiedQuantity">
        <el-input-number
          v-model="completeForm.qualifiedQuantity"
          :min="completeForm.outputQuantity"
          :precision="2"
          :step="0.01"
          class="!w-240px"
          @change="handleQualifiedChange"
        />
      </el-form-item>
      <el-form-item label="不合格数量" prop="unqualifiedQuantity">
        <el-input-number
          v-model="completeForm.unqualifiedQuantity"
          :min="0"
          :precision="2"
          :step="0.01"
          disabled
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="completeForm.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="completeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComplete" :loading="completeSubmitting"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>

  <!-- 工序详情弹窗 -->
  <OperationDetailDialog
    v-model:visible="detailDialogVisible"
    :current-detail-operation="currentDetailOperation"
    :detail-process-data="detailProcessData"
  />

  <!-- 记录进度弹窗 -->
  <el-dialog v-model="recordProgressDialogVisible" title="记录进度" width="600px" append-to-body>
    <el-form ref="progressFormRef" :model="progressForm" :rules="progressRules" label-width="120px">
      <!-- 动态工序字段 -->
      <template v-if="Object.keys(processFields).length > 0">
        <div class="mb-4">
          <div class="text-lg font-bold mb-2">工序参数</div>
          <template v-for="(field, key) in processFields" :key="key">
            <el-form-item :label="field.label" :prop="'processData.' + key">
              <!-- 选择器类型 -->
              <template v-if="field.type === 'select'">
                <el-select
                  v-model="progressForm.processData[key]"
                  :disabled="!field.editable"
                  :multiple="field.multiple"
                  style="width: 100%"
                  :placeholder="'请选择' + field.label"
                >
                  <el-option
                    v-for="option in field.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </template>

              <!-- 数字类型 -->
              <template v-else-if="field.type === 'number'">
                <div class="number-input-with-unit">
                  <el-input-number
                    v-model="progressForm.processData[key]"
                    :disabled="!field.editable"
                    :min="field.rules?.min"
                    :max="field.rules?.max"
                    :step="field.rules?.step"
                    :precision="2"
                    style="width: 100%"
                    :placeholder="'请输入' + field.label"
                  />
                  <span v-if="field.unit" class="unit-label">{{ field.unit }}</span>
                </div>
              </template>

              <!-- 字符串类型 -->
              <template v-else>
                <el-input
                  v-model="progressForm.processData[key]"
                  :disabled="!field.editable"
                  :placeholder="field.placeholder || '请输入' + field.label"
                />
              </template>
            </el-form-item>
          </template>
        </div>
      </template>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="progressForm.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="recordProgressDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitProgress" :loading="progressSubmitting"
        >确定</el-button
      >
    </template>
  </el-dialog>

  <!-- 进度记录历史弹窗 -->
  <OperationProgressHistoryDialog
    v-model:visible="progressHistoryDialogVisible"
    :progressHistoryList="progressHistoryList"
    @updated="onProgressHistoryUpdated"
  />
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Icon } from '@/components/Icon'
import OperationProgressCard from './OperationProgressCard.vue'
import OperationDetailDialog from './OperationDetailDialog.vue'
import OperationProgressHistoryDialog from './OperationProgressHistoryDialog.vue'
import OperationStartDialog from './OperationStartDialog.vue'
import {
  YVHgetWorkOrderOperationList,
  YVHgetOperationProgress,
  YVHstartOperation,
  YVHcompleteOperation,
  YVHpauseOperation,
  YVHresumeOperation,
  OperationStatus,
  YVHrecordOperationProgress,
  YVHgetOperationProgressList
} from '@/api/mes/production/order-operation'
import { DeviceApi } from '@/api/iot/device/device'
import { DeviceTypeEnum } from '@/api/iot/product/product'
import { YVHgetProcessOperation } from '@/api/mes/production/process-operation'

// 在 script setup 部分的开头添加响应式变量
const visible = ref(false)
const loading = ref(false)
const tableLoading = ref(false)
const operationList = ref<any[]>([])
const progressData = ref<any>(null)
const workOrderStatus = ref(0)

// 设备数据，从IoT设备API获取
const equipmentOptions = ref<Array<{ id: number; name: string }>>([])

// 在 script setup 部分的接口定义中添加
interface ProcessField {
  type: 'string' | 'number' | 'select'
  label: string
  order?: number
  editable: boolean
  required?: boolean
  unit?: string
  rules?: {
    min?: number
    max?: number
    step?: number
  }
  options?: Array<{
    label: string
    value: string | number
  }>
  multiple?: boolean
  placeholder?: string
}

// 修改响应式变量定义
const processFields = ref<Record<string, ProcessField>>({})

// 开始工序相关
const startDialogVisible = ref(false)
const startSubmitting = ref(false)
const currentOperation = ref<any>(null)

// 完成工序相关
const completeDialogVisible = ref(false)
const completeSubmitting = ref(false)
const completeFormRef = ref()
const completeForm = reactive({
  outputQuantity: 0,
  qualifiedQuantity: 0,
  unqualifiedQuantity: 0,
  remark: '',
  processData: {} as Record<string, any>
})

// 修改完成工序相关的验证规则
const completeRules = computed(() => {
  const rules = {
    outputQuantity: [{ required: true, message: '请输入产出数量', trigger: 'blur' }],
    qualifiedQuantity: [{ required: true, message: '请输入合格数量', trigger: 'blur' }],
    processData: {} as Record<string, any[]>
  }

  // 添加动态字段的验证规则
  Object.entries(processFields.value).forEach(([key, field]) => {
    const fieldRules: any[] = []

    // 必填验证
    if (field.required) {
      fieldRules.push({
        required: true,
        message: `请输入${field.label}`,
        trigger: 'blur'
      })
    }

    // 数字类型的验证
    if (field.type === 'number' && field.rules) {
      fieldRules.push({
        type: 'number',
        min: field.rules.min,
        max: field.rules.max,
        message: `${field.label}必须在 ${field.rules.min} 到 ${field.rules.max} 之间`,
        trigger: 'blur'
      })
    }

    if (fieldRules.length > 0) {
      rules.processData[key] = fieldRules
    }
  })

  return rules
})

// 记录进度相关
const recordProgressDialogVisible = ref(false)
const progressHistoryDialogVisible = ref(false)
const progressHistoryList = ref<any[]>([])
const progressSubmitting = ref(false)
const progressFormRef = ref()
const progressForm = reactive({
  processData: {} as Record<string, any>,
  remark: '',
  currentQuantity: 0,
  qualifiedQuantity: 0,
  unqualifiedQuantity: 0
})

// 查看详情相关
const detailDialogVisible = ref(false)
const detailProcessData = ref<Record<string, any>>({})
const currentDetailOperation = ref<any>(null)

// 添加一个计算属性来获取操作人信息
const getOperationExecution = (operationId: number) => {
  if (!progressData.value?.operations) return null
  const operation = progressData.value.operations.find((op) => op.id === operationId)
  return operation?.currentExecution || null
}

// 修改查看详情的处理函数
const handleViewDetail = async (row: any) => {
  // 从progressData中获取完整的工序信息（兼容不同ID字段）
  const operation = progressData.value?.operations?.find(
    (op: any) => op.id === row.id || op.id === row.operationId
  )

  if (!operation) {
    console.error('未找到工序执行信息')
    // 也允许打开空的详情弹窗，避免用户无反馈
    currentDetailOperation.value = null
    detailProcessData.value = {}
    detailDialogVisible.value = true
    return
  }

  console.log('工序详细信息:', {
    basicInfo: {
      operationName: row.operationName,
      sequence: row.sequence,
      status: row.status,
      completionRate: row.completionRate
    },
    executionInfo: operation.currentExecution,
    processData: operation.processData
  })

  // 解析并设置详情数据
  currentDetailOperation.value = operation
  try {
    const raw = operation.processData
    const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw || {}
    detailProcessData.value = parsed
  } catch (e) {
    console.error('解析工序参数失败:', e)
    detailProcessData.value = {}
  }
  detailDialogVisible.value = true
}

// 获取设备列表
const loadEquipmentOptions = async () => {
  try {
    // 获取直连设备类型的设备列表
    const res = await DeviceApi.getSimpleDeviceList(DeviceTypeEnum.DEVICE)
    if (res && Array.isArray(res)) {
      equipmentOptions.value = res.map((item) => ({
        id: item.id,
        name: item.deviceName
      }))
    } else if (res?.data && Array.isArray(res.data)) {
      equipmentOptions.value = res.data.map((item) => ({
        id: item.id,
        name: item.deviceName
      }))
    } else {
      console.error('获取设备列表失败: 返回数据格式不正确', res)
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
  }
}

const getStatusType = (status: number) => {
  switch (status) {
    case OperationStatus.PENDING:
      return 'info'
    case OperationStatus.IN_PROGRESS:
      return 'warning'
    case OperationStatus.COMPLETED:
      return 'success'
    case OperationStatus.PAUSED:
      return 'danger'
    default:
      return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case OperationStatus.PENDING:
      return '未开始'
    case OperationStatus.IN_PROGRESS:
      return '进行中'
    case OperationStatus.COMPLETED:
      return '已完成'
    case OperationStatus.PAUSED:
      return '已暂停'
    default:
      return '未知'
  }
}

const open = async (orderId: number, status: number) => {
  console.log('打开工序执行弹窗，工单ID:', orderId, '工单状态:', status)
  visible.value = true
  loading.value = true
  workOrderStatus.value = status // 保存工单状态
  operationList.value = [] // 清空之前的数据
  progressData.value = null // 清空之前的数据

  try {
    // 并行加载数据
    await Promise.all([loadOperationList(orderId), loadProgress(orderId), loadEquipmentOptions()])
  } catch (error) {
    console.error('加载工序数据失败:', error)
    ElMessage.error('加载工序数据失败')
  } finally {
    loading.value = false
  }
}

const loadOperationList = async (orderId: number) => {
  tableLoading.value = true
  try {
    const res = await YVHgetWorkOrderOperationList(orderId)
    if (Array.isArray(res)) {
      operationList.value = res
      console.log('工序列表数据:', operationList.value)
    } else if (res?.data && Array.isArray(res.data)) {
      operationList.value = res.data
      console.log('工序列表数据:', operationList.value)
    } else {
      console.error('获取工序列表失败: 返回数据格式不正确', res)
    }

    // 工序列表加载完成后，根据已存在的进度数据回填 executionId，避免并发顺序导致的缺失
    if (progressData.value) {
      updateOperationExecutionIds(progressData.value)
    }
  } catch (error) {
    console.error('获取工序列表失败:', error)
  } finally {
    tableLoading.value = false
  }
}

const loadProgress = async (orderId: number) => {
  try {
    const res = await YVHgetOperationProgress(orderId)
    if (typeof res === 'object' && !Array.isArray(res)) {
      progressData.value = res
      console.log('工序进度数据:', progressData.value)

      // 更新工序列表中的执行ID
      updateOperationExecutionIds(res)
    } else if (res?.code === 0 && typeof res.data === 'object' && !Array.isArray(res.data)) {
      progressData.value = res.data
      console.log('工序进度数据:', progressData.value)

      // 更新工序列表中的执行ID
      updateOperationExecutionIds(res.data)
    } else {
      console.error('获取工序进度失败: 返回数据格式不正确', res)
    }
  } catch (error) {
    console.error('获取工序进度失败:', error)
    ElMessage.error('获取工序进度失败')
  }
}

// 从进度数据中更新工序的执行ID
const updateOperationExecutionIds = (progressData: any) => {
  if (!progressData || !progressData.operations || !Array.isArray(progressData.operations)) return

  // 将进度数据中的执行ID更新到工序列表
  progressData.operations.forEach((opProgress: any) => {
    const operation = operationList.value.find(
      (op) =>
        op.id === opProgress.id ||
        op.operationId === opProgress.id ||
        (typeof opProgress.operationId !== 'undefined' &&
          (op.id === opProgress.operationId || op.operationId === opProgress.operationId))
    )
    if (operation && opProgress.currentExecution) {
      // 更新执行ID和其他可能需要的信息
      operation.executionId = opProgress.currentExecution.id
      operation.workerId = opProgress.currentExecution.workerId
      operation.workerName = opProgress.currentExecution.workerName
      operation.equipmentId = opProgress.currentExecution.equipmentId
      operation.equipmentName = opProgress.currentExecution.equipmentName
    }
  })
}

// 开始工序
const handleStart = (row: any) => {
  currentOperation.value = row
  startDialogVisible.value = true
}

const handleEquipmentChange = (equipmentId: number) => {
  const equipment = equipmentOptions.value.find((item) => item.id === equipmentId)
  if (equipment && currentOperation.value) {
    // 保留此函数以兼容可能的外部调用，但已不再直接修改子组件表单
  }
}

const onStartSubmit = async (payload: {
  workerName: string
  equipmentId?: number
  equipmentName?: string
  inputQuantity: number
  remark: string
}) => {
  if (!currentOperation.value) return
  startSubmitting.value = true
  tableLoading.value = true
  try {
    await YVHstartOperation({
      id: currentOperation.value.id,
      workerId: Date.now(),
      workerName: payload.workerName,
      equipmentId: payload.equipmentId,
      equipmentName: payload.equipmentName || '',
      inputQuantity: payload.inputQuantity,
      remark: payload.remark
    })
    ElMessage.success('开始工序成功')
    startDialogVisible.value = false
    await loadOperationList(currentOperation.value.orderId)
    await loadProgress(currentOperation.value.orderId)
  } catch (error) {
    console.error('开始工序失败:', error)
    ElMessage.error('开始工序失败')
  } finally {
    startSubmitting.value = false
    tableLoading.value = false
  }
}

// 完成工序
const handleComplete = async (row: any) => {
  console.log('完成工序', row)
  currentOperation.value = row
  completeForm.outputQuantity = 0
  completeForm.qualifiedQuantity = 0
  completeForm.unqualifiedQuantity = 0
  completeForm.remark = ''
  completeForm.processData = {}

  // 从 progressData 中找到对应的操作记录
  const operation = progressData.value?.operations?.find((op: any) => op.id === row.id)

  if (operation?.processData) {
    // 如果在 progressData 中已经有 processData，直接使用
    try {
      const parsedProcessData =
        typeof operation.processData === 'string'
          ? JSON.parse(operation.processData)
          : operation.processData

      processFields.value = {}

      // 提取每个字段的配置信息
      Object.entries(parsedProcessData).forEach(([key, fieldData]: [string, any]) => {
        // 提取字段配置（去除 value）
        const { value, ...fieldConfig } = fieldData
        processFields.value[key] = fieldConfig

        // 初始化表单值
        completeForm.processData[key] = value || ''
      })
    } catch (error) {
      console.error('解析工序数据失败:', error)
    }
  } else {
    // 如果没有，则调用接口获取
    try {
      const processInfo = await YVHgetProcessOperation(row.operationId)
      if (processInfo?.fieldsConfig) {
        processFields.value = processInfo.fieldsConfig
        // 初始化表单数据
        Object.entries(processInfo.fieldsConfig).forEach(([key, field]: [string, any]) => {
          completeForm.processData[key] = ''
        })
      }
    } catch (error) {
      console.error('获取工序信息失败:', error)
    }
  }

  completeDialogVisible.value = true
}

const handleOutputChange = (value: number) => {
  if (value < completeForm.qualifiedQuantity) {
    completeForm.qualifiedQuantity = value
  }
  completeForm.unqualifiedQuantity = value - completeForm.qualifiedQuantity
}

const handleQualifiedChange = (value: number) => {
  completeForm.unqualifiedQuantity = completeForm.outputQuantity - value
}

// 在 script setup 部分添加接口定义
interface CompleteOperationRequest {
  id: number
  executionId: number
  outputQuantity: number
  qualifiedQuantity: number
  unqualifiedQuantity: number
  remark?: string
  processData?: Record<string, any>
}

// 修改提交完成的函数
const submitComplete = () => {
  completeFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return

    // 若当前行缺少 executionId，尝试从 progressData 回填
    if (!currentOperation.value.executionId && progressData.value?.operations) {
      const matched = progressData.value.operations.find(
        (op: any) =>
          op.id === currentOperation.value.id || op.id === currentOperation.value.operationId
      )
      if (matched?.currentExecution?.id) {
        currentOperation.value.executionId = matched.currentExecution.id
      }
    }

    // 确保有执行ID
    if (!currentOperation.value.executionId) {
      ElMessage.error('无法完成工序：缺少执行ID')
      return
    }

    completeSubmitting.value = true
    tableLoading.value = true
    try {
      // 构建工序参数的数据结构，包含完整的字段配置
      const processDataWithConfig = Object.entries(completeForm.processData).reduce(
        (acc, [key, value]) => {
          const fieldConfig = processFields.value[key]
          acc[key] = {
            ...fieldConfig, // 保留所有配置信息
            value // 添加用户输入的值
          }
          return acc
        },
        {} as Record<string, any>
      )

      const request: CompleteOperationRequest = {
        id: currentOperation.value.id,
        executionId: currentOperation.value.executionId,
        outputQuantity: completeForm.outputQuantity,
        qualifiedQuantity: completeForm.qualifiedQuantity,
        unqualifiedQuantity: completeForm.unqualifiedQuantity,
        remark: completeForm.remark,
        processData: processDataWithConfig
      }

      console.log('提交的完整数据：', JSON.stringify(request, null, 2))
      await YVHcompleteOperation(request)
      ElMessage.success('完成工序成功')
      completeDialogVisible.value = false
      await loadOperationList(currentOperation.value.orderId)
      await loadProgress(currentOperation.value.orderId)
    } catch (error) {
      console.error('完成工序失败:', error)
      ElMessage.error('完成工序失败')
    } finally {
      completeSubmitting.value = false
      tableLoading.value = false
    }
  })
}

// 暂停工序
const handlePause = async (row: any) => {
  // 若缺少 executionId，尝试从 progressData 回填
  if (!row.executionId && progressData.value?.operations) {
    const matched = progressData.value.operations.find(
      (op: any) => op.id === row.id || op.id === row.operationId
    )
    if (matched?.currentExecution?.id) {
      row.executionId = matched.currentExecution.id
    }
  }

  // 确保有执行ID
  if (!row.executionId) {
    ElMessage.error('无法暂停工序：缺少执行ID')
    return
  }

  tableLoading.value = true
  try {
    await YVHpauseOperation({
      id: row.id,
      executionId: row.executionId,
      remark: '暂停生产'
    })
    ElMessage.success('暂停工序成功')
    await loadOperationList(row.orderId)
    await loadProgress(row.orderId)
  } catch (error) {
    console.error('暂停工序失败:', error)
    ElMessage.error('暂停工序失败')
  } finally {
    tableLoading.value = false
  }
}

// 恢复工序
const handleResume = async (row: any) => {
  tableLoading.value = true
  try {
    await YVHresumeOperation({
      id: row.id,
      workerId: row.workerId,
      workerName: row.workerName,
      equipmentId: row.equipmentId,
      equipmentName: row.equipmentName,
      remark: '恢复生产'
    })
    ElMessage.success('恢复工序成功')
    await loadOperationList(row.orderId)
    await loadProgress(row.orderId)
  } catch (error) {
    console.error('恢复工序失败:', error)
    ElMessage.error('恢复工序失败')
  } finally {
    tableLoading.value = false
  }
}

// 添加记录进度的表单验证规则
const progressRules = computed(() => {
  const rules = {
    processData: {} as Record<string, any[]>
  }

  // 添加动态字段的验证规则
  Object.entries(processFields.value).forEach(([key, field]) => {
    const fieldRules: any[] = []
    if (field.required) {
      fieldRules.push({
        required: true,
        message: `请输入${field.label}`,
        trigger: 'blur'
      })
    }
    if (field.type === 'number' && field.rules) {
      fieldRules.push({
        type: 'number',
        min: field.rules.min,
        max: field.rules.max,
        message: `${field.label}必须在 ${field.rules.min} 到 ${field.rules.max} 之间`,
        trigger: 'blur'
      })
    }
    if (fieldRules.length > 0) {
      rules.processData[key] = fieldRules
    }
  })

  return rules
})

// 添加记录进度的处理函数
const handleRecordProgress = async (row: any) => {
  console.log('row:', row)
  console.log('progressData:', progressData.value)

  // 从 progressData 中找到对应的操作记录
  const operation = progressData.value?.operations?.find((op: any) => op.id === row.id)
  if (!operation?.currentExecution?.id) {
    ElMessage.warning('未找到执行记录')
    return
  }

  currentOperation.value = {
    ...row,
    executionId: operation.currentExecution.id
  }
  progressForm.remark = ''
  progressForm.processData = {}

  // 获取工序配置信息
  try {
    const processInfo = await YVHgetProcessOperation(row.operationId)
    if (processInfo?.fieldsConfig) {
      processFields.value = processInfo.fieldsConfig
      // 初始化表单数据
      Object.entries(processInfo.fieldsConfig).forEach(([key, field]: [string, any]) => {
        progressForm.processData[key] = ''
      })
    }
  } catch (error) {
    console.error('获取工序信息失败:', error)
  }

  recordProgressDialogVisible.value = true
}

// 添加提交进度记录的函数
const submitProgress = () => {
  progressFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return

    progressSubmitting.value = true
    tableLoading.value = true
    try {
      // 构建工序参数的数据结构
      const processDataWithConfig = Object.entries(progressForm.processData).reduce(
        (acc, [key, value]) => {
          const fieldConfig = processFields.value[key]
          acc[key] = {
            ...fieldConfig,
            value
          }
          return acc
        },
        {} as Record<string, any>
      )

      await YVHrecordOperationProgress({
        executionId: currentOperation.value.executionId,
        processData: JSON.stringify(processDataWithConfig),
        remark: progressForm.remark
      })

      ElMessage.success('记录进度成功')
      recordProgressDialogVisible.value = false
      await loadOperationList(currentOperation.value.orderId)
      await loadProgress(currentOperation.value.orderId)
    } catch (error) {
      console.error('记录进度失败:', error)
      ElMessage.error('记录进度失败')
    } finally {
      progressSubmitting.value = false
      tableLoading.value = false
    }
  })
}

// 添加查看进度记录的处理函数
const lastViewedExecutionId = ref<number | null>(null)
const handleViewProgressHistory = async (row: any) => {
  console.log('row:', row)
  console.log('progressData:', progressData.value)

  // 从 progressData 中找到对应的操作记录
  const operation = progressData.value?.operations?.find((op: any) => op.id === row.id)
  const executionId = operation?.currentExecution?.id

  if (!executionId) {
    ElMessage.warning('未找到执行记录')
    return
  }

  lastViewedExecutionId.value = executionId

  try {
    const res = await YVHgetOperationProgressList(executionId)
    progressHistoryList.value = Array.isArray(res) ? res : res?.data || []
    progressHistoryDialogVisible.value = true
  } catch (error) {
    console.error('获取进度记录失败:', error)
    ElMessage.error('获取进度记录失败')
  }
}

// 历史记录更新后的刷新函数
const onProgressHistoryUpdated = async () => {
  if (!lastViewedExecutionId.value) return
  try {
    const res = await YVHgetOperationProgressList(lastViewedExecutionId.value)
    progressHistoryList.value = Array.isArray(res) ? res : res?.data || []
  } catch (error) {
    console.error('刷新进度记录失败:', error)
  }
}

// 添加一个计算属性来获取动态列
const processDataColumns = computed(() => {
  if (!progressHistoryList.value?.length) return []

  // 从第一条记录中获取所有可能的字段
  const firstRecord = progressHistoryList.value[0]
  if (!firstRecord?.processData) return []

  const processData = JSON.parse(firstRecord.processData) as Record<
    string,
    { label: string; order?: number; [k: string]: any }
  >
  const entries = Object.entries(processData) as Array<
    [string, { label: string; order?: number; [k: string]: any }]
  >
  return entries
    .sort((a, b) => (a[1].order ?? 0) - (b[1].order ?? 0))
    .map(([key, field]) => ({
      label: field.label,
      key,
      minWidth: '120'
    }))
})

// 添加格式化工序参数值的函数
const formatProcessDataValue = (field: any) => {
  if (!field) return ''

  // 如果是选择器类型且有选项
  if (field.type === 'select' && field.options) {
    if (Array.isArray(field.value)) {
      // 多选
      return field.value
        .map((v: any) => field.options.find((opt: any) => opt.value === v)?.label || v)
        .join('、')
    } else {
      // 单选
      const option = field.options.find((opt: any) => opt.value === field.value)
      return option ? option.label : field.value
    }
  }

  // 如果是数字类型且有单位
  if (field.type === 'number' && field.unit) {
    return `${field.value}${field.unit}`
  }

  return field.value
}

// 组件挂载时加载设备列表
onMounted(() => {
  loadEquipmentOptions()
})

defineExpose({ open })
</script>

<style lang="scss" scoped>
.mobile-form {
  padding: 0 4px;
}
.mobile-form__section {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}
.mobile-form__section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}
.mobile-item-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-item-card {
  background: #f9f9fb;
  border-radius: 8px;
  padding: 12px;
  border: 1px solid #ebeef5;
  &__header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
  &__index {
    font-size: 12px;
    color: #909399;
    font-weight: 600;
  }
  &__name {
    flex: 1;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &__body {
    font-size: 13px;
  }
  &__info-row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
  }
  &__info-label {
    color: #909399;
    flex-shrink: 0;
  }
  &__info-value {
    color: #606266;
    text-align: right;
  }
  &__footer {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #f0f0f0;
  }
}
.mobile-empty-tip {
  text-align: center;
  color: #909399;
  padding: 20px 0;
  font-size: 14px;
}
.text-lg {
  font-size: 16px;
}
.font-bold {
  font-weight: bold;
}
.mb-2 {
  margin-bottom: 8px;
}
.mb-4 {
  margin-bottom: 16px;
}
.number-input-with-unit {
  display: flex;
  align-items: center;
  gap: 8px;
}
.unit-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}
</style>
