<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <ElButton type="success" @click="showDialog">新增供应商</ElButton>

      <ElButton type="danger" @click="deleteFn">删除</ElButton>
    </div>
    <div class="user-content flex-1 flex-column overflow-hidden">
      <div class="user-list flex-1 overflow-hidden" v-loading="loading">
        <CustomizeTable
          border
          v-model="tableData"
          :config="tableConfig"
          align="center"
          @getCheckboxRecords="handleCheckboxRecords"
        ></CustomizeTable>
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[100, 200, 300, 400, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
  </div>

  <Dialog
    :title="editForm['id'] ? '编辑供应商' : '新增供应商'"
    v-model="dialogVisible"
    @close="cancelFn"
    width="75%"
  >
    <CustomizeForm
      v-loading="editLoading"
      ref="editFormRef"
      v-model="editForm"
      :config="formConfig"
      formItemWidth="100%"
      :labelWidth="100"
    >
    </CustomizeForm>

    <template #footer>
      <div style="text-align: center">
        <ElButton @click="cancelFn">取消</ElButton>

        <ElButton type="primary" :loading="saveLoading" @click="saveSupplierFn"
          >保存</ElButton
        >
      </div>
    </template>
  </Dialog>

  <Dialog
    title="管理供应价格"
    v-model="priceDialogVisible"
    width="65%"
    @close="cancelPiceFn"
    teleported
  >
    <div v-loading="priceLoading">
      <div style="display: flex; margin-bottom: 10px">
        <div style="display: flex; align-items: center; gap: 20px">
          <div><span style="color: red">*</span> 结算币种</div>
          <el-select
            style="width: 300px; flex: 1"
            v-model="currentGoods.currencyCode"
            @change="
            (v:string) => {
              
              currentGoods.currencyName =
                currencyOptions?.find((el) => v == el.currencyCode)
                  ?.currencyName || ''
              console.log(73,currentGoods.currencyName);

            }
          "
          >
            <el-option
              v-for="(item, index) in currencyOptions"
              :key="index"
              :label="`${item.currencyName}(${item.currencyCode})`"
              :value="item.currencyCode"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div
        style="border-top: 1px solid #eee; margin-bottom: 10px"
        v-if="showColorList.length"
      >
        <div style="font-size: 20px; font-weight: bold; margin: 10px 0">
          颜色(Color)
        </div>
        <div class="flex" style="flex-wrap: wrap; gap: 5px">
          <el-tag
            :title="`${item.cnname}(${item.enname})`"
            :color="item.bgColor"
            v-for="(item, index) in showColorList"
            :key="index"
            :style="{ color: item.fontColor }"
            class="tabBox"
            :class="{ active: colorIndex === item.code }"
            @click="optionSelection(item, 'color')"
            >{{ item.cnname }}({{ item.enname }})</el-tag
          >
        </div>
      </div>
      <div
        style="border-top: 1px solid #eee; margin-bottom: 10px"
        v-if="showSizeList.length"
      >
        <div style="font-size: 20px; font-weight: bold; margin: 10px 0">
          尺码(Size)
        </div>
        <div class="flex" style="flex-wrap: wrap; gap: 5px">
          <el-tag
            class="tabBox"
            color="#ffff87"
            style="color: #333"
            effect="dark"
            type="info"
            v-for="(item, index) in showSizeList"
            :key="index"
            :class="{ active: sizeIndex === item.code }"
            @click="optionSelection(item, 'size')"
          >
            {{ item.cnname }}</el-tag
          >
        </div>
      </div>
      <div
        style="
          display: flex;
          justify-content: end;

          border-top: 1px solid #eee;
        "
      >
        <div style="margin: 10px 0">
          <el-input
            placeholder="请输入供应价格"
            style="width: 200px; margin-right: 10px"
            size="small"
            v-model="supplierPirce"
            clearable
          ></el-input
          ><ElButton type="primary" @click="updatePrices" size="small"
            >批量更新供应价格</ElButton
          >
          <span style="color: #f56c6c; vertical-align: middle"
            >（请注意！该操作会覆盖已有供应价格）</span
          >
        </div>
      </div>
      <CustomizeTable
        ref="tableRef"
        border
        style="margin-bottom: 20px"
        v-model="pricetableData"
        :config="priceTableConfig"
        align="center"
        height="500px"
        @getCheckboxRecords="selectPirce"
      ></CustomizeTable>
    </div>
    <template #footer>
      <div style="text-align: center">
        <ElButton @click="cancelPiceFn">取消</ElButton>

        <ElButton type="primary" @click="savePiceFn">保存</ElButton>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="tsx">
defineOptions({
  name: 'DeclarationRule',
})
import {
  getSupplierListApi,
  deleteSupplierApi,
  getSupplierDetailApi,
  getPropertyByCateIdApi,
  getProductInfoBySpuApi,
  getBaseCurrencyInfoApi,
  addSupplierApi,
  updateSupplierApi,
} from '@/api/supplier/supplierManagement.ts'

import Dialog from './components/dialog.tsx'
import CustomizeForm from '@/components/CustomizeForm.tsx'
import CustomizeTable from '@/components/VxeTable.tsx'
import { IFormConfig } from '@/components/CustomizeForm.tsx'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import { showConfirm } from '@/utils/ui'
import { debounce, cloneDeep } from 'lodash-es'

import { Edit, CirclePlus } from '@element-plus/icons-vue'

import { TableColumn } from '@/components/VxeTable'
import {
  IgoodsType,
  IsupplierType,
  IcurrencyCode,
  IcolorType,
  IsizeType,
  IPropertyResponseItem,
  Iprice,
  IPropertyItem,
} from './types/index.ts'

const [editForm, resetEditForm] = useValue<IsupplierType>({})
const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getSupplierListApi({
      pageSize: pageSize,
      currentPage: page,
    }).then(({ data }) => {
      console.log(130, data)
      return data
    }),
})
const dialogVisible = ref(false)
const editLoading = ref(false)

