<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="80%" :close-on-click-modal="false">
    <!-- 折叠面板区域 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="top"
      class="material-edit-form"
      size="small"
    >
      <div class="section-title">基本信息</div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="物料号" prop="materialNo">
            <el-input
              v-model="formData.materialNo"
              :placeholder="isViewMode ? '' : ''"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料长描述" prop="materialName">
            <el-input
              v-model="formData.materialName"
              :placeholder="isViewMode ? '' : ''"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="基本单位" prop="sapBaseUnit">
            <el-input
              v-model="formData.sapBaseUnit"
              :placeholder="isViewMode ? '' : ''"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="内部款号" prop="internalStyleNo">
            <el-input
              v-model="formData.internalStyleNo"
              :placeholder="isViewMode ? '' : ''"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户编号" prop="sapCustomerCode">
            <el-input
              v-model="formData.sapCustomerCode"
              :placeholder="isViewMode ? '' : ''"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="section-title">公共字段</div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="客户物料编号" prop="customerMaterialNo">
            <el-input v-model="formData.customerMaterialNo" placeholder="" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户款号" prop="styleNo">
            <el-input
              v-model="formData.styleNo"
              :placeholder="isViewMode ? '' : '请输入客户款号'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="条形码" prop="barcode">
            <el-input
              v-model="formData.barcode"
              :placeholder="isViewMode ? '' : '请输入条形码'"
              :disabled="isViewMode"
              @input="handleBarcodeInput(formData, 'barcode')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="formData.name"
              :placeholder="isViewMode ? '' : '请输入名称'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="颜色" prop="color">
            <el-input
              v-model="formData.color"
              :placeholder="isViewMode ? '' : '请输入颜色'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="尺码" prop="size">
            <el-input
              v-model="formData.size"
              :placeholder="isViewMode ? '' : '请输入尺码'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规格型号" prop="specificationModel">
            <el-input
              v-model="formData.specificationModel"
              :placeholder="isViewMode ? '' : '请输入规格型号'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="成分" prop="composition">
            <el-input
              v-model="formData.composition"
              :placeholder="isViewMode ? '' : '请输入成分'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="section-title">B2B字段</div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="价格" prop="price">
            <!-- <el-input-number
              v-model="formData.price"
              :precision="2"
              :step="0.01"
              :min="0"
              :placeholder="isViewMode ? '' : '请输入价格'"
              style="width: 100%"
              :disabled="isViewMode"
            /> -->
              <el-input
              v-model="formData.price"
              :placeholder="isViewMode ? '' : '请输入价格'"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="PO号" prop="poNo">
            <el-input
              v-model="formData.poNo"
              :placeholder="isViewMode ? '' : '请输入PO号'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品牌" prop="brand">
            <el-input
              v-model="formData.brand"
              :placeholder="isViewMode ? '' : '请输入品牌'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品名" prop="productName">
            <el-input
              v-model="formData.productName"
              :placeholder="isViewMode ? '' : '请输入品名'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="系列" prop="series">
            <el-input
              v-model="formData.series"
              :placeholder="isViewMode ? '' : '请输入系列'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计划跟踪号" prop="planTrackingNo">
            <el-input
              v-model="formData.planTrackingNo"
              :placeholder="isViewMode ? '' : '请输入计划跟踪号'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产型号" prop="productionModel">
            <el-input
              v-model="formData.productionModel"
              :placeholder="isViewMode ? '' : '请输入生产型号'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产地" prop="origin">
            <el-input
              v-model="formData.origin"
              :placeholder="isViewMode ? '' : '请输入产地'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="款式名称" prop="styleName">
            <el-input
              v-model="formData.styleName"
              :placeholder="isViewMode ? '' : '请输入款式名称'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户公司登记号" prop="customerCompanyRegNo">
            <el-input
              v-model="formData.customerCompanyRegNo"
              :placeholder="isViewMode ? '' : '请输入客户公司登记号'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="上衣条形码" prop="topBarcode">
            <el-input
              v-model="formData.topBarcode"
              :placeholder="isViewMode ? '' : '请输入上衣条形码'"
              :disabled="isViewMode"
              @input="handleBarcodeInput(formData, 'topBarcode')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="上衣名称" prop="topName">
            <el-input
              v-model="formData.topName"
              :placeholder="isViewMode ? '' : '请输入上衣名称'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="上衣SKU" prop="topSku">
            <el-input
              v-model="formData.topSku"
              :placeholder="isViewMode ? '' : '请输入上衣SKU'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="裤子条形码" prop="pantsBarcode">
            <el-input
              v-model="formData.pantsBarcode"
              :placeholder="isViewMode ? '' : '请输入裤子条形码'"
              :disabled="isViewMode"
              @input="handleBarcodeInput(formData, 'pantsBarcode')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="裤子名称" prop="pantsName">
            <el-input
              v-model="formData.pantsName"
              :placeholder="isViewMode ? '' : '请输入裤子名称'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="裤子SKU" prop="pantsSku">
            <el-input
              v-model="formData.pantsSku"
              :placeholder="isViewMode ? '' : '请输入裤子SKU'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="section-title">自定义字段</div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="自定义字段1" prop="customField1">
            <el-input
              v-model="formData.customField1"
              :placeholder="isViewMode ? '' : '请输入自定义字段1'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="自定义字段2" prop="customField2">
            <el-input
              v-model="formData.customField2"
              :placeholder="isViewMode ? '' : '请输入自定义字段2'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="自定义字段3" prop="customField3">
            <el-input
              v-model="formData.customField3"
              :placeholder="isViewMode ? '' : '请输入自定义字段3'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="自定义字段4" prop="customField4">
            <el-input
              v-model="formData.customField4"
              :placeholder="isViewMode ? '' : '请输入自定义字段4'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="自定义字段5" prop="customField5">
            <el-input
              v-model="formData.customField5"
              :placeholder="isViewMode ? '' : '请输入自定义字段5'"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button v-if="!isViewMode" type="primary" @click="submitForm" :loading="formLoading">
        确定
      </el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { getMaterialBaseInfo, updateMaterialBaseInfo } from '@/api/print/materialInfo'
