<template>
  <ElDialog
    v-model="visible"
    :title="popupTitle"
    width="70%"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :disabled="isLookOrConfirm"
      :model="editForm"
      label-width="100px"
      :rules="formRules"
      validate-on-rule-change="false"
    >
      <p class="pop-p">基础信息</p>
      <ElRow>
        <el-col :span="8">
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="editForm.name"
              placeholder="请输入商品名称"
              clearable
              maxlength="40"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品类目" prop="category_id">
            <el-cascader
              ref="categoryCascader"
              v-model="editForm.category_id"
              :options="categoryTree"
              :props="{
                label: 'name',
                value: 'id',
                emitPath: false,
                checkStrictly: true,
              }"
              :show-all-levels="false"
              clearable
              filterable
              style="width: 100%"
              @change="categoryChange"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品类型" prop="print_type">
            <el-select
              v-model="editForm.print_type"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in PRINT_TYPE_OPTIONS"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </ElRow>
      <ElRow>
        <el-col :span="8">
          <el-form-item label="款号" prop="product_no">
            <el-input
              v-model="editForm.product_no"
              placeholder="请输入款号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品归属" prop="product_type">
            <el-select
              v-model="editForm.product_type"
              style="width: 100%"
              clearable
              disabled
            >
              <el-option
                v-for="item in productTypeList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="材质" prop="material">
            <el-input
              v-model="editForm.material"
              placeholder="请输入材质"
              clearable
            />
          </el-form-item>
        </el-col>
      </ElRow>
      <ElRow>
        <el-col v-if="editForm.print_type === 1" :span="8">
          <el-form-item label="支持工艺" prop="craftIds">
            <LogisticsWaySelect
              v-model="editForm.craftIds"
              :company-list="craftList"
              :start-width="'100%'"
              search-placeholder="搜索工艺名称"
              start-placeholder="请选择工艺名称"
            ></LogisticsWaySelect>
          </el-form-item>
        </el-col>
        <el-col v-if="['edit'].includes(modeTitle)" :span="8">
          <el-form-item label="客户编码" prop="editForm.userMark">
            <el-input
              v-model.number="editForm.userMark"
              oninput="value=value.replace(/[^\d]/g,'')"
              placeholder="请输入客户编码"
              clearable
              disabled
            />
          </el-form-item>
        </el-col>
      </ElRow>
      <!-- 编辑器 -->
      <wangEditor
        ref="wangeditorRef"
        v-model="editForm.cnRemark"
        placeholder="请输入中文描述"
        height="400px"
        filename="files"
        :mode-type="isLookOrConfirm ? 'simple' : 'default'"
      ></wangEditor>
      <p class="pop-p">商品图片</p>
      <div style="border: 1px solid #ddd">
        <ImageUploader
          v-model="editForm.imageList"
          :is-show-upload="isAddOrEdit"
          @change="handleChange"
        />
      </div>
      <p class="pop-p">尺码表</p>
      <div style="border: 1px solid #ddd">
        <ImageUploader
          v-model="editForm.sizeList"
          :is-show-upload="isAddOrEdit"
          @change="handleChange"
        />
      </div>
      <p class="pop-p">
        商品SKU
        <span class="pop-p-but">
          <el-button
            type="success"
            size="small"
            title="属性选择"
            @click="addOption()"
          >
            添加销售变体
          </el-button>
        </span>
      </p>
      <div v-if="skuArr?.length > 0" style="min-height: 40px">
        <div
          v-for="(item, index) in skuArr"
          v-show="item.valueList.length > 0"
          :key="item.id"
          class="variants"
        >
          <div class="title">{{ item.name }}</div>
          <ul>
            <Draggable
              v-model="item.valueList"
              item-key="id"
              @change="dragChange(index)"
            >
              <template #item="{ element }">
                <li
                  :key="element.id"
                  :style="{
                    background: element.bgColor,
                    color: element.fontColor,
                  }"
                  :class="{ active: variantsIndex === element.code }"
                  @click="optionSelection(element)"
                >
                  {{ element.cnname }}({{ element.enname }})
                  <el-icon
                    v-show="popupTitle === '新增'"
                    @click="optionDelete(index, element.code)"
                  >
                    <CloseBold />
                  </el-icon>
                </li>
              </template>
            </Draggable>
          </ul>
        </div>
      </div>
      <p class="pop-p">
        <span class="pop-p-but">
          <el-button type="success" @click="singleSetVariantImage">
            更新图片
          </el-button>
          <el-button type="primary" @click="updateProductInfoBtn('对外报价')">
            更新报价
          </el-button>
          <el-button type="success" @click="updateProductInfoBtn('商品重量')">
            更新重量
          </el-button>
          <el-button type="primary" @click="updateProductInfoBtn('注册件数')">
            更新件数
          </el-button>
        </span>
      </p>
      <!-- 表格 -->
      <div
        class="table_wrap"
        style="
          height: 250px;
          width: 100%;
          padding: 0;
          box-sizing: border-box;
          border: 1px solid #ddd;
          overflow: hidden;
        "
      >
        <CustomizeTable
          ref="tableRef"
          v-model="editForm.productList"
          :config="tableConfig"
          highlight-current-row
          border="full"
          @get-checkbox-records="handleCheckboxRecords"
        ></CustomizeTable>
      </div>
    </el-form>
    <template v-if="!['preview'].includes(modeTitle)" #footer>
      <span class="form-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button v-if="isAddOrEdit" type="primary" @click="submitProduct"
          >确定</el-button
        >
        <el-button
          v-if="modeTitle === 'confirm'"
          type="warning"
          @click="failBtn"
          >不通过</el-button
        >
        <el-button
          v-if="modeTitle === 'confirm'"
          type="primary"
          @click="passBtn"
          >通过</el-button
        >
      </span>
    </template>
  </ElDialog>
  <!--属性选择弹窗 -->
  <sku-attibute-popup
    ref="skuAttibuteRef"
    v-model:visible="attrVisible"
    :sku-options="proSkuOptions"
    :sku-arr="JSON.parse(JSON.stringify(skuArr))"
    :save="saveOption"
    @update:sku-arr="setOptions"
    @close="skuClose"
  >
  </sku-attibute-popup>
  <el-dialog
    v-model="singleImagesVisible"
    width="1000px"
    title="选择图片"
    append-to-body
  >
    <div v-if="editForm.imageList?.length > 0">
      <div style="border: 1px solid #ddd">
        <ImageUploader
          ref="imageUploaderRef"
          v-model="editForm.imageList"
          :is-more-check="false"
          :is-show-upload="false"
          @list-change="listHandleChange"
        />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="singleCancelBtn">取消</el-button>
        <el-button type="primary" @click="singleImageSelectSave">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { type FormInstance, ElMessage } from 'element-plus'