const goodsTableData = ref([])

const supplierTableData = ref<IgoodsType[]>([])

const priceDialogVisible = ref(false)
const pricetableData = ref<Iprice[]>([])
const editFormRef = ref<InstanceType<typeof CustomizeForm> | null>(null)
const selection = ref<Iprice[]>([])

interface IOption {
  [key: string]: unknown
}

//表单
const formConfig = computed<IFormConfig[]>(() => [
  {
    prop: 'supplierName',
    type: 'input',
    label: '供应商名称',
    attrs: {
      placeholder: '请输入供应商名称',
      width: '33.333%',
    },
    rules: [
      {
        required: true,
        message: '请输入供应商名称',
      },
    ],
  },
  {
    prop: 'contacts',
    type: 'input',
    label: '联系人',
    attrs: {
      placeholder: '请输入联系人',
      width: '33.333%',
    },
    rules: [
      {
        required: true,
        message: '请输入联系人',
      },
    ],
  },
  {
    prop: 'contactsNumber',
    type: 'input',
    label: '联系电话',
    attrs: {
      placeholder: '请输入联系电话',
      width: '33.333%',
    },
    rules: [
      {
        required: true,
        message: '请输入联系电话',
      },
    ],
  },
  {
    prop: 'address',
    type: 'input',
    label: '地址',
    attrs: {
      placeholder: '请输入地址',
    },
    rules: [
      {
        required: true,
        message: '请输入地址',
      },
    ],
  },

  {
    prop: 'remark',
    type: 'input',
    label: '备注',
    attrs: {
      placeholder: '请输入备注',
      type: 'textarea',
      rows: 4,
    },
  },
  {
    prop: 'table',
    title: true,
    type: '',
    label: '',
    render: () => {
      return (
        <div style={{ width: '100%' }}>
          <div class="flex" style={{ justifyContent: 'space-between' }}>
            <div
              style={{
                display: 'flex',
                flexWrap: 'nowrap',
                alignItems: 'center',
                gap: '20px',
                marginBottom: '20px',
              }}
            >
              <div>管理供应商品</div>
              <el-input
                v-model={searchSupplierGoods.value}
                clearable
                placeholder="九猫商品SPU"
                style={{ width: '200px' }}
              ></el-input>
              <el-popover
                placement="bottom"
                trigger="click"
                width="750"
                disabled={isShowSearch.value}
                v-slots={{
                  reference: () => (
                    <el-button
                      type="primary"
                      onclick={() => searchSupplyGoodsFn()}
                    >
                      查询
                    </el-button>
                  ),
                }}
              >
                <CustomizeTable
                  v-loading={goodsLoading.value}
                  isShowCheckBox={false}
                  modelValue={goodsTableData.value}
                  config={searchTableConfig.value}
                  {...{ height: '400px', align: 'center', border: true }}
                  style={{ marginBottom: '20px' }}
                ></CustomizeTable>
              </el-popover>
            </div>
            <div>
              <el-button type="danger" onclick={() => deleteSupplyGoodsFn()}>
                删除
              </el-button>
            </div>
          </div>
          <CustomizeTable
            modelValue={supplierTableData.value}
            config={formTableConfig.value}
            {...{ height: '400px', align: 'center', border: true }}
            style={{ marginBottom: '20px' }}
            onGetCheckboxRecords={(v) => getSupplierItem(v)}
          ></CustomizeTable>
        </div>
      )
    },
  },
])

