<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="90%" :append-to-body="true">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <!-- 原料质检：关联采购订单 -->
      <el-form-item v-if="props.inspectionType === 1" label="关联采购订单" prop="relatedDocumentNo">
        <el-input v-model="selectedPurchaseOrderNo" readonly placeholder="请选择采购订单" style="width: 100%">
          <template #append>
            <el-button @click="openPurchaseOrderSelector">
              <Icon icon="ep:search" /> 选择
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <!-- 过程质检：无关联单据 -->
      <el-form-item v-if="props.inspectionType === 2" label="关联单据" prop="relatedDocumentNo">
        <el-input disabled placeholder="过程质检无需关联单据" style="width: 100%" />
      </el-form-item>

      <!-- 产品质检：关联销售订单 -->
      <el-form-item v-if="props.inspectionType === 3" label="关联销售订单" prop="relatedDocumentNo">
        <el-input v-model="selectedSaleOrderNo" readonly placeholder="请选择销售订单" style="width: 100%">
          <template #append>
            <el-button @click="openSaleOrderSelector">
              <Icon icon="ep:search" /> 选择
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <!-- <el-form-item label="罐标" prop="canLabel">
        <el-input v-model="formData.canLabel" placeholder="请输入罐标" />
      </el-form-item> -->
      <el-form-item label="产品名称" prop="productId">
        <div style="display: flex; gap: 8px;">
          <el-select v-model="formData.productId" clearable filterable @change="onChangeProduct" placeholder="请选择产品"
            style="flex: 1">
            <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button v-if="formData.productId" type="primary" size="default" @click="openProductJsonEditor">
            <Icon icon="ep:setting" />
            编辑产品配置
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="产品规格" prop="productSpec">
        <el-input v-model="formData.productSpec" placeholder="请先选择产品" readonly />
      </el-form-item>
      <el-form-item label="质检员" prop="inspector">
        <el-input v-model="formData.inspector" placeholder="请输入质检员" />
      </el-form-item>
      <el-form-item label="附件" prop="attachmentFile">
        <UploadFile
          v-model="attachmentFiles"
          :limit="1"
          :file-size="10"
          :directory="'quality'"
          @update:model-value="handleAttachmentChange"
        />
      </el-form-item>
      <el-form-item label="质检日期" prop="inspectionDate">
        <el-date-picker v-model="formData.inspectionDate" type="date" value-format="x" placeholder="选择质检日期" />
      </el-form-item>
      <el-form-item label="合格状态" prop="qualifiedStatus">
        <el-select v-model="formData.qualifiedStatus" placeholder="请选择合格状态" disabled>
          <el-option label="合格" value="合格" />
          <el-option label="不合格" value="不合格" />
        </el-select>
        <div style="margin-top: 4px; font-size: 12px; color: #909399;">
          整体合格状态将根据各子项状态自动生成
        </div>
      </el-form-item>

      <!-- 原始质检数据（隐藏，用于保存） -->
      <el-form-item label="质检数据" prop="inspectionData" style="display: none;">
        <el-input v-model="formData.inspectionData" placeholder="请输入质检数据" />
      </el-form-item>
    </el-form>

    <!-- 动态质检表单 - 独立于主表单，避免验证冲突 -->
    <div v-if="dynamicInspectionItems.length > 0" style="margin-top: 20px;">
      <h4 style="margin: 0 0 16px 0; color: #303133;">质检项目</h4>
      <DynamicForm v-model="inspectionFormData" :items="dynamicInspectionItems" :gutter="16" :column-span="12"
        label-width="120px" @form-change="handleInspectionFormChange" />
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 采购订单选择器 -->
  <PurchaseOrderInEnableList ref="purchaseOrderSelectorRef" :title="'选择采购订单（原料质检）'" :in-enable="false"
    @success="handlePurchaseOrderSelect" />

  <!-- 销售订单选择器 -->
  <SaleOrderOutEnableList ref="saleOrderSelectorRef" :title="'选择销售订单（产品质检）'" :out-enable="false"
    @success="handleSaleOrderSelect" />

  <!-- 产品JSON字段编辑弹窗 -->
  <Dialog v-model="productJsonEditorVisible" title="编辑产品配置" width="90%" :append-to-body="true">
    <FormBuilder v-model="productJsonFormItems" title="产品配置字段" :mode="'advanced'"
      :custom-field-types="['text', 'number', 'select']"
      @change="handleProductJsonFormChange" @preview-change="handleProductJsonPreviewChange" />
    <template #footer>
      <el-button @click="productJsonEditorVisible = false">取消</el-button>
      <el-button type="primary" @click="saveProductJsonField" :loading="productJsonSaving">保存配置</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { getAccessToken } from '@/utils/auth'
