<template>
  <doc-alert title="【MES】工序记录" url="https://doc.iocoder.cn/mes/process-record/" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="mb-4" :model="queryParams" ref="queryFormRef" :inline="true" label-width="80px">
      <el-form-item label="批次号">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工序类型">
        <el-select
          v-model="selectedProcessType"
          placeholder="请选择工序类型"
          clearable
          class="!w-240px"
          @change="handleProcessTypeChange"
        >
          <el-option
            v-for="item in processTypes"
            :key="item.code"
            :label="`${item.name} (${item.code})`"
            :value="item.code"
          >
            <div class="flex items-center">
              <span class="mr-1">{{ item.name }}</span>
              <span class="text-gray-400 text-sm">({{ item.code }})</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="未开始" :value="0" />
          <el-option label="进行中" :value="2" />
          <el-option label="完成" :value="1" />
          <el-option label="异常" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 数据展示部分 -->
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>工序记录列表</span>
      </div>
    </template>

    <el-table :data="filteredTableData" border style="width: 100%">
      <!-- 基础信息列 -->
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="batchNo" label="批次号" width="120" />
      <el-table-column label="工序信息" min-width="100">
        <template #default="{ row }">
          <div class="process-info">
            <span class="process-name">{{ row.processName }}</span>
            <span class="process-code">{{ row.processCode }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="operator" label="操作员" width="100" />
      <el-table-column label="处理时间" width="120">
        <template #default="{ row }">
          {{ formatDateTime(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 动态工序数据列 -->
      <template v-if="selectedProcessType">
        <template v-for="field in getTableColumns(filteredTableData[0])" :key="field.prop">
          <el-table-column
            :prop="'processData.' + field.prop + '.value'"
            :label="field.label"
            min-width="120"
          >
            <template #default="{ row }">
              <span>
                {{ formatFieldValue(row.processData[field.prop]) }}
              </span>
            </template>
          </el-table-column>
        </template>
      </template>

      <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />

      <!-- 操作列 -->
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" @click="handleViewProcessData(row)"> 查看/编辑 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 工序数据详情对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="currentProcess?.processName + ' - 工序数据'"
    width="600px"
  >
    <el-form
      v-if="currentProcess"
      ref="formRef"
      :model="editingProcessData"
      label-width="140px"
      :rules="formRules"
    >
      <template v-for="(field, key) in currentProcess.processData" :key="key">
        <el-form-item :label="field.label" :required="field.required" :prop="key">
          <!-- 选择器类型 -->
          <template v-if="field.type === 'select'">
            <el-select
              v-model="editingProcessData[key]"
              :disabled="!field.editable"
              style="width: 100%"
            >
              <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="editingProcessData[key]"
                :disabled="!field.editable"
                :min="field.rules?.min"
                :max="field.rules?.max"
                :step="field.rules?.step"
                :precision="2"
                style="width: 100%"
              />
              <span v-if="field.unit" class="unit-label">{{ field.unit }}</span>
            </div>
          </template>

          <!-- 字符串类型 -->
          <template v-else>
            <el-input
              v-model="editingProcessData[key]"
              :disabled="!field.editable"
              :placeholder="field.placeholder"
            />
          </template>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveProcessData"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Icon } from '@/components/Icon'

// 接口定义
interface ProcessRecord {
  id: number
  processName: string
  processCode: string
  startTime: string
  endTime: string
  operator: string
  status: number
  remark: string
  processData: Record<string, any>
  batchNo: string // Added batchNo to the interface
}

interface ProcessField {
  value: any
  label: string
  editable: boolean
  required?: boolean
  type: string
  rules?: {
    min?: number
    max?: number
    step?: number
  }
  unit?: string
  showInTable?: boolean
  order?: number
  options?: Array<{
    label: string
    value: string | number
  }>
  placeholder?: string
  multiple?: boolean
}

interface QueryParams {
  pageNo: number
  pageSize: number
  batchNo?: string
  status?: number
}

// 响应式变量定义
const loading = ref(true)
const total = ref(0)
const queryFormRef = ref<FormInstance>()
const selectedProcessType = ref('')
const dialogVisible = ref(false)
const currentProcess = ref<ProcessRecord | null>(null)
const editingProcessData = reactive<Record<string, any>>({})
const formRef = ref<FormInstance>()

// 查询参数
const queryParams = reactive<QueryParams>({
  pageNo: 1,
  pageSize: 10,
  batchNo: undefined,
  status: undefined
})

// 工序类型列表
const processTypes = [
  { name: '焊接工序', code: 'WELDING' },
  { name: '热处理工序', code: 'HEAT_TREATMENT' },
  { name: '装配工序', code: 'ASSEMBLY' },
  { name: '质量检验', code: 'QUALITY_CHECK' }
]

// 查询操作
const handleQuery = () => {
  // TODO: 实现查询逻辑
  console.log('查询参数：', queryParams)
}

// 重置操作
const resetQuery = () => {
  queryFormRef.value?.resetFields?.()
  queryParams.batchNo = undefined
  queryParams.status = undefined
  selectedProcessType.value = ''
  handleQuery()
}

// 模拟数据，实际应该从API获取
const mockData = {
  code: 0,
  data: [
    {
      processData: {
        weldingTemperature: {
          value: 200.5,
          label: '焊接温度',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 1000,
            step: 0.1
          },
          unit: '°C',
          showInTable: true,
          order: 1
        },
        inspectionResult: {
          value: '合格',
          label: '检验结果',
          editable: true,
          required: true,
          type: 'select',
          options: [
            { label: '合格', value: '合格' },
            { label: '不合格', value: '不合格' }
          ],
          showInTable: true,
          order: 3
        },
        weldingMethod: {
          value: '电弧焊',
          label: '焊接方法',
          editable: false,
          type: 'string',
          showInTable: true,
          order: 2
        },
        weldingPressure: {
          value: 2.4,
          label: '焊接压力',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 10,
            step: 0.1
          },
          unit: 'MPa',
          showInTable: false
        },
        weldingMaterial: {
          value: '不锈钢',
          label: '焊接材料',
          editable: true,
          type: 'string',
          placeholder: '请输入焊接材料',
          showInTable: false
        }
      },
      processName: '焊接工序',
      processCode: 'WELDING',
      startTime: '2024-03-19 10:00:00',
      remark: '焊接质量良好',
      id: 1,
      batchNo: 'B202403190001',
      endTime: '2024-03-19 11:30:00',
      operator: '张三',
      status: 1
    },
    {
      processData: {
        surfaceHardness: {
          value: 58,
          label: '表面硬度',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 100,
            step: 1
          },
          unit: 'HRC',
          showInTable: true,
          order: 2
        },
        deformation: {
          value: 0.02,
          label: '变形量',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 1,
            step: 0.01
          },
          unit: 'mm',
          showInTable: false
        },
        holdingTime: {
          value: 120,
          label: '保温时间',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 300,
            step: 1
          },
          unit: 'min',
          showInTable: true,
          order: 3
        },
        heatingTemperature: {
          value: 800,
          label: '加热温度',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 1200,
            step: 1
          },
          unit: '°C',
          showInTable: true,
          order: 1
        },
        coolingMethod: {
          value: '空冷',
          label: '冷却方式',
          editable: true,
          type: 'select',
          options: [
            { label: '空冷', value: '空冷' },
            { label: '水冷', value: '水冷' },
            { label: '油冷', value: '油冷' }
          ],
          showInTable: false
        }
      },
      processName: '热处理工序',
      processCode: 'HEAT_TREATMENT',
      startTime: '2024-03-19 13:00:00',
      remark: '热处理完成',
      id: 2,
      batchNo: 'B202403190001',
      endTime: '2024-03-19 15:00:00',
      operator: '李四',
      status: 1
    },
    {
      processData: {
        assemblyParts: {
          value: ['轴承', '轴套', '螺栓'],
          label: '装配零件',
          editable: true,
          required: true,
          type: 'select',
          multiple: true,
          options: [
            { label: '轴承', value: '轴承' },
            { label: '轴套', value: '轴套' },
            { label: '螺栓', value: '螺栓' },
            { label: '螺母', value: '螺母' },
            { label: '垫片', value: '垫片' }
          ],
          showInTable: true,
          order: 1
        },
        gapValue: {
          value: 0.03,
          label: '间隙值',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 0.1,
            step: 0.01
          },
          unit: 'mm',
          showInTable: true,
          order: 2
        },
        torque: {
          value: 45.5,
          label: '扭矩',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 100,
            step: 0.5
          },
          unit: 'N·m',
          showInTable: true,
          order: 3
        },
        testResult: {
          value: '通过',
          label: '测试结果',
          editable: true,
          required: true,
          type: 'select',
          options: [
            { label: '通过', value: '通过' },
            { label: '不通过', value: '不通过' },
            { label: '待复检', value: '待复检' }
          ],
          showInTable: true,
          order: 4
        },
        alignmentError: {
          value: 0.02,
          label: '对准误差',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 0.1,
            step: 0.01
          },
          unit: 'mm',
          showInTable: true,
          order: 5
        }
      },
      processName: '装配工序',
      processCode: 'ASSEMBLY',
      startTime: '2024-03-19 15:30:00',
      remark: '装配完成，测试通过',
      id: 3,
      batchNo: 'B202403190002',
      endTime: '2024-03-19 17:00:00',
      operator: '王五',
      status: 1
    },
    {
      processData: {
        inspectionMethod: {
          value: '目视检查',
          label: '检验方法',
          editable: true,
          type: 'select',
          options: [
            { label: '目视检查', value: '目视检查' },
            { label: '尺寸测量', value: '尺寸测量' },
            { label: '无损检测', value: '无损检测' }
          ],
          showInTable: true,
          order: 1
        },
        surfaceQuality: {
          value: '良好',
          label: '表面质量',
          editable: true,
          required: true,
          type: 'select',
          options: [
            { label: '优秀', value: '优秀' },
            { label: '良好', value: '良好' },
            { label: '合格', value: '合格' },
            { label: '不合格', value: '不合格' }
          ],
          showInTable: true,
          order: 2
        },
        dimensionError: {
          value: 0.05,
          label: '尺寸误差',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 1,
            step: 0.01
          },
          unit: 'mm',
          showInTable: true,
          order: 3
        },
        defectCount: {
          value: 0,
          label: '缺陷数量',
          editable: true,
          required: true,
          type: 'number',
          rules: {
            min: 0,
            max: 100,
            step: 1
          },
          showInTable: true,
          order: 4
        }
      },
      processName: '质量检验',
      processCode: 'QUALITY_CHECK',
      startTime: '2024-03-19 17:30:00',
      remark: '产品质量符合要求',
      id: 4,
      batchNo: 'B202403190002',
      endTime: '2024-03-19 18:00:00',
      operator: '赵六',
      status: 1
    }
  ],
  msg: ''
}