defineOptions({ name: 'MaterialEditForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const type = ref('') // 操作类型：create-新增；update-修改
const activeNames = ref(['1', '2', '3', '4']) // 默认展开所有折叠面板

// 基础信息字段（根据后端VO字段映射）
const basicInfoFields = ref([
  { label: '物料号', value: '', field: 'materialNo' },
  { label: '物料长描述', value: '', field: 'materialName' },
  { label: '客户编码', value: '', field: 'sapCustomerCode' },
  { label: '客户物料编号', value: '', field: 'customerMaterialNo' },
  { label: '物料类型(SAP)', value: '', field: 'sapMaterialType' },
  { label: '基本单位(SAP)', value: '', field: 'sapBaseUnit' }
])

// 表单数据（根据后端MaterialBaseInfoSaveReqVO字段名映射）
const formData = ref({
  id: undefined, // 新增时为空，编辑时需要
  materialNo: '', // 物料号
  materialName: '', // 物料长描述
  customerMaterialNo: '', // 客户物料编号
  styleNo: '', // 款号
  barcode: '', // 条形码
  name: '', // 名称
  color: '', // 颜色
  size: '', // 尺码
  specificationModel: '', // 规格型号（注意这里是specificationModel）
  composition: '', // 成分
  price: 0, // 价格
  poNo: '', // PO号
  brand: '', // 品牌
  productName: '', // 品名
  series: '', // 系列
  planTrackingNo: '', // 计划跟踪号
  productionModel: '', // 生产型号
  origin: '', // 产地
  styleName: '', // 款式名称
  customerCompanyRegNo: '', // 客户公司登记号（注意这里是customerCompanyRegNo）
  topBarcode: '', // 上衣条形码
  topName: '', // 上衣名称
  topSku: '', // 上衣SKU
  pantsBarcode: '', // 裤子条形码
  pantsName: '', // 裤子名称
  pantsSku: '', // 裤子SKU
  customField1: '', // 自定义字段1
  customField2: '', // 自定义字段2
  customField3: '', // 自定义字段3
  customField4: '', // 自定义字段4
  customField5: '', // 自定义字段5
  sapBaseUnit: '', // 基本单位(SAP)
  sapCustomerCode: '', // 客户编号
  internalStyleNo: '' // 内部款号
})

// 表单校验规则（根据后端VO必填字段设置）
const formRules = reactive({
  materialNo: [{ required: true, message: '物料号不能为空', trigger: 'blur' }],
  materialName: [{ required: true, message: '物料长描述不能为空', trigger: 'blur' }],
  styleNo: [{ required: false, message: '款号不能为空', trigger: 'blur' }],
  barcode: [{ required: false, message: '条形码不能为空', trigger: 'blur' }],
  name: [{ required: false, message: '名称不能为空', trigger: 'blur' }],
  color: [{ required: false, message: '颜色不能为空', trigger: 'blur' }],
  size: [{ required: false, message: '尺码不能为空', trigger: 'blur' }],
  specificationModel: [{ required: false, message: '规格型号不能为空', trigger: 'blur' }],
  composition: [{ required: false, message: '成分不能为空', trigger: 'blur' }],
  price: [{ required: false, message: '价格不能为空', trigger: 'blur' }],
  poNo: [{ required: false, message: 'PO号不能为空', trigger: 'blur' }],
  brand: [{ required: false, message: '品牌不能为空', trigger: 'blur' }],
  productName: [{ required: false, message: '品名不能为空', trigger: 'blur' }],
  series: [{ required: false, message: '系列不能为空', trigger: 'blur' }],
  planTrackingNo: [{ required: false, message: '计划跟踪号不能为空', trigger: 'blur' }],
  productionModel: [{ required: false, message: '生产型号不能为空', trigger: 'blur' }],
  origin: [{ required: false, message: '产地不能为空', trigger: 'blur' }],
  styleName: [{ required: false, message: '款式名称不能为空', trigger: 'blur' }],
  customerCompanyRegNo: [{ required: false, message: '客户公司登记号不能为空', trigger: 'blur' }],
  topBarcode: [{ required: false, message: '上衣条形码不能为空', trigger: 'blur' }],
  topName: [{ required: false, message: '上衣名称不能为空', trigger: 'blur' }],
  topSku: [{ required: false, message: '上衣SKU不能为空', trigger: 'blur' }],
  pantsBarcode: [{ required: false, message: '裤子条形码不能为空', trigger: 'blur' }],
  pantsName: [{ required: false, message: '裤子名称不能为空', trigger: 'blur' }],
  pantsSku: [{ required: false, message: '裤子SKU不能为空', trigger: 'blur' }],
  customField1: [{ required: false, message: '自定义字段1不能为空', trigger: 'blur' }],
  customField2: [{ required: false, message: '自定义字段2不能为空', trigger: 'blur' }],
  customField3: [{ required: false, message: '自定义字段3不能为空', trigger: 'blur' }],
  customField4: [{ required: false, message: '自定义字段4不能为空', trigger: 'blur' }],
  customField5: [{ required: false, message: '自定义字段5不能为空', trigger: 'blur' }]
})

const dialogTitle = computed(() => {
  if (type.value === 'view') return '物料详情'
  return type.value === 'create' ? '新增物料' : '编辑物料'
})

// 是否为详情模式（只读）
const isViewMode = computed(() => type.value === 'view')

/** 打开弹窗 */
const open = async (typeStr: string, id?: number) => {
  dialogVisible.value = true
  type.value = typeStr

  // 重置表单
  resetForm()

  if ((typeStr === 'update' || typeStr === 'view') && id) {
    formLoading.value = true
    try {
      // 这里应该调用API获取物料详情
      const data = await getMaterialBaseInfo(id)

      // 设置表单数据
      formData.value = { ...data }

      // 设置基础信息显示
      basicInfoFields.value.forEach((field) => {
        if (data[field.field] !== undefined) {
          field.value = data[field.field]
        }
      })
    } catch (error) {
      message.error('获取物料详情失败')
      console.log(error)
    } finally {
      formLoading.value = false
    }
  } else if (typeStr === 'create') {
    // 新增时清空基础信息
    basicInfoFields.value.forEach((field) => {
      field.value = ''
    })
  }
}

defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true

  try {
    // 这里应该调用API保存数据
    if (type.value === 'create') {
      // await MaterialApi.createMaterial(formData.value)
      console.log('创建物料：', formData.value)
    } else {
      await updateMaterialBaseInfo(formData.value)
      console.log('更新物料：', formData.value)
    }

    message.success(`${type.value === 'create' ? '新增' : '编辑'}成功`)
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    message.error('操作失败')
    console.log(error)
  } finally {
    formLoading.value = false
  }
}

/** 条形码输入处理，过滤空格 */
const handleBarcodeInput = (formData: any, field: string) => {
  if (formData[field]) {
    formData[field] = formData[field].replace(/\s+/g, '')
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    materialNo: '', // 物料号
    materialName: '', // 物料长描述
    customerMaterialNo: '', // 客户物料编号
    styleNo: '', // 款号
    barcode: '', // 条形码
    name: '', // 名称
    color: '', // 颜色
    size: '', // 尺码
    specificationModel: '', // 规格型号
    composition: '', // 成分
    price: 0, // 价格
    poNo: '', // PO号
    brand: '', // 品牌
    productName: '', // 品名
    series: '', // 系列
    planTrackingNo: '', // 计划跟踪号
    productionModel: '', // 生产型号
    origin: '', // 产地
    styleName: '', // 款式名称
    customerCompanyRegNo: '', // 客户公司登记号
    topBarcode: '', // 上衣条形码
    topName: '', // 上衣名称
    topSku: '', // 上衣SKU
    pantsBarcode: '', // 裤子条形码
    pantsName: '', // 裤子名称
    pantsSku: '', // 裤子SKU
    customField1: '', // 自定义字段1
    customField2: '', // 自定义字段2
    customField3: '', // 自定义字段3
    customField4: '', // 自定义字段4
    customField5: '', // 自定义字段5
    sapBaseUnit: '', // 基本单位(SAP)
    sapCustomerCode: '', // 客户编号
    internalStyleNo: '' // 内部款号
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.material-basic-info {
  padding: 12px;
  margin-bottom: 30px;
  display: flex;
  width: 100%;
  gap: 15px;
  flex-wrap: wrap;
}
.info-field {
  width: calc(16.6666% - 15px);
}
.info-item {
}

.info-label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.88);
  margin-bottom: 4px;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #6c6c6c;
  word-break: break-all;
  line-height: 1.4;
  min-height: 20px;
}

.material-edit-form {
  padding: 0px;
}

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

.material-edit-form :deep(.el-form-item__label) {
  padding-bottom: 4px;
  line-height: 1.2;
  font-weight: 500;
}

.material-edit-form :deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