import { QualityApi, Quality } from '@/api/iot/product-inspection'
import { PurchaseOrderApi, PurchaseOrderVO } from '@/api/erp/purchase/order'
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import { ProductApi, ProductVO, ProductUpdateJsonFieldReqVO } from '@/api/erp/product/product'
import PurchaseOrderInEnableList from '@/views/erp/purchase/order/components/PurchaseOrderInEnableList.vue'
import SaleOrderOutEnableList from '@/views/erp/sale/order/components/SaleOrderOutEnableList.vue'
import DynamicForm, { type DynamicFormItem } from '@/components/DynamicForm'
import FormBuilder, { type FormBuilderItem } from '@/components/FormBuilder'
import { UploadFile } from '@/components/UploadFile'

/** 质检表单通用组件 */
defineOptions({ name: 'QualityForm' })

// 定义props
interface Props {
  inspectionType: number // 质检类型：1-原料质检，2-过程质检，3-产品质检
}

const props = defineProps<Props>()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined as number | undefined,
  canLabel: undefined as string | undefined,
  productId: undefined as number | undefined,
  productName: undefined as string | undefined,
  productSpec: undefined as string | undefined,
  inspector: undefined as string | undefined,
  inspectionDate: undefined as number | undefined,
  qualifiedStatus: undefined as string | undefined,
  inspectionType: props.inspectionType,
  inspectionData: undefined as string | undefined,
  relatedDocumentNo: undefined as number | undefined,
  attachmentUrl: undefined as string | undefined,
  attachmentName: undefined as string | undefined
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref

// 选择器相关数据
const selectedPurchaseOrderNo = ref('')
const selectedSaleOrderNo = ref('')
const purchaseOrderSelectorRef = ref()
const saleOrderSelectorRef = ref()

// 产品相关数据
const productList = ref<ProductVO[]>([])

// 动态质检表单数据
const dynamicInspectionItems = ref<DynamicFormItem[]>([])
const inspectionFormData = ref<Record<string, any>>({})

// 产品JSON字段编辑相关数据
const productJsonEditorVisible = ref(false)
const productJsonFormItems = ref<FormBuilderItem[]>([])
const productJsonSaving = ref(false)
const currentProductJsonData = ref<Record<string, any>>({})
const productJsonPreviewData = ref<Record<string, any>>({})

// 附件上传相关数据
const attachmentFiles = ref<string>('')
const fileList = ref<any[]>([])
const uploading = ref(false)

/** 处理附件变化 */
const handleAttachmentChange = (value: string | string[]) => {
  // UploadFile 组件返回的是URL字符串或URL数组
  if (typeof value === 'string' && value) {
    formData.value.attachmentUrl = value
    // 从URL中提取文件名
    const urlParts = value.split('/')
    const fileName = urlParts[urlParts.length - 1]
    formData.value.attachmentName = decodeURIComponent(fileName)
  } else if (Array.isArray(value) && value.length > 0) {
    // 如果是数组，取第一个
    formData.value.attachmentUrl = value[0]
    const urlParts = value[0].split('/')
    const fileName = urlParts[urlParts.length - 1]
    formData.value.attachmentName = decodeURIComponent(fileName)
  } else {
    // 清空附件
    formData.value.attachmentUrl = undefined
    formData.value.attachmentName = undefined
  }
}

/** 打开采购订单选择器 */
const openPurchaseOrderSelector = () => {
  purchaseOrderSelectorRef.value.open()
}

/** 打开销售订单选择器 */
const openSaleOrderSelector = () => {
  saleOrderSelectorRef.value.open()
}

/** 处理采购订单选择 */
const handlePurchaseOrderSelect = (order: PurchaseOrderVO) => {
  formData.value.relatedDocumentNo = order.id
  selectedPurchaseOrderNo.value = order.no
}

/** 处理销售订单选择 */
const handleSaleOrderSelect = (order: SaleOrderVO) => {
  formData.value.relatedDocumentNo = order.id
  selectedSaleOrderNo.value = order.no
}

