<template>
  <el-dialog v-model="visibleProxy" title="进度记录历史" width="1000px" append-to-body>
    <el-table :data="progressHistoryList" border stripe>
      <el-table-column type="index" label="序号" width="60" align="center" />

      <!-- 动态工序参数列 -->
      <template v-for="column in processDataColumns" :key="column.key">
        <el-table-column :label="column.label" :min-width="column.minWidth" show-overflow-tooltip>
          <template #default="{ row }">
            <template v-if="row.processData">
              {{ formatProcessDataValue(JSON.parse(row.processData)[column.key]) }}
            </template>
          </template>
        </el-table-column>
      </template>

      <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
      <el-table-column label="记录时间" prop="createTime" width="180" align="center" />

      <!-- 操作列：编辑进度记录 -->
      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            @click="openEdit(row)"
            v-hasPermi="['mes:production-order:operations']"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="visibleProxy = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 编辑进度记录弹窗 -->
  <el-dialog v-model="editDialogVisible" title="编辑进度记录" width="600px" append-to-body>
    <el-form ref="editFormRef" :model="editForm" label-width="120px">
      <template v-if="Object.keys(editFieldsConfig).length > 0">
        <div class="mb-6 bg-gray-50 p-4 rounded">
          <div class="text-base font-bold mb-4 text-gray-700">工序参数</div>
          <template v-for="(field, key) in editFieldsConfig" :key="key">
            <el-form-item :label="field.label" class="mb-4">
              <!-- 选择器类型 -->
              <template v-if="field.type === 'select'">
                <el-select
                  v-model="editForm.processData[key]"
                  :disabled="field.editable === false"
                  :multiple="field.multiple"
                  :placeholder="'请选择' + field.label"
                  class="!w-[280px]"
                >
                  <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="flex items-center">
                  <el-input-number
                    v-model="editForm.processData[key]"
                    :disabled="field.editable === false"
                    :min="field.rules?.min ?? 0"
                    :max="field.rules?.max ?? Infinity"
                    :step="field.rules?.step ?? 1"
                    controls-position="right"
                    class="!w-[180px]"
                  />
                  <span v-if="field.unit" class="ml-2 text-gray-600">{{ field.unit }}</span>
                </div>
              </template>

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

      <el-form-item label="备注">
        <el-input
          v-model="editForm.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          class="!w-[380px]"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit" :loading="editSubmitting">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { YVHupdateOperationProgress } from '@/api/mes/production/order-operation'

const props = defineProps<{
  visible: boolean
  progressHistoryList: any[]
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'updated'): void
}>()

const visibleProxy = computed({
  get: () => props.visible,
  set: (val: boolean) => emit('update:visible', val)
})

const processDataColumns = computed(() => {
  if (!props.progressHistoryList?.length)
    return [] as Array<{ label: string; key: string; minWidth: string }>
  const firstRecord = props.progressHistoryList[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
}

// 编辑相关
const editDialogVisible = ref(false)
const editSubmitting = ref(false)
const editFormRef = ref()
const editingRecordId = ref<number | null>(null)
const editFieldsConfig = ref<Record<string, any>>({})
const editForm = reactive({
  processData: {} as Record<string, any>,
  remark: ''
})

const openEdit = (row: any) => {
  editingRecordId.value = row.id
  editForm.remark = row.remark || ''
  const parsed = row.processData ? JSON.parse(row.processData) : {}
  editFieldsConfig.value = parsed
  editForm.processData = Object.entries(parsed).reduce(
    (acc: Record<string, any>, [key, field]: [string, any]) => {
      acc[key] = field?.value ?? ''
      return acc
    },
    {}
  )
  editDialogVisible.value = true
}

const submitEdit = async () => {
  if (!editingRecordId.value) return
  try {
    editSubmitting.value = true
    const processDataWithConfig = Object.entries(editForm.processData).reduce(
      (acc, [key, value]) => {
        const fieldConfig = editFieldsConfig.value[key]
        acc[key] = {
          ...fieldConfig,
          value
        }
        return acc
      },
      {} as Record<string, any>
    )

    await YVHupdateOperationProgress({
      id: editingRecordId.value,
      processData: JSON.stringify(processDataWithConfig),
      remark: editForm.remark
    })

    ElMessage.success('更新成功')
    editDialogVisible.value = false
    emit('updated')
  } catch (error) {
    console.error('更新进度记录失败:', error)
    ElMessage.error('更新失败')
  } finally {
    editSubmitting.value = false
  }
}
</script>