const tableData = ref<ProcessRecord[]>(mockData.data)

// 根据选中的工序类型筛选数据
const filteredTableData = computed(() => {
  if (!selectedProcessType.value) {
    return tableData.value
  }
  return tableData.value.filter((item) => item.processCode === selectedProcessType.value)
})

// 生成表单验证规则
const formRules = computed(() => {
  if (!currentProcess.value) return {}

  const rules: Record<string, any[]> = {}
  Object.entries(currentProcess.value.processData).forEach(([key, field]) => {
    if (field.required) {
      rules[key] = [
        {
          required: true,
          message: `请输入${field.label}`,
          trigger: 'blur'
        }
      ]
    }

    if (field.type === 'number' && field.rules) {
      if (!rules[key]) rules[key] = []
      rules[key].push({
        type: 'number',
        min: field.rules.min,
        max: field.rules.max,
        message: `${field.label}必须在 ${field.rules.min} 到 ${field.rules.max} 之间`,
        trigger: 'blur'
      })
    }
  })
  return rules
})

// 格式化标签名称
const formatLabel = (key: string) => {
  const fieldData = currentProcess.value?.processData[key]
  return fieldData?.label || key
}

// 查看/编辑工序数据
const handleViewProcessData = (row: ProcessRecord) => {
  currentProcess.value = row
  // 深拷贝processData以供编辑，只复制value值
  const processDataValues = Object.entries(row.processData).reduce(
    (acc, [key, field]) => {
      acc[key] = field.value
      return acc
    },
    {} as Record<string, any>
  )
  Object.assign(editingProcessData, processDataValues)
  dialogVisible.value = true
}