/** 处理动态质检表单变化 */
const handleInspectionFormChange = (value: Record<string, any>) => {
  // 可以在这里添加额外的处理逻辑
  console.log('质检表单数据变化:', value)

  // 自动计算整体合格状态
  updateOverallQualifiedStatus(value)
}

/** 根据子项合格状态自动更新整体合格状态 */
const updateOverallQualifiedStatus = (inspectionData: Record<string, any>) => {
  // 获取所有子项的合格状态
  const qualifiedStatuses: string[] = []

  Object.keys(inspectionData).forEach(key => {
    if (key.endsWith('_qualified') && inspectionData[key] !== null && inspectionData[key] !== undefined) {
      qualifiedStatuses.push(inspectionData[key])
    }
  })

  console.log('子项合格状态:', qualifiedStatuses)
  console.log('质检数据:', inspectionData)

  // 如果有子项状态，则根据子项状态决定整体状态
  if (qualifiedStatuses.length > 0) {
    // 如果所有子项都合格，则整体合格；否则整体不合格
    // 兼容 'true' 和 '合格' 两种值
    const allQualified = qualifiedStatuses.every(status => status === '合格' || status === 'true')
    console.log('所有子项都合格:', allQualified)
    formData.value.qualifiedStatus = allQualified ? '合格' : '不合格'
    console.log('设置整体合格状态为:', formData.value.qualifiedStatus)
  }
}