//列表表格
const tableConfig = ref<TableColumn[]>([
  {
    prop: 'supplierName',
    label: '供应商名称',
  },
  {
    prop: 'contacts',
    label: '联系人',
  },

  {
    prop: 'contactsNumber',
    label: '联系电话',
  },
  {
    prop: 'address',
    label: '地址',
  },

  {
    prop: 'remark',
    label: '备注',
  },

  {
    prop: 'opeare',
    label: '操作',
    attrs: {
      align: 'center',
    },
    render: {
      default: ({ row }: { row: IsupplierType }) => (
        <div>
          <el-icon
            size="24"
            title="编辑"
            color="#EF6C00"
            style="cursor: pointer; vertical-align: middle"
            onclick={() => editSupplier(row.id as string)}
          >
            <Edit />
          </el-icon>
        </div>
      ),
    },
  },
])

//表单表格
const formTableConfig = ref<TableColumn[]>([
  {
    prop: 'productName',
    label: '商品名称',
  },
  {
    prop: 'productNo',
    label: '款号',
  },

  {
    prop: 'productSpu',
    label: '商品SPU',
  },
  {
    prop: 'productImage',
    label: '商品图片',
    render: {
      default: ({ row }: { row: IgoodsType }) => (
        <div>
          <el-image style="width: 50px; height: 50px" src={row.productImage} />
        </div>
      ),
    },
  },

  {
    prop: 'currencyCode',
    label: '币种',
  },
  {
    prop: 'supplyPrice',
    label: '供应价格',
    render: {
      default: ({ row }: { row: IgoodsType }) => (
        <div>{getSupplyPrice(row)}</div>
      ),
    },
  },

  {
    prop: 'opeare',
    label: '操作',
    attrs: {
      align: 'center',
    },
    render: {
      default: ({ row }: { row: IgoodsType }) => (
        <el-button type="primary" onclick={() => addPice(row)} size="small">
          管理供应价格
        </el-button>
      ),
    },
  },
])

//查询商品表格
const searchTableConfig = ref<TableColumn[]>([
  {
    prop: 'name',
    label: '商品名称',
  },
  {
    prop: 'productNo',
    label: '款号',
  },

  {
    prop: 'sku',
    label: '商品SPU',
  },
  {
    prop: 'imgUrl',
    label: '商品图片',
    render: {
      default: ({ row }: { row: IgoodsType }) => (
        <div>
          <el-image style="width: 50px; height: 50px" src={row.imgUrl} />
        </div>
      ),
    },
  },
  {
    prop: 'opeare',
    label: '操作',
    attrs: {
      align: 'center',
      width: '65px',
    },
    render: {
      default: ({ row }: { row: IgoodsType }) => (
        <div>
          <el-icon
            size="24"
            title="新增"
            color="#EF6C00"
            style="cursor: pointer; vertical-align: middle"
            onclick={() => addGoods(row)}
          >
            <CirclePlus />
          </el-icon>
        </div>
      ),
    },
  },
])

//管理供应价格表格
const priceTableConfig = ref<TableColumn[]>([
  {
    prop: 'productItemImage',
    label: 'SKU图片',
    render: {
      default: ({ row }: { row: Iprice }) => (
        <div>
          <el-image
            style="width: 50px; height: 50px"
            src={row.productItemImage}
          />
        </div>
      ),
    },
  },
  {
    prop: 'productItemSku',
    label: 'SKU码',
  },

  {
    prop: 'opeare',
    label: '供应价格',
    attrs: {
      align: 'center',
      width: '230px',
    },
    render: {
      default: ({ row }: { row: Iprice }) => (
        <div>
          <el-input
            modelValue={row.supplyPrice}
            onInput={(v: string | number) => {
              v = String(v).replace(/[^\d.]/g, '')
              const parts = v.split('.')
              if (parts.length > 2) v = parts[0] + '.' + parts.slice(1).join('')
              row.supplyPrice = Number(v)
            }}
            clearable
            placeholder="请输入更新价格"
            style="width: 200px; margin-right: 20px"
            size="small"
          ></el-input>
        </div>
      ),
    },
  },
])