// 保存工序数据
const handleSaveProcessData = async () => {
  if (!currentProcess.value || !formRef.value) return

  try {
    // 表单验证
    await formRef.value.validate()

    // 更新表格中的数据，保持label不变，只更新value
    const index = tableData.value.findIndex((item) => item.id === currentProcess.value!.id)
    if (index !== -1) {
      const updatedProcessData = Object.entries(editingProcessData).reduce(
        (acc, [key, value]) => {
          acc[key] = {
            ...currentProcess.value!.processData[key],
            value
          }
          return acc
        },
        {} as Record<string, any>
      )

      tableData.value[index].processData = updatedProcessData

      // 将整个表格数据序列化并输出到控制台
      const formattedData = {
        code: 0,
        data: tableData.value,
        msg: ''
      }
      console.log('序列化后的JSON数据：')
      console.log(JSON.stringify(formattedData, null, 2))

      ElMessage.success('保存成功')
      dialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
  }
}

// 工序类型变化处理
const handleProcessTypeChange = (value: string) => {
  // 可以在这里添加其他处理逻辑
  console.log('选中的工序类型：', value)
}

// 获取当前工序需要显示的列
const getProcessColumns = computed(() => {
  if (!currentProcess.value) return []

  const processData = currentProcess.value.processData
  return Object.entries(processData)
    .filter(([_, field]) => field.showInTable)
    .sort((a, b) => (a[1].order || 0) - (b[1].order || 0))
    .map(([key, field]) => ({
      prop: key,
      label: field.label,
      formatter: (row: any) => {
        const value = row.processData[key].value
        const unit = row.processData[key].unit
        if (Array.isArray(value)) {
          return value.join('、')
        }
        return unit ? `${value}${unit}` : value
      }
    }))
})

// 获取表格列配置
const getTableColumns = (row: any) => {
  if (!row) return []
  return Object.entries(row.processData)
    .filter(([_, field]) => (field as ProcessField).showInTable)
    .sort((a, b) => ((a[1] as ProcessField).order || 0) - ((b[1] as ProcessField).order || 0))
    .map(([key, field]) => ({
      prop: key,
      label: (field as ProcessField).label
    }))
}

// 格式化字段值
const formatFieldValue = (field: ProcessField | undefined) => {
  if (!field) return ''

  const { value, unit } = field
  if (Array.isArray(value)) {
    return value.join('、')
  }
  return unit ? `${value}${unit}` : value
}

// 在 script 部分添加新的方法
const formatDateTime = (time: string) => {
  if (!time) return '-'
  return time
}

const getStatusType = (status: number) => {
  const statusMap: Record<number, 'success' | 'warning' | 'info' | 'danger'> = {
    0: 'info', // 未开始
    1: 'success', // 完成
    2: 'warning', // 进行中
    3: 'danger' // 异常
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '未开始',
    1: '完成',
    2: '进行中',
    3: '异常'
  }
  return statusMap[status] || '未知'
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb-4 {
  margin-bottom: 16px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.number-input-with-unit {
  display: flex;
  align-items: center;
  gap: 8px;
}
.unit-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}
:deep(.el-form-item__label) {
  word-break: break-word;
  white-space: pre-wrap;
  line-height: 1.2;
  padding-right: 12px;
}
.process-code {
  color: #909399;
  font-size: 13px;
  margin-left: 8px;
}
.process-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.process-name {
  font-size: 14px;
  color: var(--el-text-color-primary);
}
.process-code {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

:deep(.el-form-item) {
  margin-bottom: 18px;
  margin-right: 16px;
}

:deep(.el-form-item__content) {
  display: flex;
  align-items: center;
}

:deep(.el-select) {
  width: 240px;
}
</style>