/** 打开产品JSON字段编辑器 */
const openProductJsonEditor = async () => {
  if (!formData.value.productId) {
    message.warning('请先选择产品')
    return
  }

  try {
    // 获取产品详情
    const productDetail = await ProductApi.getProduct(formData.value.productId)

    // 解析现有的JSON字段数据
    let existingJsonData: Record<string, any> = {}
    if (productDetail.jsonField) {
      try {
        const jsonConfig = JSON.parse(productDetail.jsonField)

        // 检查是否是新的配置格式（包含标准字段）
        if (jsonConfig.items && Array.isArray(jsonConfig.items)) {
          // 新格式：直接使用 FormBuilder 配置
          productJsonFormItems.value = jsonConfig.items.map((item: any) => ({
            id: item.id || `product_config_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            label: item.label,
            key: item.key,
            type: item.type,
            defaultValue: item.defaultValue,
            placeholder: item.placeholder,
            required: item.required,
            disabled: item.disabled,
            // 质检标准相关属性
            standard: item.standard || '',
            standardType: item.standardType || 'text',
            standardValue: item.standardValue || '',
            standardRange: item.standardRange || { min: 0, max: 100 },
            standardOptions: item.standardOptions || [],
            showStandard: item.showStandard !== undefined ? item.showStandard : true,
            // 其他属性
            ...(item.type === 'number' && {
              min: item.min,
              max: item.max,
              step: item.step,
              precision: item.precision
            }),
            ...(item.type === 'textarea' && {
              rows: item.rows,
              maxlength: item.maxlength
            }),
            ...(item.type === 'select' && {
              options: item.options || []
            }),
            ...(item.type === 'date' && {
              dateType: item.dateType,
              format: item.format,
              valueFormat: item.valueFormat
            }),
            ...(item.type === 'switch' && {
              activeText: item.activeText,
              inactiveText: item.inactiveText
            }),
            rules: item.rules
          }))

          // 设置预览数据
          if (jsonConfig.previewData) {
            productJsonPreviewData.value = jsonConfig.previewData
          }
        } else {
          // 旧格式：使用原来的解析方法
          existingJsonData = jsonConfig
          productJsonFormItems.value = Object.entries(existingJsonData).map(([key, value], index) => ({
            id: `product_config_${index + 1}`,
            label: getFieldLabel(key),
            key: key,
            type: getFieldTypeByValue(value),
            defaultValue: value,
            placeholder: `请输入${getFieldLabel(key)}`,
            // 初始化标准字段
            standard: '',
            standardType: 'text',
            standardValue: '',
            standardRange: { min: 0, max: 100 },
            standardOptions: [],
            showStandard: true,
            required: false
          }))
        }
      } catch (e) {
        console.warn('解析产品JSON字段失败:', e)
        productJsonFormItems.value = []
      }
    } else {
      // 如果没有现有数据，显示空状态，让用户自己添加字段
      productJsonFormItems.value = []
    }

    currentProductJsonData.value = existingJsonData
    productJsonEditorVisible.value = true
  } catch (error) {
    console.error('获取产品详情失败:', error)
    message.error('获取产品详情失败')
  }
}

/** 处理产品JSON表单变化 */
const handleProductJsonFormChange = (items: FormBuilderItem[]) => {
  productJsonFormItems.value = items
}

/** 处理产品JSON预览数据变化 */
const handleProductJsonPreviewChange = (value: Record<string, any>) => {
  console.log('预览数据变化:', value)
  productJsonPreviewData.value = value
}

/** 保存产品JSON字段 */
const saveProductJsonField = async () => {
  if (!formData.value.productId) {
    message.warning('请先选择产品')
    return
  }

  try {
    productJsonSaving.value = true

    // 保存 FormBuilder 的完整配置，包括标准字段
    console.log('FormBuilder 配置数据:', productJsonFormItems.value)

    // 清理和验证配置数据，确保每个字段项都有完整的结构以兼容LabView
    const cleanedItems = productJsonFormItems.value.map(item => {
      // 创建完整的字段结构，确保所有字段都存在（即使为空值）
      const cleanedItem: any = {
        // 基础字段
        id: item.id || `product_config_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        label: item.label || '',
        key: item.key || '',
        type: item.type || 'text',
        defaultValue: item.defaultValue,
        placeholder: item.placeholder || '',
        required: item.required !== undefined ? item.required : false,
        disabled: item.disabled !== undefined ? item.disabled : false,

        // 标准相关字段（所有类型都包含，即使不适用也赋空值）
        standard: item.standard || '',
        standardType: item.standardType || 'text',
        standardValue: item.standardValue || 0,
        standardRange: item.standardRange || { min: 0, max: 100 },
        standardOptions: item.standardOptions || [],
        showStandard: item.showStandard !== undefined ? item.showStandard : true,

        // number 类型专用字段
        min: 0,
        max: 0,
        step: 0,
        precision: 0,

        // select 类型专用字段
        options: [],

        // text 类型专用字段（支持rows和maxlength）
        rows: 1,
        maxlength: 100,

        // 其他字段
        rules: item.rules
      }

      // 清理 defaultValue，确保类型匹配
      if (cleanedItem.type === 'text' && typeof cleanedItem.defaultValue === 'number') {
        cleanedItem.defaultValue = String(cleanedItem.defaultValue)
      } else if (cleanedItem.type === 'number' && typeof cleanedItem.defaultValue === 'string') {
        const numValue = parseFloat(cleanedItem.defaultValue)
        cleanedItem.defaultValue = isNaN(numValue) ? null : numValue
      }

      // 根据实际类型设置对应字段的值
      if (item.type === 'number') {
        cleanedItem.min = item.min !== undefined ? item.min : 0
        cleanedItem.max = item.max !== undefined ? item.max : 100
        cleanedItem.step = item.step !== undefined ? item.step : 0.1
        cleanedItem.precision = item.precision !== undefined ? item.precision : 1
        // number类型保留standardRange
        cleanedItem.standardRange = item.standardRange || { min: 0, max: 100 }
      } else if (item.type === 'select') {
        cleanedItem.options = item.options || []
        cleanedItem.standardOptions = item.standardOptions || []
        // 非number类型清空standardRange
        cleanedItem.standardRange = { min: 0, max: 100 }
      } else if (item.type === 'text') {
        // text类型支持rows和maxlength属性
        cleanedItem.rows = item.rows !== undefined ? item.rows : 1
        cleanedItem.maxlength = item.maxlength !== undefined ? item.maxlength : 100
        // 非number类型清空standardRange
        cleanedItem.standardRange = { min: 0, max: 100 }
      } else {
        // 其他类型清空standardRange
        cleanedItem.standardRange = { min: 0, max: 100 }
      }

      return cleanedItem
    })

    // 构建包含标准字段的完整配置
    const formBuilderConfig = {
      items: cleanedItems,
      previewData: productJsonPreviewData.value
    }

    console.log('最终保存的完整配置:', formBuilderConfig)

    // 调用API更新产品JSON字段
    const updateData: ProductUpdateJsonFieldReqVO = {
      id: formData.value.productId,
      jsonField: JSON.stringify(formBuilderConfig)
    }

    await ProductApi.updateJsonField(updateData)

    productJsonEditorVisible.value = false
    message.success('产品配置保存成功')

    // 保存成功后，重新生成质检表单
    if (formData.value.productId) {
      const product = productList.value.find((item) => item.id === formData.value.productId)
      if (product) {
        await generateDynamicInspectionForm(product)
      }
    }
  } catch (error) {
    console.error('保存产品JSON字段失败:', error)
    message.error('保存产品配置失败')
  } finally {
    productJsonSaving.value = false
  }
}

/** 处理产品变更 */
const onChangeProduct = async (productId: number | null) => {
  if (productId) {
    try {
      // 获取完整的产品信息，包含 standard 字段
      const productDetail = await ProductApi.getProduct(productId)

      formData.value.productName = productDetail.name
      formData.value.productSpec = productDetail.standard || '暂无规格'

      // 根据产品生成动态质检表单，传递已获取的产品详情
      await generateDynamicInspectionForm(productDetail, productDetail)
    } catch (error) {
      console.error('获取产品详情失败:', error)
      message.error('获取产品详情失败')

      // 如果获取详情失败，使用简单列表中的信息
      const product = productList.value.find((item) => item.id === productId)
      if (product) {
        formData.value.productName = product.name
        formData.value.productSpec = '暂无规格'
        await generateDynamicInspectionForm(product)
      }
    }
  } else {
    // 清空产品选择时，清空相关字段
    formData.value.productName = ''
    formData.value.productSpec = ''
    dynamicInspectionItems.value = []
    inspectionFormData.value = {}
  }
}

/** 生成动态质检表单 */
const generateDynamicInspectionForm = async (product: ProductVO, productDetail?: any) => {
  try {
    // 如果没有传入产品详情，则获取产品详情
    let productInfo = productDetail
    if (!productInfo) {
      productInfo = await ProductApi.getProduct(product.id)
    }

    let inspectionItems: DynamicFormItem[] = []

    // 如果产品有jsonField配置，则解析jsonField
    if (productInfo.jsonField) {
      try {
        const jsonConfig = JSON.parse(productInfo.jsonField)

        // 检查是否是新的配置格式（包含标准字段）
        if (jsonConfig.items && Array.isArray(jsonConfig.items)) {
          // 新格式：直接使用 FormBuilder 配置
          inspectionItems = jsonConfig.items.map((item: any) => ({
            key: item.key,
            label: item.label,
            type: item.type,
            placeholder: item.placeholder || `请输入${item.label}`,
            defaultValue: item.defaultValue,
            required: item.required,
            disabled: item.disabled,
            // 传递质检标准相关属性
            standard: item.standard,
            standardType: item.standardType,
            standardValue: item.standardValue,
            standardRange: item.standardRange,
            standardOptions: item.standardOptions,
            showStandard: item.showStandard,
            // 传递其他属性
            ...(item.type === 'number' && {
              min: item.min,
              max: item.max,
              step: item.step,
              precision: item.precision
            }),
            ...(item.type === 'textarea' && {
              rows: item.rows,
              maxlength: item.maxlength
            }),
            ...(item.type === 'select' && {
              options: item.options || []
            }),
            ...(item.type === 'date' && {
              dateType: item.dateType || 'date',
              format: item.format,
              valueFormat: item.valueFormat
            }),
            ...(item.type === 'switch' && {
              activeText: item.activeText,
              inactiveText: item.inactiveText
            }),
            rules: item.rules
          }))
        } else {
          // 旧格式：使用原来的解析方法
          inspectionItems = parseJsonFieldToInspectionItems(jsonConfig)
        }
      } catch (e) {
        console.warn('解析产品JSON字段失败，使用默认配置:', e)
        inspectionItems = getDefaultInspectionItems()
      }
    } else {
      // 如果没有jsonField，使用默认配置
      inspectionItems = getDefaultInspectionItems()
    }

    // 为每个质检项目添加对应的合格状态字段
    const itemsWithQualifiedStatus: DynamicFormItem[] = []

    inspectionItems.forEach((item: DynamicFormItem) => {
      // 添加原始质检项目
      itemsWithQualifiedStatus.push(item)

      // 为每个质检项目添加对应的合格状态字段
      itemsWithQualifiedStatus.push({
        key: `${item.key}_qualified`,
        label: '合格状态',
        type: 'radio',
        options: [
          { label: '合格', value: '合格' },
          { label: '不合格', value: '不合格' }
        ]
      })
    })

    dynamicInspectionItems.value = itemsWithQualifiedStatus
    inspectionFormData.value = {}

    // 初始化表单数据
    itemsWithQualifiedStatus.forEach((item: DynamicFormItem) => {
      // 为合格状态字段设置默认值为"合格"
      if (item.key.endsWith('_qualified')) {
        inspectionFormData.value[item.key] = '合格'
      } else {
        // 使用默认值，如果没有默认值则为 undefined（不使用 null）
        inspectionFormData.value[item.key] = item.defaultValue !== undefined ? item.defaultValue : undefined
      }
    })

    // 初始化完成后，计算整体合格状态
    updateOverallQualifiedStatus(inspectionFormData.value)
  } catch (error) {
    console.error('生成动态质检表单失败:', error)
    // 出错时使用默认配置
    const defaultItems = getDefaultInspectionItems()

    // 为默认配置也添加合格状态字段
    const itemsWithQualifiedStatus: DynamicFormItem[] = []

    defaultItems.forEach((item: DynamicFormItem) => {
      // 添加原始质检项目
      itemsWithQualifiedStatus.push(item)

      // 为每个质检项目添加对应的合格状态字段
      itemsWithQualifiedStatus.push({
        key: `${item.key}_qualified`,
        label: '合格状态',
        type: 'radio',
        options: [
          { label: '合格', value: '合格' },
          { label: '不合格', value: '不合格' }
        ]
      })
    })

    dynamicInspectionItems.value = itemsWithQualifiedStatus
    inspectionFormData.value = {}
    itemsWithQualifiedStatus.forEach((item: DynamicFormItem) => {
      // 为合格状态字段设置默认值为"合格"
      if (item.key.endsWith('_qualified')) {
        inspectionFormData.value[item.key] = '合格'
      } else {
        // 使用默认值，如果没有默认值则为 undefined（不使用 null）
        inspectionFormData.value[item.key] = item.defaultValue !== undefined ? item.defaultValue : undefined
      }
    })

    // 初始化完成后，计算整体合格状态
    updateOverallQualifiedStatus(inspectionFormData.value)
  }
}

/** 解析产品JSON字段为质检项目 */
const parseJsonFieldToInspectionItems = (jsonConfig: Record<string, any>): DynamicFormItem[] => {
  const items: DynamicFormItem[] = []

  // 遍历JSON配置，将每个字段转换为DynamicFormItem
  Object.entries(jsonConfig).forEach(([key, value]) => {
    let type: DynamicFormItem['type'] = 'text'

    // 根据值的类型推断字段类型
    if (typeof value === 'number') {
      type = 'number'
    } else if (typeof value === 'boolean') {
      type = 'switch'
    } else if (Array.isArray(value)) {
      type = 'select'
    } else if (typeof value === 'string') {
      // 检查是否是日期格式
      if (value.match(/^\d{4}-\d{2}-\d{2}/)) {
        type = 'date'
      } else if (value.length > 50) {
        type = 'textarea'
      } else {
        type = 'text'
      }
    }

    items.push({
      key,
      label: getFieldLabel(key),
      type,
      placeholder: `请输入${getFieldLabel(key)}`
    })
  })

  return items
}

/** 获取字段标签 */
const getFieldLabel = (key: string): string => {
  const labelMap: Record<string, string> = {
    config1: '产品配置1',
    config2: '产品配置2',
    config3: '产品配置3',
    weight: '重量',
    color: '颜色',
    purity: '纯度',
    moisture: '水分含量',
    temperature: '温度',
    pressure: '压力',
    flowRate: '流量',
    status: '状态',
    quality: '质量等级',
    defectCount: '缺陷数量',
    remark: '备注'
  }
  return labelMap[key] || key
}

/** 根据值类型获取字段类型 */
const getFieldTypeByValue = (value: any): 'text' | 'number' | 'select' | 'textarea' | 'date' | 'switch' => {
  if (typeof value === 'number') {
    return 'number'
  } else if (typeof value === 'boolean') {
    return 'switch'
  } else if (Array.isArray(value)) {
    return 'select'
  } else if (typeof value === 'string') {
    if (value.match(/^\d{4}-\d{2}-\d{2}/)) {
      return 'date'
    } else if (value.length > 50) {
      return 'textarea'
    } else {
      return 'text'
    }
  }
  return 'text'
}

/** 获取默认质检项目 */
const getDefaultInspectionItems = (): DynamicFormItem[] => {
  return [
    {
      key: 'quality',
      label: '质量等级',
      type: 'select',
      placeholder: '请选择质量等级',
      options: [
        { label: '优等品', value: 'excellent' },
        { label: '一等品', value: 'first' },
        { label: '合格品', value: 'qualified' },
        { label: '不合格品', value: 'unqualified' }
      ]
    },
    {
      key: 'defectCount',
      label: '缺陷数量',
      type: 'number',
      placeholder: '请输入缺陷数量',
      min: 0,
      max: 100,
      precision: 0,
      step: 1
    },
    {
      key: 'remark',
      label: '备注',
      type: 'text',
      placeholder: '请输入备注信息'
    }
  ]
}


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const qualityData = await QualityApi.getQuality(id)
      formData.value = qualityData
      // 初始化附件文件
      if (qualityData.attachmentUrl) {
        attachmentFiles.value = qualityData.attachmentUrl
      }
      // 如果有关联单据号，需要显示对应的订单号
      if (formData.value.relatedDocumentNo) {
        await loadSelectedOrderInfo()
      }

      // 解析质检数据并生成动态表单
      if (formData.value.productName) {
        // 通过产品名称查找产品
        const product = productList.value.find((item) => item.name === formData.value.productName)
        if (product) {
          // 设置产品ID以便后续操作
          formData.value.productId = product.id
          await generateDynamicInspectionForm(product)
          // 解析已保存的质检数据
          if (formData.value.inspectionData) {
            try {
              const parsedData = JSON.parse(formData.value.inspectionData)
              inspectionFormData.value = parsedData
            } catch (error) {
              console.error('解析质检数据失败:', error)
              inspectionFormData.value = {}
            }
          }
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}

/** 加载已选择的订单信息 */
const loadSelectedOrderInfo = async () => {
  if (!formData.value.relatedDocumentNo) return

  try {
    if (props.inspectionType === 1) {
      // 原料质检：加载采购订单信息
      const order = await PurchaseOrderApi.getPurchaseOrder(formData.value.relatedDocumentNo)
      selectedPurchaseOrderNo.value = order.no
    } else if (props.inspectionType === 3) {
      // 产品质检：加载销售订单信息
      const order = await SaleOrderApi.getSaleOrder(formData.value.relatedDocumentNo)
      selectedSaleOrderNo.value = order.no
    }
  } catch (error) {
    console.error('加载订单信息失败:', error)
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 验证必填的质检项目
  const missingFields: string[] = []
  dynamicInspectionItems.value.forEach((item: DynamicFormItem) => {
    // 只验证非合格状态字段
    if (!item.key.endsWith('_qualified') && item.required) {
      const value = inspectionFormData.value[item.key]
      // 检查值是否为空（undefined、null、空字符串）
      if (value === undefined || value === null || value === '') {
        missingFields.push(item.label)
      }
    }
  })

  if (missingFields.length > 0) {
    message.error(`请填写必填项目：${missingFields.join('、')}`)
    return
  }

  // 生成适合LabView解析的质检数据结构
  const labviewCompatibleData = generateLabviewCompatibleInspectionData()

  // 将质检数据转换为JSON字符串
  formData.value.inspectionData = JSON.stringify(labviewCompatibleData)

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Quality
    if (formType.value === 'create') {
      await QualityApi.createQuality(data)
      message.success(t('common.createSuccess'))
    } else {
      await QualityApi.updateQuality(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 生成适合LabView解析的质检数据结构 */
const generateLabviewCompatibleInspectionData = (): any => {
  // 获取产品配置信息，用于获取标准信息
  let productConfig: any = null
  if (formData.value.productId) {
    try {
      // 从动态表单项中获取产品配置（因为已经加载过了）
      // 这里简化处理，实际应该从产品详情中获取
    } catch (error) {
      console.warn('获取产品配置失败:', error)
    }
  }

  // 构建LabView兼容的数据结构
  const resultData: any = {
    // 基础信息
    productName: formData.value.productName || '',
    productSpec: formData.value.productSpec || '',
    inspector: formData.value.inspector || '',
    inspectionDate: formData.value.inspectionDate,
    qualifiedStatus: formData.value.qualifiedStatus || '合格',

    // 质检项目数组 - 每个项目都有相同的字段结构
    inspectionItems: [] as any[]
  }

  // 获取所有非合格状态的字段（实际的检测项目）
  const inspectionKeys = Object.keys(inspectionFormData.value).filter(key => !key.endsWith('_qualified'))

  inspectionKeys.forEach(key => {
    const value = inspectionFormData.value[key]
    const qualifiedKey = `${key}_qualified`
    const qualifiedValue = inspectionFormData.value[qualifiedKey]

    // 查找对应的配置项以获取标准信息
    const configItem = dynamicInspectionItems.value.find(item => item.key === key)

    // 构建统一的检测项目结构
    const inspectionItem = {
      // 基础字段
      itemKey: key,
      itemName: configItem?.label || getFieldDisplayName(key),
      result: value !== undefined && value !== null ? value : '',
      qualified: qualifiedValue || '合格',

      // 标准相关字段（确保所有项目都有相同的字段结构）
      standard: configItem?.standard || '',
      standardType: configItem?.standardType || 'text',
      standardValue: configItem?.standardValue || '',
      standardRange: configItem?.standardRange || { min: 0, max: 100 },
      standardOptions: configItem?.standardOptions || [],

      // 类型相关字段（确保所有项目都有相同的字段结构）
      fieldType: configItem?.type || 'text',
      min: configItem?.type === 'number' ? (configItem.min || 0) : 0,
      max: configItem?.type === 'number' ? (configItem.max || 100) : 0,
      step: configItem?.type === 'number' ? (configItem.step || 0.1) : 0,
      precision: configItem?.type === 'number' ? (configItem.precision || 1) : 0,
      options: configItem?.type === 'select' ? (configItem.options || []) : [],

      // text 类型专用字段（支持rows和maxlength）
      rows: configItem?.type === 'text' ? (configItem.rows || 1) : 1,
      maxlength: configItem?.type === 'text' ? (configItem.maxlength || 100) : 10,

      // 其他预留字段，确保结构统一
      placeholder: configItem?.placeholder || '',
      required: configItem?.required || false,
      disabled: configItem?.disabled || false,
      showStandard: configItem?.showStandard !== undefined ? configItem.showStandard : true
    }

    resultData.inspectionItems.push(inspectionItem)
  })

  return resultData
}

/** 获取字段显示名称 */
const getFieldDisplayName = (key: string): string => {
  const nameMap: Record<string, string> = {
    quality: '质量等级',
    defectCount: '缺陷数量',
    remark: '备注',
    weight: '重量',
    color: '颜色',
    purity: '纯度',
    moisture: '水分含量',
    temperature: '温度',
    pressure: '压力',
    flowRate: '流量',
    status: '状态'
  }
  return nameMap[key] || key
}

/** 附件上传前验证 */
const beforeUpload = (file: File) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('上传文件大小不能超过 10MB!')
    return false
  }
  uploading.value = true
  return true
}

/** 附件上传成功处理 */
const handleUploadSuccess = (response: any, file: any) => {
  uploading.value = false
  if (response.code === 0) {
    formData.value.attachmentUrl = response.data.url
    formData.value.attachmentName = file.name
    message.success('附件上传成功')
  } else {
    message.error('附件上传失败')
  }
}

/** 附件上传失败处理 */
const handleUploadError = () => {
  uploading.value = false
  message.error('附件上传失败')
}

/** 附件移除处理 */
const handleRemove = () => {
  formData.value.attachmentUrl = undefined
  formData.value.attachmentName = undefined
  fileList.value = []
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined as number | undefined,
    canLabel: undefined as string | undefined,
    productId: undefined as number | undefined,
    productName: undefined as string | undefined,
    productSpec: undefined as string | undefined,
    inspector: undefined as string | undefined,
    inspectionDate: undefined as number | undefined,
    qualifiedStatus: undefined as string | undefined,
    inspectionType: props.inspectionType,
    inspectionData: undefined as string | undefined,
    relatedDocumentNo: undefined as number | undefined,
    attachmentUrl: undefined as string | undefined,
    attachmentName: undefined as string | undefined
  }
  selectedPurchaseOrderNo.value = ''
  selectedSaleOrderNo.value = ''
  dynamicInspectionItems.value = []
  inspectionFormData.value = {}
  fileList.value = []
  attachmentFiles.value = ''
  formRef.value?.resetFields()
}

/** 初始化 */
onMounted(async () => {
  // 加载产品列表
  productList.value = await ProductApi.getProductSimpleList()
})
</script>