const formRef = shallowRef<FormInstance>()
import { CloseBold } from '@element-plus/icons-vue'
import Draggable from 'vuedraggable'
import wangEditor from '@/components/WangEditor.vue'
import ImageUploader from '../components/ImageUploader.vue'
const imageUploaderRef = shallowRef<InstanceType<typeof ImageUploader>>()
import LogisticsWaySelect from '../../logistics/components/LogisticsWaySelect.tsx'
import {
  getByCateIdApi,
  createProductApi,
  updateProductApi,
  updateStatusApi,
  deleteProductApi,
} from '@/api/product'
import CustomizeTable from '@/components/VxeTable.tsx'
const tableRef = ref<InstanceType<typeof CustomizeTable> | null>(null)
import { TableColumn } from '@/components/VxeTable'
import { defineModel, defineEmits, defineExpose, defineProps } from 'vue'
import {
  ProductDetail,
  ImageInfo,
  SkuPropertyValue,
  SkuProperty,
  InterSkuArr,
  ProductSku,
  CurrencyType,
  InterProductType,
  TableRowData,
} from '@/types/api/product'
import { IAllList } from '@/types/api/podUsOrder'
const visible = defineModel<boolean>('visible', { default: false })
const emits = defineEmits(['success'])
const props = defineProps({
  categoryTree: {
    type: Array,
    required: true,
  },
  productTypeList: {
    type: Array as () => InterProductType[],
    required: true,
  },
  craftList: {
    type: Array as () => IAllList[],
    required: true,
  },
  currencyList: {
    type: Array as () => CurrencyType[],
    required: true,
  },
})
const PRINT_TYPE_OPTIONS = [
  { label: '局部印', value: 1, type: 'warning' },
  { label: '代发普货', value: 2, type: 'danger' },
] as const
const createDefaultForm = (
  overrides?: Partial<ProductDetail>,
): ProductDetail => ({
  id: null,
  name: '',
  userMark: null,
  category_id: null,
  material: '',
  print_type: null,
  product_no: '',
  currency_code: '',
  currency_name: '',
  product_type: 'platform',
  title: '',
  craftIds: [],
  processing: true,
  cnRemark: '',
  imageList: [],
  sizeList: [],
  color_images: '',
  img_url: '',
  skuProperties: [],
  productList: [],
  factory_price: null,
  sort: null,
  property1_cate_id: null,
  property1_enname: '',
  property2_cate_id: null,
  property2_enname: '',
  weight: null,
  namespace: '',
  ...overrides, // 支持部分覆盖
})
const editForm = reactive<ProductDetail>(createDefaultForm())
const formRules = reactive({
  name: [
    {
      required: true,
      message: '请输入商品名称',
      trigger: 'blur',
    },
  ],
  title: [
    {
      required: true,
      message: '请输入Title',
      trigger: 'blur',
    },
  ],
  category_id: [
    {
      required: true,
      message: '请输入商品类目',
      trigger: 'change',
    },
  ],
  print_type: [
    {
      required: true,
      message: '请输入商品类型',
      trigger: 'change',
    },
  ],
  sales_price: [
    {
      required: true,
      message: '请输入销售价格',
      trigger: 'blur',
    },
    {
      pattern: /^(\d+)?(\.\d+)?$/,
      message: '只能输入数字',
    },
  ],
  weight: [
    {
      required: true,
      message: '请输入商品克重',
      trigger: 'blur',
    },
  ],
  origin_code: [
    {
      required: true,
      message: '请选择产地',
      trigger: 'change',
    },
  ],
  product_type: [
    {
      required: true,
      message: '请选择商品归属',
      trigger: 'change',
    },
  ],
})
const titleMap = {
  add: '新增',
  edit: '编辑',
  preview: '查看详情',
  success: '注册完成',
  confirm: '供应链确定',
} as const
type ModeType = keyof typeof titleMap
const modeTitle = ref<ModeType>('add')
const isAddOrEdit = computed(() => ['add', 'edit'].includes(modeTitle.value))
const isLookOrConfirm = computed(() =>
  ['preview', 'confirm'].includes(modeTitle.value),
)
import ImageView from '@/components/ImageView.vue'
const popupTitle = computed(() => titleMap[modeTitle.value as ModeType])
import skuAttibutePopup from '@/components/skuAttibute.vue'
const attrVisible = ref<boolean>(false)
const skuAttibuteRef = shallowRef<InstanceType<typeof skuAttibutePopup>>()
const proSkuOptions = ref<SkuProperty[]>([])
const categoryChange = async (id: number) => {
  const res = await getByCateIdApi(id)
  if (res.code === 200) {
    proSkuOptions.value = res.data || []
    const skuProperties = editForm?.skuProperties || []
    getSkuarr(skuProperties)
  } else {
    proSkuOptions.value = []
  }
}
const skuArr = ref<InterSkuArr[]>([]) // 回显属性用的数组
const getSkuarr = (skuProperties: SkuProperty[]) => {
  if (!skuProperties || skuProperties.length === 0) {
    skuArr.value = []
    return
  }
  const skuArrs = proSkuOptions.value.map((option: SkuProperty) => {
    const matched = skuProperties.find((item) => item.id === option.id)
    const obj: InterSkuArr = {
      id: option.id,
      enname: option.enname,
      name: `${option.cnname}(${option.enname})`,
      listCode: [],
      valueList: [],
      selected: 0,
    }
    if (matched?.valueList && option.valueList) {
      matched.valueList.forEach((matchedValue: SkuPropertyValue) => {
        if (matchedValue?.code) {
          obj.listCode.push(matchedValue.code)
          obj.valueList.push(matchedValue)
        }
      })
      option.valueList.forEach((optionValue) => {
        const isSelected = matched.valueList.some(
          (matchedValue) => matchedValue.id === optionValue.id,
        )
        if (isSelected) {
          optionValue.selected = 1
        }
      })
    }
    return obj
  })
  skuArr.value = skuArrs || []
}
const addOption = async () => {
  if (!editForm.category_id) {
    ElMessage.error('请选择商品类目')
    return
  }
  if (!editForm.name) {
    ElMessage.error('请先填写商品名称')
    return
  }
  attrVisible.value = true
  skuAttibuteRef.value?.open('edit')
}
import {
  cartesianProduct,
  emptyArray,
  cloneDeep,
  validateSkuItems,
  generateColorImages,
  finalizeSkuItems,
  calculateMinWeight,
  checkUpdateParams,
  checkDataChange,
} from '@/utils/product'
const MAX_CATE = 3
const saveOption = () => {
  /* 1. 校验分类 */
  const skuArrs = skuArr.value.filter((v: InterSkuArr) => v.listCode.length > 0)
  if (!skuArrs.length) {
    editForm.productList = []
    return ElMessage.error('请选择分类')
  }
  if (skuArrs.length > MAX_CATE) return ElMessage.error('分类选择不得大于3类')
  const checkList: SkuPropertyValue[][] = skuArrs.map(
    (v: InterSkuArr) => v.valueList,
  )
  const cartesianList = cartesianProduct<SkuPropertyValue>(checkList)
  /* 2. 提前建索引，加速后续匹配 */
  const existMap: Map<string, ProductSku> = new Map(
    editForm.productList.map((r: ProductSku) => [r.sku, r]), // 已存在 SKU
  )

  /* 3. 生成新列表 */
  const newList = cartesianList.map((codes, idx) => {
    const baseSku = popupTitle.value === '编辑' ? editForm.sku : 'SKU'
    const item = {
      sort: idx + 1,
      sku: baseSku + codes.map((c: SkuPropertyValue) => `_${c.code}`).join(''),
      sku_name:
        editForm.name +
        codes.map((c: SkuPropertyValue) => `_${c.cnname}`).join(''),
      sku_weight: null,
      reg_count: null,
    } as ProductSku

    /* 3.1 属性字段一次性写入 */
    codes.forEach((c: SkuPropertyValue, j: number) => {
      ;(item as unknown as Record<string, unknown>)[`property${j + 1}_id`] =
        c.id
      ;(item as unknown as Record<string, unknown>)[`option_enname${j + 1}`] =
        c.enname
      ;(item as unknown as Record<string, unknown>)[`custom_value${j + 1}`] =
        c.enname
      ;(item as unknown as Record<string, unknown>)[`property_code${j + 1}`] =
        c.code
      ;(item as unknown as Record<string, unknown>)[
        `property_cate_id${j + 1}`
      ] = skuArrs[j].id
    })

    /* 3.3 若已存在，保留 id 等信息 */
    const old = existMap.get(item.sku)
    const typedItem = item as ProductSku

    if (old) {
      typedItem.id = old.id // 保留主键
      typedItem.sku_weight = old.sku_weight // 关键：旧重量优先
      return { ...old, ...typedItem } // 其余字段用新数据
    }
    return typedItem
  })

  /* 4. 统一写回 + 价格兜底 */
  editForm.productList = newList.map((it, idx) => ({
    ...it,
    sort: idx + 1,
    factory_price: it.factory_price ?? editForm.factory_price,
    sales_price: it.sales_price ?? editForm.sales_price,
  }))
  attrVisible.value = false
}
const setOptions = (payload: { skuArr: InterSkuArr[] }) => {
  skuArr.value = JSON.parse(JSON.stringify(payload.skuArr))
}
const skuClose = () => {}
const tableSkuArr = computed(() => {
  return skuArr.value.filter((v: InterSkuArr) => {
    return v.listCode.length > 0
  })
})