const searchSupplierGoods = ref('')

/**
 * @description: 取消按钮
 */
function cancelFn() {
  dialogVisible.value = false
  searchSupplierGoods.value = ''
  editFormRef.value?.resetFields()
  resetEditForm()
}
/**
 * @description: 取消供应价格按钮
 */
function cancelPiceFn() {
  priceDialogVisible.value = false
}

//保存供应价格
function savePiceFn() {
  if (!currentGoods.value.currencyCode) {
    return ElMessage({
      message: '请选择结算币种',
      type: 'warning',
    })
  }

  const hasEmptyPrice = pricetableData.value.some(
    (item) =>
      !item.supplyPrice ||
      String(item.supplyPrice).trim() === '' ||
      Number(item.supplyPrice) <= 0,
  )

  if (hasEmptyPrice) {
    ElMessage.warning('供应价格为必填项，且必须大于0')
    return
  }

  ElMessage({
    message: '保存成功',
    type: 'success',
  })

  supplierTableData.value.forEach((el) => {
    if (el.id === currentGoods.value.id) {
      el.currencyCode = currentGoods.value.currencyCode
      el.currencyName = currentGoods.value.currencyName
      el.supplierPriceItemList = [...pricetableData.value]
    }
  })
  console.log('supplierTableData', supplierTableData.value)

  cancelPiceFn()
}

/**
 * @description: 检查数据
 */
const saveLoading = ref(false)
async function checkData(): Promise<{
  isValid: boolean
  postData: IsupplierType
}> {
  try {
    // 1. 表单验证
    await editFormRef.value?.validate()

    // 2. 准备数据
    const postData = { ...editForm.value }

    const hasEmptyPriceItemList = supplierTableData.value?.some(
      (product) => !product.supplierPriceItemList,
    )

    if (hasEmptyPriceItemList) {
      ElMessage({
        message: '请填写所有供应价格',
        type: 'warning',
      })
      return { isValid: false, postData }
    }
    // 检查所有供应价格是否已填写
    const hasEmptyPrice = supplierTableData.value?.some((product) =>
      product.supplierPriceItemList?.some(
        (item) => !item.supplyPrice && item.supplyPrice !== 0,
      ),
    )

    console.log(656, hasEmptyPrice)
    // return
    if (hasEmptyPrice) {
      ElMessage({
        message: '请填写所有供应价格',
        type: 'warning',
      })
      return { isValid: false, postData }
    }
    if (supplierTableData.value?.length) {
      postData.supplierProductInfoList = [...supplierTableData.value].map(
        (el) => {
          el.createTime && delete el.createTime
          el.updateTime && delete el.updateTime
          return {
            ...el,
          }
        },
      )
    }

    // 所有验证通过
    return { isValid: true, postData }
  } catch (error) {
    console.error('表单验证失败:', error)
    // 表单验证失败时，仍然返回数据
    const postData = { ...editForm.value }
    return { isValid: false, postData }
  }
}

/**
 * @description: 保存按钮
 */
const saveSupplierFn = debounce(async () => {
  saveLoading.value = true
  try {
    const { isValid, postData } = await checkData()
    if (isValid) {
      if (!postData.id) {
        await addSupplierApi({
          ...postData,
        })
      } else {
        await updateSupplierApi({
          ...postData,
        })
      }
      ElMessage({
        message: postData.id ? '更新成功' : '新增成功',
        type: 'success',
      })

      cancelFn()
      search()
    }
  } catch (e) {
    return
  } finally {
    saveLoading.value = false
  }
}, 400)

/**
 * @description: 获取选中数据
 */
function handleCheckboxRecords(value: never[]) {
  selection.value = value
}

/**
 * @description: 多选删除按钮
 */
async function deleteFn() {
  if (!selection.value.length) {
    return ElMessage({
      message: '请选择供应商',
      type: 'warning',
    })
  }
  try {
    await showConfirm('是否删除供应商', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const ids = {
      ids: selection.value.map((item: IOption) => item.id).join(','),
    }
    await deleteSupplierApi(ids)
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    search()
  } catch (e) {
    search()
    // showError(e)
  }
}

/**
 * @description: 新增供应商
 */
async function showDialog() {
  dialogVisible.value = true
  supplierTableData.value = []
  supplierSeletctions.value = []
}

/**
 * @description: 编辑供应商
 */
async function editSupplier(id: string | number) {
  dialogVisible.value = true
  editLoading.value = true
  supplierTableData.value = []
  supplierSeletctions.value = []
  try {
    const { data } = await getSupplierDetailApi(id)
    editForm.value = data

    supplierTableData.value = cloneDeep(
      editForm.value.supplierProductInfoList || [],
    ).map((product) => {
      const customMap = new Map(
        product.customProductInfo?.customProductItemList?.map((item) => [
          item.id,
          item,
        ]) || [],
      )

      product.supplierPriceItemList?.forEach((priceItem) => {
        const customItem = customMap.get(priceItem.productItemId)
        if (customItem) {
          priceItem.propertyCode1 = customItem.propertyCode1
          priceItem.propertyCode2 = customItem.propertyCode2
        }
      })

      return product
    })

    console.log(728, editForm.value)
  } catch (error) {
    console.log(error)
  } finally {
    editLoading.value = false
  }
}

//查询spu
const goodsLoading = ref(false)
const isShowSearch = ref(false)
const supplierSeletctions = ref<IgoodsType[]>([])
async function searchSupplyGoodsFn() {
  if (!searchSupplierGoods.value) {
    ElMessage.warning('请输入SPU')
    isShowSearch.value = true
    return
  } else {
    isShowSearch.value = false
    goodsLoading.value = true

    try {
      const { data } = await getProductInfoBySpuApi(searchSupplierGoods.value)
      goodsTableData.value = [data]

      console.log(604, data)
    } catch (error) {
      console.log(error)
    } finally {
      goodsLoading.value = false
    }
  }
}

//删除商品
function deleteSupplyGoodsFn() {
  if (!supplierSeletctions.value.length) {
    return ElMessage.warning(`请勾选商品`)
  }
  const deleteIds = supplierSeletctions.value.map((el) => el.productSpu)
  supplierTableData.value = supplierTableData.value.filter(
    (el) => !deleteIds.includes(el.productSpu),
  )
}

function getSupplierItem(v: IgoodsType[]) {
  supplierSeletctions.value = v
}

const priceLoading = ref(false)
const currencyOptions = ref<IcurrencyCode[]>([])
const colorList = ref<IcolorType[]>([])
const showColorList = ref<IcolorType[]>([])
const sizeList = ref<IsizeType[]>([])
const showSizeList = ref<IsizeType[]>([])
const currentGoods = ref()

//管理供应价格按钮
async function addPice(product: IgoodsType) {
  supplierPirce.value = ''
  colorIndex.value = null
  sizeIndex.value = null
  priceDialogVisible.value = true
  priceLoading.value = true
  currentGoods.value = cloneDeep(product)
  console.log('product', currentGoods.value)
  const tempArr = product.supplierPriceItemList || product.customProductItemList
  pricetableData.value = cloneDeep(
    tempArr?.map((el) => {
      if (!el.productItemId) el.productItemId = el.id || ''
      return {
        ...el,
        productItemImage: el.productItemImage || el.image,
        productItemSku: el.productItemSku || el.sku,
      }
    }) || [],
  )
  try {
    const [currencyResponse, propertyResponse] = await Promise.all([
      getBaseCurrencyInfoApi(),
      getPropertyByCateIdApi(
        (product.categoryId || product.customProductInfo?.categoryId) as string,
      ),
    ])
    currencyOptions.value = currencyResponse.data || []
    const propertyData: IPropertyResponseItem[] = propertyResponse.data || []
    colorList.value = propertyData.find((el) => el.id == 1)?.valueList || []
    sizeList.value = propertyData.find((el) => el.id == 2)?.valueList || []

    if (!currentGoods.value.propertyList?.length) {
      currentGoods.value.propertyList = product.customProductInfo?.propertyList
    }
    // 创建属性映射
    const propertyMap = createPropertyMap(currentGoods.value.propertyList || [])
    console.log(758, propertyMap)

    // 过滤显示的颜色和尺寸
    showColorList.value = filterPropertyList(
      colorList.value,
      propertyMap.get(1) || [],
    )

    showSizeList.value = filterPropertyList(
      sizeList.value,
      propertyMap.get(2) || [],
    )
  } catch (error) {
    console.log(error)
  } finally {
    priceLoading.value = false
  }
}

// 辅助函数：创建属性映射
function createPropertyMap(propertyList: IPropertyItem[]): Map<number, number[]> {
  const map = new Map<number, number[]>()

  propertyList.forEach((item) => {
    if (item.propertyId && item.valueId) {
      if (!map.has(item.propertyId)) {
        map.set(item.propertyId, [])
      }
      map.get(item.propertyId)!.push(item.valueId)
    }
  })

  return map
}

// 辅助函数：过滤属性列表
function filterPropertyList<T extends { id?: number | string }>(
  sourceList: T[],
  targetIds: number[],
): T[] {
  return sourceList.filter((item) => {
    const itemId = typeof item.id === 'string' ? parseInt(item.id) : item.id
    return itemId !== undefined && targetIds.includes(itemId as number)
  })
}

//新增商品
function addGoods(data: IgoodsType) {
  data.productImage = data.productImage || data.imgUrl || ''
  data.productSpu = data.productSpu || data.sku || ''
  data.productName = data.productName || data.name || ''
  data.currencyCode = ''
  data.currencyName = ''
  data.productId = data.id || undefined

  const idSet = new Set(supplierTableData.value.map((item) => item.productSpu))

  if (idSet.has(data.productSpu)) {
    ElMessage.warning(`商品已存在，请勿重复添加`)
    return
  }
  supplierTableData.value.push(data)
  ElMessage.success('商品添加成功')
}

const selectPirceList = ref<Iprice[]>([])
const supplierPirce = ref('')
function selectPirce(value: never[]) {
  selectPirceList.value = value
}
//批量供应价格
function updatePrices() {
  if (!supplierPirce.value) {
    ElMessage.warning(`请输入供应价格`)
    return
  }
  if (selectPirceList.value.length) {
    selectPirceList.value.forEach((el) => {
      el.supplyPrice = supplierPirce.value
    })
  } else {
    ElMessage.warning(`请先勾选需要修改价格的商品`)
  }
}

//获取颜色和尺寸
const colorIndex = ref()
const sizeIndex = ref()
const tableRef = ref()
const optionSelection = (row: IcolorType, type: 'color' | 'size') => {
  updateSelectionIndex(row, type)
  updateTableSelection()
}

// 更新选中索引的函数
const updateSelectionIndex = (row: IcolorType, type: 'color' | 'size') => {
  if (type === 'color') {
    colorIndex.value = colorIndex.value === row.code ? null : row.code
  } else if (type === 'size') {
    sizeIndex.value = sizeIndex.value === row.code ? null : row.code
  }
}

// 更新表格选中状态的函数
const updateTableSelection = () => {
  pricetableData.value.forEach((item) => {
    tableRef.value.setCheckboxRow(item, false)
  })
  const rowsToSelect = getRowsToSelect()

  rowsToSelect.forEach((item) => {
    tableRef.value.setCheckboxRow(item, true)
  })
  console.log('rowsToSelect', rowsToSelect)

  selectPirceList.value = [...(rowsToSelect || [])]
}

// 获取应该选中的行
const getRowsToSelect = () => {
  return pricetableData.value.filter((item) => {
    if (colorIndex.value && sizeIndex.value) {
      return (
        item.propertyCode1 === colorIndex.value &&
        item.propertyCode2 === sizeIndex.value
      )
    }
    if (colorIndex.value) {
      return item.propertyCode1 === colorIndex.value
    }
    if (sizeIndex.value) {
      return item.propertyCode2 === sizeIndex.value
    }
    return false
  })
}
//获取供应价格区间
function getSupplyPrice(row: IgoodsType) {
  let range = ''
  const arr = row.supplierPriceItemList
  if (arr?.length) {
    const prices = arr
      .map((item) => {
        // 尝试转换为数字
        const price = parseFloat(item.supplyPrice as string)
        return isNaN(price) ? null : price
      })
      .filter((price) => price !== null) as number[]
    if (prices.length === 0) {
      range = '' // 或者根据需求返回默认值
    }

    // 计算最小值和最大值
    const minPrice = Math.min(...prices)
    const maxPrice = Math.max(...prices)

    // 判断是否需要范围格式
    if (minPrice === maxPrice) {
      // 所有价格相同或只有一个价格
      range = minPrice.toString()
    } else {
      // 价格有范围
      range = `${minPrice}-${maxPrice}`
    }
  } else {
    range = ''
  }
  row.supplyPriceRange = range as string
  return range
}
</script>

<style lang="scss" scoped>
.header-filter-form {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}
.user-operate-btn {
  margin-bottom: 10px;
}
.dialog-footer {
  text-align: center;
}
.tabBox {
  cursor: pointer;
}
.active {
  border: 2px solid rgb(0, 140, 255);
}
</style>