const tableConfig = computed<TableColumn[]>(() => {
  const baseColumns: TableColumn[] = [
    {
      prop: 'sku_name',
      label: 'SKU名称',
      attrs: { align: 'center' },
    },
    {
      prop: 'sku',
      label: 'SKU',
      attrs: { align: 'center' },
    },
    {
      prop: 'image',
      label: 'SKU图片',
      attrs: { align: 'center', width: 80 },
      render: {
        default: ({ row }: { row: TableRowData }) => {
          return h(ImageView, {
            src: row.image as string,
            alt: 'SKU图片',
          })
        },
      },
    },
  ]

  const skuProps = tableSkuArr.value.map(
    (item: InterSkuArr, index: number) => ({
      prop: `custom_value${index + 1}`,
      label: item.enname,
      attrs: { align: 'center' },
    }),
  )

  const endColumns: TableColumn[] = [
    {
      prop: 'factory_price',
      label: '',
      attrs: { align: 'center', width: 250 },
      render: {
        header: () => [
          h('span', '对外报价 '),
          h(
            ElSelect,
            {
              modelValue: editForm.currency_code,
              'onUpdate:modelValue': (val: string) => {
                editForm.currency_code = val
                const item = props.currencyList.find(
                  (c: CurrencyType) => c.currencyCode === val,
                )
                if (item) editForm.currency_name = item.currencyName
              },
              placeholder: '币种',
              style: 'width: 150px',
            },
            () =>
              props.currencyList.map((c: CurrencyType) =>
                h(ElOption, {
                  key: c.currencyCode,
                  label: c.currencyName,
                  value: c.currencyCode,
                }),
              ),
          ),
        ],
      },
    },
    {
      prop: 'sku_weight',
      label: '重量',
      attrs: { align: 'center', width: 80 },
    },
    {
      prop: 'reg_count',
      label: '注册件数',
      attrs: { align: 'center', width: 100 },
    },
  ]

  return [...baseColumns, ...skuProps, ...endColumns]
})
const tableSelection = ref<ProductSku[]>([])
// 定义字段值类型
type UpdatableField = 'sku_weight' | 'reg_count'
type PriceFields = 'factory_price' | 'sales_price'
const updateProductInfoBtn = async (content: string) => {
  if (!tableSelection.value.length) return ElMessage.error('请选择要更新的商品')
  type FieldOrArray = UpdatableField | PriceFields[]
  const fieldMap: Record<string, FieldOrArray> = {
    商品重量: 'sku_weight',
    注册件数: 'reg_count',
    对外报价: ['factory_price', 'sales_price'],
  }
  const fieldOrArray = fieldMap[content]
  try {
    const { value } = await ElMessageBox.prompt('', `批量更新${content}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: `请输入${content}`,
      inputPattern: /.+/,
      inputErrorMessage: `${content}不能为空`,
    })
    tableSelection.value.forEach((item: ProductSku) => {
      if (typeof fieldOrArray === 'string') {
        // 单字段更新
        ;(item as unknown as Record<string, unknown>)[fieldOrArray] =
          Number(value)
      } else {
        // 数组，同时更新两个价格字段
        fieldOrArray.forEach((field) => {
          ;(item as unknown as Record<string, unknown>)[field] = Number(value)
        })
      }
    })
  } catch (error) {
    // 用户取消
  }
}

const singleImagesVisible = ref(false)
const singleSetVariantImage = () => {
  if (emptyArray(tableSelection.value)) return
  singleImagesVisible.value = true
}
const singleImage = ref<(string | null)[]>([])
const listHandleChange = (list: (string | null)[]) => {
  singleImage.value = list
}
const singleImageSelectSave = () => {
  if (Object.keys(singleImage.value).length === 0) {
    return ElMessage.warning('请勾选图片')
  }
  tableSelection.value.forEach((p: ProductSku) => {
    p.image = singleImage.value[0] as string
  })
  singleImagesVisible.value = false
  imageUploaderRef.value?.clear()
}
const singleCancelBtn = () => {
  singleImagesVisible.value = false
  imageUploaderRef.value?.clear()
}
function handleCheckboxRecords(value: ProductSku[]) {
  tableSelection.value = value
}
const handleChange = (list: ImageInfo[]) => {
  console.log('图片列表变化', list)
}
const dragChange = (i: number) => {
  const skuArrItem: InterSkuArr = skuArr.value[i]
  const sortMap: { [key: string]: number } = {}
  skuArrItem.listCode = skuArrItem.valueList
    .map((e) => e.code)
    .filter((code) => code !== null)
  skuArrItem.valueList.forEach((item, index) => {
    const code = item.code ?? 'defaultCode' // 如果 item.code 为 null，则使用 'defaultCode'
    item.sort = index + 1
    sortMap[code] = item.sort
  })
  const skuPropItem = proSkuOptions.value.find(
    (e: SkuProperty) => e.enname === skuArrItem.enname,
  )
  if (skuPropItem) {
    skuPropItem.valueList.sort(
      (a: SkuPropertyValue, b: SkuPropertyValue) =>
        sortMap[a.code] - sortMap[b.code],
    )
    skuPropItem.valueList.forEach((item: SkuPropertyValue, index: number) => {
      item.sort = index + 1
    })
  }
  sortSkuItemList()
}
const sortSkuItemList = () => {
  // 构建每个属性维度的排序映射：{ code: sortIndex }
  const skuArrSort: Array<Record<string, number>> = skuArr.value.map(
    (item: InterSkuArr) => {
      const map: Record<string, number> = {}
      item.listCode.forEach((code, i) => {
        if (code !== null) map[code] = i
      })
      return map
    },
  )

  const propList = [
    'property_code1',
    'property_code2',
    'property_code3',
  ] as const

  editForm.productList.sort((a: ProductSku, b: ProductSku) => {
    for (let i = 0; i < propList.length; i++) {
      const prop = propList[i]
      const aVal = a[prop as keyof ProductSku] as string | null | undefined
      const bVal = b[prop as keyof ProductSku] as string | null | undefined
      if (aVal == null && bVal == null) continue
      if (aVal == null) return -1 // null 排前面
      if (bVal == null) return 1
      const sortA = skuArrSort[i]?.[aVal] ?? Number.MAX_SAFE_INTEGER
      const sortB = skuArrSort[i]?.[bVal] ?? Number.MAX_SAFE_INTEGER
      const diff = sortA - sortB
      if (diff !== 0) return diff
    }
    return 0
  })

  editForm.productList.forEach((item: ProductSku, i: number) => {
    item.sort = i + 1
  })
}
const variantsIndex = ref<string | undefined>(undefined)
const optionSelection = (row: SkuPropertyValue) => {
  variantsIndex.value = row.code
  const list = editForm.productList
  let arr: ProductSku[] = []
  arr = list.filter(
    (item: ProductSku) =>
      item.property_code1 == row.code ||
      item.property_code2 == row.code ||
      item.property_code3 == row.code,
  )
  if (!arr.length) return
  // 清除之前的勾选
  tableRef.value?.clearCheckbox()
  tableSelection.value = arr
  // 滚动到第一行并高亮
  tableRef.value?.scrollToRow(arr[0] as unknown as TableRowData)
  // 勾选所有匹配行
  arr.forEach((item) => {
    tableRef.value?.setCheckboxRow(item as unknown as TableRowData, true)
  })
}
const optionDelete = (i: number, code: string) => {
  const arr: SkuPropertyValue[] = []
  const arrCode: string[] = []
  proSkuOptions.value[i].valueList.map((v: SkuPropertyValue) => {
    if (v.code == code) v.selected = 0
    else if (v.selected !== 0) {
      arrCode.push(v.code)
      arr.push(v)
    }
  })
  skuArr.value[i].valueList = arr
  skuArr.value[i].listCode = arrCode
  saveOption()
}
// 编辑时：用传入的数据覆盖
const getFormDetaild = (data: ProductDetail) => {
  Object.assign(editForm, createDefaultForm(data)) // data 会覆盖默认值
  originalForm.value = cloneDeep(editForm) // 保存快照
  categoryChange(editForm.category_id as number)
}
const open = async (key: ModeType = 'add', data?: ProductDetail) => {
  modeTitle.value = key
  if (key === 'add') {
    Object.assign(editForm, createDefaultForm())
    formRef.value?.clearValidate()
    skuArr.value = []
  } else if (data) {
    getFormDetaild(data)
  }
}
const originalForm = ref<ProductDetail | null>(null)
const submitProduct = async () => {
  // 1. 表单验证
  await formRef.value?.validate()
  // 2. 深拷贝原始数据（避免污染响应式源）
  const formCopy = cloneDeep(toRaw(editForm))
  const obj: ProductDetail = formCopy
  // 3. 处理首图
  obj.img_url = obj.img_url || obj.imageList[0]?.image_url || ''
  // 4. 标题默认值
  obj.title = obj.title || obj.name
  // 5. 构建 skuProperties（基于当前选中的属性值）
  const skuProperties = buildSkuProperties()
  obj.skuProperties = skuProperties
  // 6. 动态添加 propertyX_cate_id / propertyX_enname
  assignPropertyMetadata(obj)
  // 7. 准备商品列表与图片列表的深拷贝
  if (!obj.productList) {
    ElMessage.error('请添加销售属性')
  }
  const productListCopy = cloneDeep(obj.productList)
  const imageListCopy = cloneDeep(obj.imageList)

  // 8. 收集颜色与图片映射（用于 color_images）
  const colorImageMap = buildColorImageMap()
  // 9. 校验所有 SKU 并同时收集错误信息
  const errs = validateSkuItems(productListCopy)
  if (errs.length) {
    ElMessage.error(errs.join('\n')) // 换行显示
    return
  }
  const minPrice = productListCopy.reduce((min, item) => {
    const price = Number(item.factory_price)
    if (!isNaN(price)) {
      return price < min ? price : min
    }
    return min
  }, Infinity)
  obj.factory_price = minPrice // 历史价格字段最小值
  // 10. 校验币种
  if (!obj.currency_code) {
    ElMessage.error('请选择对外报价的币种')
    return
  }
  // 11. 生成 color_images
  obj.color_images = generateColorImages(colorImageMap)
  // 12. 处理图片排序（如果 imageList 需要按 sort 字段）
  obj.imageList = imageListCopy
    .sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0)) // 按 sort 升序，缺失时视为 0
    .map((e: ImageInfo) => ({
      image_url: e.image_url,
      sort: e.sort,
      id: e.id,
    }))
  // 13. 商品列表最终处理：排序等
  finalizeSkuItems(productListCopy)
  obj.productList = productListCopy
  // 14. 计算最小重量
  obj.weight = calculateMinWeight(productListCopy)
  let res
  if (['edit'].includes(modeTitle.value)) {
    const keyMap = {
      productList: 'id',
      imageList: 'id',
      sizeList: 'id',
    }
    const customChanges = checkUpdateParams(
      obj,
      originalForm.value,
      'id',
      keyMap,
      true,
    )
    const shouldSubmit = checkDataChange(customChanges)
    if (shouldSubmit) {
      res = await updateProductApi({
        ...customChanges!,
        id: editForm.id,
      } as ProductDetail)
    } else {
      return ElMessage.warning('未检测到数据变更，无需提交')
    }
  } else {
    obj.namespace = 'factory'
    res = await createProductApi(obj)
  }
  if (res.code === 200) {
    visible.value = false
    emits('success')
    ElMessage.success('提交成功')
  } else {
    ElMessage.error(res.message)
  }
}
const updateStatus = async (params: {
  status?: string
  remark?: string | null
}) => {
  try {
    const res = await updateStatusApi({
      ids: String(editForm.id),
      remark: null,
      ...params,
    })
    if (res.code === 200) {
      visible.value = false
      emits('success')
      ElMessage.success(res.message)
    } else {
      ElMessage.error(res.message)
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('操作失败，请稍后重试')
  }
}
// 通用删除/驳回
const doReject = async (remark: string) => {
  try {
    const res = await deleteProductApi({
      ids: String(editForm.id),
      remark,
    })
    if (res.code === 200) {
      visible.value = false
      emits('success')
      ElMessage.success(res.message)
    } else {
      ElMessage.error(res.message)
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('操作失败，请稍后重试')
  }
}
// 通过（无需原因）
const passBtn = () => updateStatus({ status: '-10' })
// 驳回（需要输入原因）
const failBtn = async () => {
  let remark: string
  try {
    const { value } = await ElMessageBox.prompt('', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入驳回原因',
      inputPattern: /.+/,
      inputErrorMessage: '请输入驳回原因',
    })
    remark = value
  } catch {
    return // 用户取消，静默退出
  }
  await doReject(remark)
}
// 构建 skuProperties（基于当前选中的属性值
function buildSkuProperties() {
  const result: SkuProperty[] = []
  for (const iterator of tableSkuArr.value) {
    const current = proSkuOptions.value.find(
      (item: SkuProperty) => item.id === iterator.id,
    )
    if (current) {
      // 保留当前选中的值列表
      current.valueList = current.valueList.filter((val: SkuPropertyValue) =>
        iterator.listCode.includes(val.code),
      )
      result.push(cloneDeep(current)) // 克隆避免修改原数据
    }
  }
  return result
}

/** 动态添加属性分类字段（property1_cate_id, property1_enname ...） */
function assignPropertyMetadata(obj: ProductDetail) {
  let idx = 1
  for (const item of skuArr.value) {
    if (item.valueList?.length) {
      ;(obj as unknown as Record<string, unknown>)[`property${idx}_cate_id`] =
        item.id
      ;(obj as unknown as Record<string, unknown>)[`property${idx}_enname`] =
        item.enname
      idx++
    }
  }
}

/** 构建颜色与图片的映射（仅用于去重生成 color_images） */
function buildColorImageMap() {
  const colorMap: Record<string, string> = {}
  const colorProperty = skuArr.value.find((item: InterSkuArr) =>
    item.enname?.toLowerCase().includes('color'),
  )
  if (!colorProperty) return {}
  for (const item of editForm.productList) {
    const code1 = item.property_code1
    const code2 = item.property_code2
    // 判断哪个属性是颜色（通常 property_code1 或 property_code2 对应颜色）
    if (code1 && colorProperty.listCode.includes(code1) && !colorMap[code1]) {
      colorMap[code1] = item.image
    }
    if (code2 && colorProperty.listCode.includes(code2) && !colorMap[code2]) {
      colorMap[code2] = item.image
    }
  }
  return colorMap
}
defineExpose({
  open,
})
</script>
<style scoped lang="scss">
@use './create.scss';
</style>
