<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-3">
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <el-button icon="ArrowLeft" @click="handleBack">返回</el-button>
          <span class="ml-4 text-xl font-bold">{{ pageTitle }}</span>
        </div>
      </div>
    </el-card>

    <div class="product-wizard-page">
      <!-- 步骤条 -->
      <el-card shadow="never" class="mb-3">
        <el-steps :active="currentStep" finish-status="success" align-center>
          <el-step title="选择分类" description="选择商品分类" />
          <el-step title="填写商品信息" description="填写商品基本信息" />
          <el-step title="完成" description="确认提交" />
        </el-steps>
      </el-card>

      <!-- 步骤内容 -->
      <div class="step-content" v-loading="loading">
        <!-- 步骤1: 选择分类 -->
        <el-card v-show="currentStep === 0" shadow="never" class="step-card">
          <template #header>
            <div class="flex items-center">
              <!-- <el-icon class="mr-2"><Warning /></el-icon> -->
              <span class="text-lg font-bold">选择分类</span>
            </div>
          </template>

          <div class="category-selection">
            <el-row :gutter="20">
              <!-- 一级分类 -->
              <el-col :span="8">
                <div class="category-box">
                  <div class="category-header">选择一级分类</div>
                  <div class="category-search">
                    <el-input
                      v-model="searchLevel1"
                      placeholder="搜索一级分类"
                      clearable
                      prefix-icon="Search"
                      size="small"
                    />
                  </div>
                  <div class="category-list">
                    <div
                      v-for="item in filteredLevel1Categories"
                      :key="item.id"
                      :class="['category-item', { 'active': categoryForm.topCategoryId === item.id }]"
                      @click="selectLevel1(item)"
                    >
                      <span>{{ item.label }}</span>
                      <el-icon v-if="categoryForm.topCategoryId === item.id"><ArrowRight /></el-icon>
                    </div>
                    <el-empty v-if="filteredLevel1Categories.length === 0" description="暂无数据" :image-size="60" />
                  </div>
                </div>
              </el-col>

              <!-- 二级分类 -->
              <el-col :span="8">
                <div class="category-box">
                  <div class="category-header">选择二级分类</div>
                  <div class="category-search">
                    <el-input
                      v-model="searchLevel2"
                      placeholder="搜索二级分类"
                      clearable
                      prefix-icon="Search"
                      size="small"
                    />
                  </div>
                  <div class="category-list">
                    <div
                      v-for="item in filteredLevel2Categories"
                      :key="item.id"
                      :class="['category-item', { 'active': categoryForm.mediumCategoryId === item.id }]"
                      @click="selectLevel2(item)"
                    >
                      <span>{{ item.label }}</span>
                      <el-icon v-if="categoryForm.mediumCategoryId === item.id"><ArrowRight /></el-icon>
                    </div>
                    <el-empty v-if="filteredLevel2Categories.length === 0" description="请先选择一级分类" :image-size="60" />
                  </div>
                </div>
              </el-col>

              <!-- 三级分类 -->
              <el-col :span="8">
                <div class="category-box">
                  <div class="category-header">选择三级分类</div>
                  <div class="category-search">
                    <el-input
                      v-model="searchLevel3"
                      placeholder="搜索三级分类"
                      clearable
                      prefix-icon="Search"
                      size="small"
                    />
                  </div>
                  <div class="category-list">
                    <div
                      v-for="item in filteredLevel3Categories"
                      :key="item.id"
                      :class="['category-item', { 'active': categoryForm.bottomCategoryId === item.id }]"
                      @click="selectLevel3(item)"
                    >
                      <span>{{ item.label }}</span>
                      <el-icon v-if="categoryForm.bottomCategoryId === item.id"><Check /></el-icon>
                    </div>
                    <el-empty v-if="filteredLevel3Categories.length === 0" description="请先选择二级分类" :image-size="60" />
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 已选分类提示 -->
          <!-- <div class="mt-4">
            <el-checkbox v-model="autoCreateCategory" label="如果选择的分类不存在，自动创建分类" />
          </div>
          <div class="mt-2">
            <el-input
              v-model="manualCategoryInput"
              placeholder="请输入入口类名称"
              clearable
              style="width: 400px;"
            />
          </div> -->
        </el-card>

        <!-- 步骤2: 填写商品信息 -->
        <el-card v-show="currentStep === 1" shadow="never" class="step-card">
          <template #header>
            <span class="text-lg font-bold">基本信息</span>
          </template>

          <el-form ref="productFormRef" :model="productForm" :rules="productRules" label-width="120px" class="product-info-form">
            <!-- 商品分类显示 -->
            <el-form-item label="商品分类:">
              <div class="category-display">
                <span class="category-text">{{ getCategoryPath() }}</span>
                <el-link type="primary" :underline="false" @click="currentStep = 0" class="ml-2">修改</el-link>
                <el-link type="danger" :underline="false" @click="clearCategory" class="ml-2">删除</el-link>
              </div>
            </el-form-item>

            <!-- 商品编号 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商品编号:" prop="productNo" required>
                  <el-input
                    v-model="productForm.productNo"
                    placeholder="002169745"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态:">
                  <span class="category-text">上架在售</span>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 商品名称 -->
            <el-form-item label="商品名称:" prop="itemName" required>
              <el-input
                v-model="productForm.itemName"
                type="textarea"
                :rows="2"
                placeholder="请输入商品名称"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <!-- A10产品名称 -->
            <el-form-item label="A10产品名称:">
              <el-input
                v-model="productForm.a10ProductName"
                type="textarea"
                :rows="2"
                placeholder="请输入A10产品名称"
                maxlength="200"
                show-word-limit
              />
              <div class="form-item-tip">
                A10产品名称应包含该产品的关键词,本身的名称、本身的型号、产品的主要特点、产品的用途、产品的颜色、产品的规格等。可以A3时间 A4 单击
              </div>
            </el-form-item>

            <!-- 规格型号 和 UPC(69)条码 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="规格型号:">
                  <el-input
                    v-model="productForm.specification"
                    placeholder="请输入规格型号"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="UPC(69)条码:">
                  <el-input
                    v-model="productForm.upcBarcode"
                    placeholder="请输入UPC(69)条码"
                    maxlength="20"
                    show-word-limit
                    @input="handleUpcInput"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 发票名称 和 发票规格 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="发票名称:">
                  <el-input
                    v-model="productForm.invoiceName"
                    placeholder="请输入发票名称"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发票规格:">
                  <el-input
                    v-model="productForm.invoiceSpec"
                    placeholder="请输入发票规格"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <!-- 商品品牌 -->
               <el-col :span="12">
                <el-form-item label="商品品牌:" prop="brandId" required>
                  <el-select
                    v-model="productForm.brandId"
                    placeholder="请输入品牌名称搜索"
                    filterable
                    remote
                    clearable
                    :remote-method="handleBrandSearch"
                    :loading="brandLoading"
                    class="w-full"
                  >
                    <el-option
                      v-for="item in brandOptions"
                      :key="item.id"
                      :label="item.brandName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
               </el-col>

              <el-col :span="12">
                <el-form-item label="单位:">
                  <el-select v-model="productForm.unitId" placeholder="请选择" clearable class="w-full">
                    <el-option
                      v-for="option in unitOptions"
                      :key="option.id"
                      :label="option.unitName"
                      :value="option.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>


            <!-- 税率 和 币种 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="税率:" required>
                  <el-select v-model="productForm.taxRate" placeholder="请选择税率" clearable class="w-full">
                    <el-option
                      v-for="option in taxRateOptions"
                      :key="option.id"
                      :label="option.taxrateName"
                      :value="option.taxrate"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="币种:">
                  <el-select v-model="productForm.currency" placeholder="请选择" class="w-full">
                    <el-option label="人民币(RMB)" value="RMB" />
                    <el-option label="美元(USD)" value="USD" />
                    <el-option label="欧元(EUR)" value="EUR" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 销量人气 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="销量人气:">
                  <el-input
                    v-model="productForm.salesVolume"
                    type="number"
                    placeholder="请输入销量人气"
                    :min="0"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 包装规格 -->
            <el-form-item label="促销标题:">
              <el-input
                v-model="productForm.packagingSpec"
                type="textarea"
                :rows="3"
                placeholder="请输入包装规格"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>

            <!-- 重量 和 体积 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商品重量:">
                  <el-input
                    v-model="productForm.weight"
                    placeholder="0"
                    maxlength="10"
                    show-word-limit
                  >
                    <template #append>
                      <el-select v-model="productForm.weightUnit" placeholder="请选择" style="width: 80px">
                        <el-option label="kg" value="kg" />
                        <el-option label="g" value="g" />
                        <el-option label="t" value="t" />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品体积:">
                  <el-input
                    v-model="productForm.volume"
                    placeholder="0"
                    maxlength="10"
                    show-word-limit
                  >
                    <template #append>
                      <el-select v-model="productForm.volumeUnit" placeholder="请选择" style="width: 80px">
                        <el-option label="m³" value="m3" />
                        <el-option label="cm³" value="cm3" />
                        <el-option label="L" value="L" />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 参考链接 -->
            <el-form-item label="参考链接">
              <el-input
                v-model="productForm.referenceLink"
                type="textarea"
                :rows="3"
                placeholder="请输入参考链接"
              />
            </el-form-item>

            <!-- 主供应商 -->
            <el-form-item label="主供应商:" prop="mainLibraryIntro" required>
              <el-select v-model="productForm.mainLibraryIntro" placeholder="请选择" clearable class="w-full" value-key="id">
                <el-option
                  v-for="option in supplierOptions"
                  :key="option.id"
                  :label="`${option.supplierNo},${option.enterpriseName}`"
                  :value="String(option.id)"
                />
              </el-select>
            </el-form-item>

            <!-- 售后服务 -->
            <el-form-item label="售后服务:">
              <el-select v-model="productForm.afterSalesService" placeholder="请选择" clearable class="w-full">
                <el-option
                  v-for="option in afterSalesOptions"
                  :key="option.id"
                  :label="option.afterSalesItems"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>

            <!-- 服务保障 -->
            <el-form-item label="服务保障:">
              <el-checkbox-group v-model="serviceGuarantees">
                <el-checkbox
                  v-for="option in serviceGuaranteeOptions"
                  :key="option.id"
                  :label="option.ensureName"
                  :value="option.id"
                />
              </el-checkbox-group>
            </el-form-item>

            <!-- 安装服务 -->
            <el-form-item label="安装服务:">
              <el-checkbox-group v-model="installationServices">
                <el-checkbox label="免费安装" value="freeInstallation" />
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 销售价格 -->
        <el-card v-show="currentStep === 1" shadow="never" class="step-card mt-3">
          <template #header>
            <span class="text-lg font-bold">销售价格</span>
          </template>

          <el-form ref="priceFormRef" :model="productForm" :rules="productRules" label-width="120px" class="product-info-form">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="市场价:" prop="midRangePrice" required>
                  <el-input
                    v-model="productForm.midRangePrice"
                    type="number"
                    placeholder="请输入市场价"
                    @blur="formatPrice('midRangePrice')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="平台售价:" prop="standardPrice" required>
                  <el-input
                    v-model="productForm.standardPrice"
                    type="number"
                    placeholder="请输入平台售价"
                    @blur="formatPrice('standardPrice')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最低售价:" prop="certificatePrice" required>
                  <el-input
                    v-model="productForm.certificatePrice"
                    type="number"
                    placeholder="请输入最低售价"
                    @blur="formatPrice('certificatePrice')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="最低起订量:" prop="minOrderQuantity" required>
                  <el-input
                    v-model="productForm.minOrderQuantity"
                    type="number"
                    placeholder="请输入最低起订量"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备注:">
                  <span class="currency-text">市场价>会员价>最低售价</span>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>
        </el-card>

        <!-- 采购价格 -->
        <el-card v-show="currentStep === 1" shadow="never" class="step-card mt-3">
          <template #header>
            <span class="text-lg font-bold">采购价格</span>
          </template>

          <el-form ref="purchasePriceFormRef" :model="productForm" :rules="productRules" label-width="120px" class="product-info-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="采购价:" prop="purchasePrice" required>
                  <el-input
                    v-model="productForm.purchasePrice"
                    type="number"
                    placeholder="请输入采购价"
                    @blur="formatPrice('purchasePrice')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="暂估采购价:">
                  <el-input
                    v-model="productForm.estimatedPurchasePrice"
                    type="number"
                    placeholder="请输入暂估采购价"
                    @blur="formatPrice('estimatedPurchasePrice')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 采购信息 -->
        <el-card v-show="currentStep === 1" shadow="never" class="step-card mt-3">
          <template #header>
            <span class="text-lg font-bold">采购信息</span>
          </template>

          <el-form ref="purchaseInfoFormRef" :model="productForm" :rules="productRules" label-width="120px" class="product-info-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="产品经理:" prop="productNature" required>
                  <el-select v-model="productForm.productNature" placeholder="请选择" clearable class="w-full" value-key="staffId">
                    <el-option
                      v-for="option in staffOptions"
                      :key="option.staffId"
                      :label="`${option.staffCode},${option.staffName}`"
                      :value="String(option.staffId)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采购人员:" prop="purchasingPersonnel" required>
                  <el-select v-model="productForm.purchasingPersonnel" placeholder="请选择" clearable class="w-full" value-key="staffId">
                    <el-option
                      v-for="option in staffOptions"
                      :key="option.staffId"
                      :label="`${option.staffCode},${option.staffName}`"
                      :value="String(option.staffId)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 商品属性 -->
        <el-card v-show="currentStep === 1" shadow="never" class="step-card mt-3">
          <template #header>
            <span class="text-lg font-bold">商品属性</span>
          </template>

          <el-form ref="attributeFormRef" :model="productForm" label-width="120px" class="product-info-form">
            <div v-if="attributesList.length === 0" class="text-center text-gray-500 py-8">
              该分类暂无属性配置
            </div>
            <template v-else>
              <el-row :gutter="20" v-for="(row, rowIndex) in Math.ceil(attributesList.length / 2)" :key="rowIndex">
                <el-col :span="12" v-for="colIndex in 2" :key="colIndex">
                  <template v-if="attributesList[rowIndex * 2 + colIndex - 1]">
                    <el-form-item
                      :label="attributesList[rowIndex * 2 + colIndex - 1].productAttributesName + ':'"
                      :required="attributesList[rowIndex * 2 + colIndex - 1].required === '1'"
                    >
                      <!-- 下拉选择 -->
                      <el-select
                        v-if="attributesList[rowIndex * 2 + colIndex - 1].entryMethod === '1'"
                        v-model="productAttributesValues[attributesList[rowIndex * 2 + colIndex - 1].id]"
                        placeholder="请选择"
                        clearable
                        class="w-full"
                      >
                        <el-option
                          v-for="option in parseAttributesList(attributesList[rowIndex * 2 + colIndex - 1].attributesList)"
                          :key="option"
                          :label="option"
                          :value="option"
                        />
                      </el-select>
                      <!-- 多选 -->
                      <el-select
                        v-else-if="attributesList[rowIndex * 2 + colIndex - 1].entryMethod === '3'"
                        v-model="productAttributesValues[attributesList[rowIndex * 2 + colIndex - 1].id]"
                        placeholder="请选择"
                        multiple
                        clearable
                        class="w-full"
                      >
                        <el-option
                          v-for="option in parseAttributesList(attributesList[rowIndex * 2 + colIndex - 1].attributesList)"
                          :key="option"
                          :label="option"
                          :value="option"
                        />
                      </el-select>
                      <!-- 文本输入 -->
                      <el-input
                        v-else
                        v-model="productAttributesValues[attributesList[rowIndex * 2 + colIndex - 1].id]"
                        placeholder="请输入"
                        clearable
                      />
                    </el-form-item>
                  </template>
                </el-col>
              </el-row>
            </template>
          </el-form>
        </el-card>

        <!-- 商品详情 -->
        <el-card v-show="currentStep === 1" shadow="never" class="step-card mt-3">
          <template #header>
            <span class="text-lg font-bold">商品详情</span>
          </template>

          <el-form ref="detailFormRef" :model="productForm" label-width="120px" class="product-info-form">
            <!-- 商品主图 -->
            <el-form-item label="商品主图:">
              <div class="image-upload-container">
                <div v-if="productForm.productImage" class="image-preview">
                  <img :src="productForm.productImage" class="preview-image" />
                  <div class="image-actions">
                    <el-button size="small" @click="openMainImageSelector">重新选择</el-button>
                    <el-button size="small" type="danger" @click="clearMainImage">删除</el-button>
                  </div>
                </div>
                <div v-else class="image-upload-placeholder" @click="openMainImageSelector">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击选择图片</div>
                </div>
              </div>
              <div class="form-item-tip">
                从图片库选择，建议尺寸300*300px
              </div>
            </el-form-item>

            <!-- 商品轮播图 -->
            <el-form-item label="商品轮播图:">
              <div class="carousel-images-container">
                <div class="carousel-image-list">
                  <div v-for="(imgUrl, index) in carouselImages" :key="index" class="carousel-image-item">
                    <img :src="imgUrl" class="carousel-preview-image" />
                    <div class="carousel-image-actions">
                      <el-button size="small" type="danger" @click="removeCarouselImage(index)">删除</el-button>
                    </div>
                  </div>
                  <div class="image-upload-placeholder carousel-add-btn" @click="openCarouselImageSelector">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <div class="upload-text">添加图片</div>
                  </div>
                </div>
              </div>
              <div class="form-item-tip">
                从图片库选择，支持多选，建议尺寸300*300px
              </div>
            </el-form-item>

            <!-- 商品详情 -->
            <el-form-item label="商品详情:">
              <el-tabs v-model="activeDetailTab" type="border-card">
                <el-tab-pane label="电脑端详情" name="pc">
                  <Editor v-model="productForm.pcDetail" :height="400" />
                </el-tab-pane>
                <el-tab-pane label="移动端详情" name="mobile">
                  <Editor v-model="productForm.mobileDetail" :height="400" />
                </el-tab-pane>
              </el-tabs>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 定制说明 -->
        <el-card v-show="currentStep === 1" shadow="never" class="step-card mt-3">
          <template #header>
            <span class="text-lg font-bold">定制说明</span>
          </template>

          <el-form ref="customFormRef" :model="customForm" label-width="120px" class="product-info-form">
            <!-- 可定制开关 -->
            <el-form-item label="可定制:">
              <el-switch v-model="customForm.customizable" />
            </el-form-item>

            <!-- 定制内容 -->
            <template v-if="customForm.customizable">
              <!-- 定制方式 -->
              <el-form-item label="定制方式:">
                <div class="custom-options">
                  <el-button
                    v-for="option in customMethodOptions"
                    :key="option.value"
                    :type="customForm.selectedMethods.includes(option.value) ? 'primary' : 'default'"
                    @click="toggleMethod(option.value)"
                  >
                    {{ option.label }}
                  </el-button>
                </div>
              </el-form-item>

              <!-- 定制工艺 -->
              <el-form-item label="定制工艺:">
                <div class="custom-options">
                  <el-button
                    v-for="craft in customCraftOptions"
                    :key="craft.value"
                    :type="customForm.selectedCrafts.includes(craft.value) ? 'primary' : 'default'"
                    @click="toggleCraft(craft.value)"
                  >
                    {{ craft.label }}
                  </el-button>
                </div>
              </el-form-item>

              <!-- 定制方式表格 -->
              <el-form-item label="" label-width="120">
                <el-table :data="customForm.customDetails" border class="custom-table">
                  <el-table-column label="装饰方法" width="120">
                    <template #default="{ row }">
                      <span>{{ row.decorationMethod }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="定制工艺" width="120">
                    <template #default="{ row }">
                      <span>{{ row.craft }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="起订数量" width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.minOrderQty" placeholder="请输入" />
                    </template>
                  </el-table-column>
                  <el-table-column label="起订价格" width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.minOrderPrice" placeholder="请输入" />
                    </template>
                  </el-table-column>
                  <el-table-column label="打样工期[天]" width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.samplePeriod" placeholder="请输入" />
                    </template>
                  </el-table-column>
                  <el-table-column label="生产周期[天]" width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.productionPeriod" placeholder="请输入" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100" fixed="right">
                    <template #default="{ $index }">
                      <el-link type="danger" :underline="false" @click="removeCustomDetail($index)">
                        删除
                      </el-link>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>

              <!-- 定制说明 -->
              <el-form-item label="定制说明:">
                <el-input
                  v-model="customForm.customDescription"
                  type="textarea"
                  :rows="5"
                  placeholder="请输入定制说明"
                />
              </el-form-item>
            </template>
          </el-form>
        </el-card>

        <!-- 步骤3: 完成 -->
        <el-card v-show="currentStep === 2" shadow="never" class="step-card completion-card">
          <div class="completion-content">
            <div class="success-icon">
              <el-icon :size="80" color="#67c23a">
                <CircleCheck />
              </el-icon>
            </div>
            <div class="completion-text">
              商品编辑完成，请点击返回，继续其他操作
            </div>
            <div class="completion-action">
              <el-button type="primary" @click="handleBackToList">返回</el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 底部操作按钮 -->
      <el-card v-if="currentStep < 2" shadow="never" class="mt-3">
        <div class="flex justify-center gap-4">
          <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
          <el-button v-if="currentStep < 2" type="primary" @click="nextStep">下一步</el-button>
          <el-button @click="handleBack">取消</el-button>
        </div>
      </el-card>
    </div>

    <!-- 文件选择器组件 -->
    <FileSelector
      v-model="mainImageSelectorVisible"
      :allowed-types="[1]"
      :multiple="false"
      title="选择商品主图"
      @confirm="handleMainImageSelected"
    />
    <!-- 轮播图文件选择器 -->
    <FileSelector
      v-model="carouselImageSelectorVisible"
      :allowed-types="[1]"
      :multiple="true"
      title="选择商品轮播图"
      @confirm="handleCarouselImagesSelected"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Warning, ArrowRight, Check, Plus, CircleCheck } from '@element-plus/icons-vue';
import Editor from '@/components/Editor/index.vue';
import FileSelector from '@/components/FileSelector/index.vue';
import { categoryTreeVO } from '@/api/product/category/types';
import { BrandVO } from '@/api/product/brand/types';
import { BaseForm } from '@/api/product/base/types';
import { AttributesVO } from '@/api/product/attributes/types';
import { addBase, updateBase, getBase, categoryTree, categoryAttributeList, getAfterSaleList, getServiceList, getUnitList, getTaxRateList } from '@/api/product/base';
import { listBrand } from '@/api/product/brand';
import { listInfo } from '@/api/customer/supplierInfo';
import { InfoVO } from '@/api/customer/supplierInfo/types';
import { listComStaff } from '@/api/system/comStaff';
import { ComStaffVO } from '@/api/system/comStaff/types';

const route = useRoute();
const router = useRouter();

const currentStep = ref(0);
const loading = ref(false);
const submitLoading = ref(false);
const productFormRef = ref();

// 服务保障和安装服务的多选框
const serviceGuarantees = ref<(string | number)[]>([]);
const installationServices = ref<string[]>([]);

// 商品详情选项卡
const activeDetailTab = ref('pc');

// 文件选择器相关
const mainImageSelectorVisible = ref(false);
const carouselImageSelectorVisible = ref(false);

// 轮播图URL数组（UI管理用）
const carouselImages = ref<string[]>([]);

// 税率选项
const taxRateOptions = ref<any[]>([]);

// 定制说明表单
const customForm = reactive({
  customizable: false,
  selectedMethods: [] as string[],
  selectedCrafts: [] as string[],
  customDetails: [] as Array<{
    decorationMethod: string;
    craft: string;
    minOrderQty: string;
    minOrderPrice: string;
    samplePeriod: string;
    productionPeriod: string;
  }>,
  customDescription: ''
});

// 定制方式选项
const customMethodOptions = [
  { label: '包装定制', value: 'package' },
  { label: '商品定制', value: 'product' },
  { label: '开模定制', value: 'mold' }
];

// 定制工艺选项
const customCraftOptions = [
  { label: '丝印', value: 'silkScreen' },
  { label: '热转印', value: 'thermalTransfer' },
  { label: '激光', value: 'laser' },
  { label: '烤花', value: 'baking' },
  { label: '压印', value: 'embossing' }
];

// 定制方式映射
const customMethodMap: Record<string, string> = {
  'package': '包装定制',
  'product': '商品定制',
  'mold': '开模定制'
};

// 定制工艺映射
const customCraftMap: Record<string, string> = {
  'silkScreen': '丝印',
  'thermalTransfer': '热转印',
  'laser': '激光',
  'baking': '烤花',
  'embossing': '压印'
};

// 服务保障选择不需要watch，在提交时直接转换为逗号分隔字符串

// 监听安装服务复选框变化，同步到表单
watch(installationServices, (newVal) => {
  productForm.freeInstallation = newVal.includes('freeInstallation') ? '1' : '0';
}, { deep: true });

// 监听定制方式和工艺选择变化，更新表格数据
watch([() => customForm.selectedMethods, () => customForm.selectedCrafts], ([newMethods, newCrafts]) => {
  const newDetails: typeof customForm.customDetails = [];

  // 遍历所有选中的定制方式和工艺组合
  newMethods.forEach(method => {
    const decorationMethod = customMethodMap[method];

    newCrafts.forEach(craft => {
      const craftName = customCraftMap[craft];

      // 查找是否已存在该组合的数据
      const existing = customForm.customDetails.find(
        item => item.decorationMethod === decorationMethod && item.craft === craftName
      );

      newDetails.push(existing || {
        decorationMethod,
        craft: craftName,
        minOrderQty: '',
        minOrderPrice: '',
        samplePeriod: '',
        productionPeriod: ''
      });
    });
  });

  customForm.customDetails = newDetails;
}, { deep: true });

// 切换定制方式选择
const toggleMethod = (method: string) => {
  const index = customForm.selectedMethods.indexOf(method);
  if (index > -1) {
    customForm.selectedMethods.splice(index, 1);
  } else {
    customForm.selectedMethods.push(method);
  }
};

// 切换定制工艺选择
const toggleCraft = (craft: string) => {
  const index = customForm.selectedCrafts.indexOf(craft);
  if (index > -1) {
    customForm.selectedCrafts.splice(index, 1);
  } else {
    customForm.selectedCrafts.push(craft);
  }
};

// 删除定制详情行
const removeCustomDetail = (index: number) => {
  customForm.customDetails.splice(index, 1);
};

const pageTitle = computed(() => {
  return route.params.id ? '编辑商品' : '新增商品';
});

// 分类选择表单
const categoryForm = reactive({
  topCategoryId: undefined as string | number | undefined,
  mediumCategoryId: undefined as string | number | undefined,
  bottomCategoryId: undefined as string | number | undefined,
});

const autoCreateCategory = ref(false);
const manualCategoryInput = ref('');

// 商品信息表单
const productForm = reactive<BaseForm>({
  id: undefined,
  productNo: undefined,
  itemName: undefined,
  brandId: undefined,
  topCategoryId: undefined,
  mediumCategoryId: undefined,
  bottomCategoryId: undefined,
  unitId: undefined,
  productImage: undefined,
  imageUrl: undefined,
  isSelf: 0,
  productReviewStatus: 0,
  homeRecommended: 0,
  categoryRecommendation: 0,
  cartRecommendation: 0,
  recommendedProductOrder: 0,
  isPopular: 0,
  isNew: 0,
  productStatus: '0',
  remark: undefined,
  a10ProductName: undefined,
  specification: undefined,
  upcBarcode: undefined,
  invoiceName: undefined,
  invoiceSpec: undefined,
  packagingSpec: undefined,
  referenceLink: undefined,
  weight: undefined,
  weightUnit: 'kg',
  volume: undefined,
  volumeUnit: 'm3',
  mainLibraryIntro: undefined,
  afterSalesService: undefined,
  serviceGuarantee: undefined, // 服务保障ID列表，逗号分隔
  freeInstallation: '0',
  midRangePrice: undefined,
  standardPrice: undefined,
  certificatePrice: undefined,
  purchasePrice: undefined,
  estimatedPurchasePrice: undefined,
  productNature: '1',
  purchasingPersonnel: '1',
  pcDetail: undefined,
  mobileDetail: undefined,
  taxRate: undefined,
  currency: 'RMB',
  minOrderQuantity: undefined,
  salesVolume: undefined,
});

// 表单验证规则
const productRules = {
  productNo: [{ required: true, message: '商品编号不能为空', trigger: 'blur' }],
  itemName: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
  brandId: [{ required: true, message: '商品品牌不能为空', trigger: 'change' }],
  mainLibraryIntro: [{ required: true, message: '主供应商不能为空', trigger: 'change' }],
  midRangePrice: [{ required: true, message: '市场价不能为空', trigger: 'blur' }],
  standardPrice: [{ required: true, message: '平台售价不能为空', trigger: 'blur' }],
  certificatePrice: [{ required: true, message: '最低售价不能为空', trigger: 'blur' }],
  purchasePrice: [{ required: true, message: '采购价不能为空', trigger: 'blur' }],
  productNature: [{ required: true, message: '产品经理不能为空', trigger: 'change' }],
  purchasingPersonnel: [{ required: true, message: '采购人员不能为空', trigger: 'change' }],
  taxRate: [{ required: true, message: '税率不能为空', trigger: 'change' }],
  minOrderQuantity: [{ required: true, message: '最低起订量不能为空', trigger: 'blur' }],
};

// 分类和品牌选项
const categoryOptions = ref<categoryTreeVO[]>([]);
const brandOptions = ref<BrandVO[]>([]);
const brandLoading = ref(false);
let brandSearchTimer: ReturnType<typeof setTimeout> | null = null;

// 商品属性列表
const attributesList = ref<AttributesVO[]>([]);
const productAttributesValues = ref<Record<string | number, any>>({});

// 售后服务和服务保障选项
const afterSalesOptions = ref<any[]>([]);
const serviceGuaranteeOptions = ref<any[]>([]);

// 单位选项
const unitOptions = ref<any[]>([]);

// 主供应商选项
const supplierOptions = ref<InfoVO[]>([]);

// 采购人员选项
const staffOptions = ref<ComStaffVO[]>([]);

// 搜索关键词
const searchLevel1 = ref('');
const searchLevel2 = ref('');
const searchLevel3 = ref('');

// 一级分类列表
const level1Categories = computed(() => {
  return categoryOptions.value || [];
});

// 二级分类列表
const level2Categories = ref<categoryTreeVO[]>([]);

// 三级分类列表
const level3Categories = ref<categoryTreeVO[]>([]);

// 过滤后的一级分类列表
const filteredLevel1Categories = computed(() => {
  if (!searchLevel1.value) {
    return level1Categories.value;
  }
  return level1Categories.value.filter(item =>
    item.label.toLowerCase().includes(searchLevel1.value.toLowerCase())
  );
});

// 过滤后的二级分类列表
const filteredLevel2Categories = computed(() => {
  if (!searchLevel2.value) {
    return level2Categories.value;
  }
  return level2Categories.value.filter(item =>
    item.label.toLowerCase().includes(searchLevel2.value.toLowerCase())
  );
});

// 过滤后的三级分类列表
const filteredLevel3Categories = computed(() => {
  if (!searchLevel3.value) {
    return level3Categories.value;
  }
  return level3Categories.value.filter(item =>
    item.label.toLowerCase().includes(searchLevel3.value.toLowerCase())
  );
});

// 选中的分类名称
const selectedLevel1Name = ref('');
const selectedLevel2Name = ref('');
const selectedLevel3Name = ref('');

// 选择一级分类
const selectLevel1 = (item: categoryTreeVO) => {
  categoryForm.topCategoryId = item.id;
  categoryForm.mediumCategoryId = undefined;
  categoryForm.bottomCategoryId = undefined;
  selectedLevel1Name.value = item.label;
  selectedLevel2Name.value = '';
  selectedLevel3Name.value = '';

  level2Categories.value = item.children || [];
  level3Categories.value = [];
};

// 选择二级分类
const selectLevel2 = (item: categoryTreeVO) => {
  categoryForm.mediumCategoryId = item.id;
  categoryForm.bottomCategoryId = undefined;
  selectedLevel2Name.value = item.label;
  selectedLevel3Name.value = '';

  level3Categories.value = item.children || [];
};

// 选择三级分类
const selectLevel3 = async (item: categoryTreeVO) => {
  categoryForm.bottomCategoryId = item.id;
  selectedLevel3Name.value = item.label;

  // 加载该分类下的属性列表
  await loadCategoryAttributes(item.id);
};

// 获取分类路径
const getCategoryPath = () => {
  const parts = [];
  if (selectedLevel1Name.value) parts.push(selectedLevel1Name.value);
  if (selectedLevel2Name.value) parts.push(selectedLevel2Name.value);
  if (selectedLevel3Name.value) parts.push(selectedLevel3Name.value);
  return parts.join(' > ') || '请选择分类';
};

// 清除分类
const clearCategory = () => {
  categoryForm.topCategoryId = undefined;
  categoryForm.mediumCategoryId = undefined;
  categoryForm.bottomCategoryId = undefined;
  selectedLevel1Name.value = '';
  selectedLevel2Name.value = '';
  selectedLevel3Name.value = '';
  level2Categories.value = [];
  level3Categories.value = [];
  attributesList.value = [];
  productAttributesValues.value = {};
};

// 下一步
const nextStep = async () => {
  if (currentStep.value === 0) {
    // 验证分类选择
    if (!categoryForm.topCategoryId) {
      ElMessage.warning('请选择一级分类');
      return;
    }
    if (!categoryForm.mediumCategoryId) {
      ElMessage.warning('请选择二级分类');
      return;
    }
    if (!categoryForm.bottomCategoryId) {
      ElMessage.warning('请选择三级分类');
      return;
    }

    // 将分类信息同步到商品表单
    productForm.topCategoryId = categoryForm.topCategoryId;
    productForm.mediumCategoryId = categoryForm.mediumCategoryId;
    productForm.bottomCategoryId = categoryForm.bottomCategoryId;

    currentStep.value++;
  } else if (currentStep.value === 1) {
    // 验证商品信息表单并提交
    try {
      await productFormRef.value?.validate();
      // 调用提交函数
      await handleSubmit();
    } catch (error) {
      ElMessage.warning('请完善商品信息');
      return;
    }
  }
};

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

// 提交
const handleSubmit = async () => {
  try {
    submitLoading.value = true;

    // 准备提交数据，包含定制信息
    const submitData = {
      ...productForm,
      // 将服务保障ID数组转换为逗号分隔字符串
      serviceGuarantee: serviceGuarantees.value.map(id => String(id)).join(','),
      // 轮播图URL逗号分隔
      imageUrl: carouselImages.value.join(','),
      // 将商品属性值转换为JSON字符串
      attributesList: JSON.stringify(productAttributesValues.value),
      customizable: customForm.customizable,
      customizedStyle: customForm.selectedMethods.join(','),
      customizedCraft: customForm.selectedCrafts.join(','),
      customDescription: customForm.customDescription,
      customDetailsJson: JSON.stringify(customForm.customDetails)
    };

    if (productForm.id) {
      await updateBase(submitData);
      ElMessage.success('修改成功');
    } else {
      await addBase(submitData);
      ElMessage.success('新增成功');
    }
    // 跳转到完成页面（步骤3）
    currentStep.value = 2;
  } catch (error) {
    console.error('提交失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 返回
const handleBack = () => {
  router.back();
};

// 返回列表
const handleBackToList = () => {
  router.push('/product/base');
};

// 打开主图选择器
const openMainImageSelector = () => {
  mainImageSelectorVisible.value = true;
};

// 处理主图选择
const handleMainImageSelected = (files: any[]) => {
  if (files && files.length > 0) {
    productForm.productImage = files[0].url;
  }
};

// 清除主图
const clearMainImage = () => {
  productForm.productImage = undefined;
};

// 打开轮播图选择器
const openCarouselImageSelector = () => {
  carouselImageSelectorVisible.value = true;
};

// 处理轮播图选择（多选）
const handleCarouselImagesSelected = (files: any[]) => {
  if (files && files.length > 0) {
    files.forEach(file => {
      if (!carouselImages.value.includes(file.url)) {
        carouselImages.value.push(file.url);
      }
    });
  }
};

// 删除轮播图
const removeCarouselImage = (index: number) => {
  carouselImages.value.splice(index, 1);
};

// UPC(69)条码只允许输入数字
const handleUpcInput = () => {
  if (productForm.upcBarcode) {
    productForm.upcBarcode = productForm.upcBarcode.replace(/\D/g, '');
  }
};

// 格式化价格为两位小数
const formatPrice = (field: string) => {
  const val = (productForm as any)[field];
  if (val !== undefined && val !== null && val !== '') {
    const num = parseFloat(String(val));
    if (!isNaN(num)) {
      (productForm as any)[field] = parseFloat(num.toFixed(2));
    }
  }
};

// 获取分类树
const getCategoryTree = async () => {
  try {
    const res = await categoryTree();
    categoryOptions.value = res.data || [];
  } catch (error) {
    console.error('获取分类树失败:', error);
  }
};

// 加载品牌选项（默认100条）
const loadBrandOptions = async (keyword?: string) => {
  brandLoading.value = true;
  try {
    const res = await listBrand({ pageNum: 1, pageSize: 100, brandName: keyword });
    brandOptions.value = res.rows || [];
  } catch (error) {
    console.error('加载品牌列表失败:', error);
  } finally {
    brandLoading.value = false;
  }
};

// 品牌远程搜索（防抖）
const handleBrandSearch = (query: string) => {
  if (brandSearchTimer) clearTimeout(brandSearchTimer);
  brandSearchTimer = setTimeout(() => {
    loadBrandOptions(query || undefined);
  }, 300);
};

// 处理品牌下拉框显示/隐藏
const handleBrandVisibleChange = (visible: boolean) => {
  if (visible && brandOptions.value.length === 0) {
    loadBrandOptions();
  }
};

// 获取售后服务列表
const getAfterSalesOptions = async () => {
  try {
    const res = await getAfterSaleList();
    afterSalesOptions.value = res.data || [];
    // 如果是新增模式且有选项，设置第一个为默认值
    if (!route.params.id && afterSalesOptions.value.length > 0 && !productForm.afterSalesService) {
      productForm.afterSalesService = afterSalesOptions.value[0].id;
    }
  } catch (error) {
    console.error('获取售后服务列表失败:', error);
  }
};

// 获取服务保障列表
const getServiceGuaranteeOptions = async () => {
  try {
    const res = await getServiceList();
    serviceGuaranteeOptions.value = res.data || [];
    // 如果是新增模式且有选项，设置第一个为默认选中
    if (!route.params.id && serviceGuaranteeOptions.value.length > 0 && serviceGuarantees.value.length === 0) {
      serviceGuarantees.value = [serviceGuaranteeOptions.value[0].id];
    }
  } catch (error) {
    console.error('获取服务保障列表失败:', error);
  }
};

// 获取单位列表
const getUnitOptions = async () => {
  try {
    const res = await getUnitList();
    unitOptions.value = res.data || [];
  } catch (error) {
    console.error('获取单位列表失败:', error);
  }
};

// 获取主供应商列表
const getSupplierOptions = async () => {
  try {
    const res = await listInfo();
    console.log('供应商接口返回:', res);
    // 处理可能的数据结构: res.data 或 res.rows
    const dataList = res.data || res.rows || [];
    supplierOptions.value = dataList;
    console.log('供应商列表:', supplierOptions.value);
    // 如果有选项且当前没有选中值,设置第一个为默认值
    if (supplierOptions.value.length > 0 && !productForm.mainLibraryIntro) {
      productForm.mainLibraryIntro = String(supplierOptions.value[0].id);
    }
  } catch (error) {
    console.error('获取主供应商列表失败:', error);
  }
};

// 获取采购人员列表
const getStaffOptions = async () => {
  try {
    const res = await listComStaff();
    console.log('采购人员接口返回:', res);
    // 处理可能的数据结构: res.data 或 res.rows
    const dataList = res.data || res.rows || [];
    staffOptions.value = dataList;
    console.log('采购人员列表:', staffOptions.value);
    // 如果有选项且当前没有选中值,设置第一个为默认值
    if (staffOptions.value.length > 0 && !productForm.purchasingPersonnel) {
      productForm.purchasingPersonnel = String(staffOptions.value[0].staffId);
    }
  } catch (error) {
    console.error('获取采购人员列表失败:', error);
  }
};

// 获取税率列表
const getTaxRateOptions = async () => {
  try {
    const res = await getTaxRateList();
    taxRateOptions.value = res.rows || [];
  } catch (error) {
    console.error('获取税率列表失败:', error);
  }
};

// 加载分类属性列表
const loadCategoryAttributes = async (categoryId: string | number) => {
  try {
    const res = await categoryAttributeList(categoryId);
    attributesList.value = res.data || [];
    // 清空之前的属性值
    productAttributesValues.value = {};

    // 如果是新增模式，为有选项的属性设置默认值
    if (!route.params.id) {
      attributesList.value.forEach(attr => {
        if (attr.entryMethod === '1' && attr.attributesList) { // 下拉选择
          const options = parseAttributesList(attr.attributesList);
          if (options.length > 0) {
            productAttributesValues.value[attr.id] = options[0];
          }
        } else if (attr.entryMethod === '3' && attr.attributesList) { // 多选
          const options = parseAttributesList(attr.attributesList);
          if (options.length > 0) {
            productAttributesValues.value[attr.id] = [options[0]];
          }
        }
      });
    }
  } catch (error) {
    console.error('加载分类属性失败:', error);
    attributesList.value = [];
  }
};

// 解析属性值列表（JSON数组或逗号分隔字符串）
const parseAttributesList = (attributesListStr: string): string[] => {
  if (!attributesListStr) return [];

  try {
    // 尝试解析为JSON数组
    const parsed = JSON.parse(attributesListStr);
    if (Array.isArray(parsed)) {
      return parsed;
    }
  } catch (e) {
    // 如果不是JSON，按逗号分隔
    return attributesListStr.split(',').map(item => item.trim()).filter(item => item);
  }

  return [];
};

// 加载商品详情（编辑模式）
const loadProductDetail = async () => {
  const id = route.params.id;
  if (id) {
    try {
      loading.value = true;
      const res = await getBase(id as string);
      Object.assign(productForm, res.data);

      // 回显轮播图
      if (res.data.imageUrl) {
        carouselImages.value = res.data.imageUrl.split(',').filter((url: string) => url.trim());
      } else {
        carouselImages.value = [];
      }

      // 回显分类选择
      categoryForm.topCategoryId = res.data.topCategoryId;
      categoryForm.mediumCategoryId = res.data.mediumCategoryId;
      categoryForm.bottomCategoryId = res.data.bottomCategoryId;

      // 回显服务保障复选框 - 将逗号分隔的ID字符串转换为数组
      if (res.data.serviceGuarantee) {
        serviceGuarantees.value = res.data.serviceGuarantee.split(',').map((id: string) => {
          // 尝试转换为数字，如果失败则保持字符串
          const numId = Number(id.trim());
          return isNaN(numId) ? id.trim() : numId;
        });
      } else {
        serviceGuarantees.value = [];
      }

      // 回显安装服务复选框
      const services: string[] = [];
      if (res.data.freeInstallation === '1') services.push('freeInstallation');
      installationServices.value = services;

      // 回显商品属性值
      if (res.data.attributesList) {
        try {
          const parsedAttributes = JSON.parse(res.data.attributesList);
          productAttributesValues.value = parsedAttributes;
        } catch (e) {
          console.error('解析商品属性失败:', e);
          productAttributesValues.value = {};
        }
      }

      // 回显分类名称
      if (categoryForm.topCategoryId) {
        const level1 = level1Categories.value.find(item => item.id === categoryForm.topCategoryId);
        if (level1) {
          selectLevel1(level1);

          if (categoryForm.mediumCategoryId) {
            const level2 = level2Categories.value.find(item => item.id === categoryForm.mediumCategoryId);
            if (level2) {
              selectLevel2(level2);

              if (categoryForm.bottomCategoryId) {
                const level3 = level3Categories.value.find(item => item.id === categoryForm.bottomCategoryId);
                if (level3) {
                  await selectLevel3(level3);
                }
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('加载商品详情失败:', error);
      ElMessage.error('加载商品详情失败');
    } finally {
      loading.value = false;
    }
  }
};

onMounted(async () => {
  await getCategoryTree();
  await getUnitOptions();
  await getAfterSalesOptions();
  await getServiceGuaranteeOptions();
  await getTaxRateOptions();
  // 先加载商品详情(如果是编辑模式)
  await loadProductDetail();
  // 再加载下拉选项,这样如果详情中没有值,会自动设置第一个
  await getSupplierOptions();
  await getStaffOptions();
  loadBrandOptions();
});
</script>

<style scoped lang="scss">
.product-wizard-page {
  .category-selection {
    margin-top: 12px;
  }

  .category-box {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: hidden;

    .category-header {
      background-color: #f5f7fa;
      padding: 10px 12px;
      font-weight: 600;
      border-bottom: 1px solid #e4e7ed;
      text-align: center;
      font-size: 14px;
    }

    .category-search {
      padding: 10px;
      border-bottom: 1px solid #e4e7ed;
      background-color: #fff;
    }

    .category-list {
      height: 280px;
      overflow-y: auto;

      .category-item {
        padding: 10px 12px;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #f0f0f0;
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }

        &.active {
          background-color: #ecf5ff;
          color: #409eff;
          font-weight: 600;
        }

        &:last-child {
          border-bottom: none;
        }
      }
    }
  }

  .confirm-info {
    margin-top: 12px;
    text-align: left;
  }

  .product-info-form {
    .category-display {
      display: flex;
      align-items: center;

      .category-text {
        color: #606266;
      }
    }

    .form-item-tip {
      font-size: 12px;
      color: #909399;
      line-height: 1.5;
      margin-top: 4px;
    }

    .currency-text {
      color: #303133;
      font-size: 14px;
    }
  }

  .image-upload-container {
    width: 178px;

    .image-preview {
      position: relative;

      .preview-image {
        width: 178px;
        height: 178px;
        display: block;
        object-fit: cover;
        border-radius: 6px;
        border: 1px solid #dcdfe6;
      }

      .image-actions {
        margin-top: 8px;
        display: flex;
        gap: 8px;
      }
    }
  }

  .image-upload-placeholder {
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    background-color: #fafafa;

    &:hover {
      border-color: #409eff;
      background-color: #f5f7fa;
    }

    .upload-icon {
      font-size: 28px;
      color: #8c939d;
      margin-bottom: 8px;
    }

    .upload-text {
      color: #8c939d;
      font-size: 14px;
    }
  }

  .custom-options {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .carousel-images-container {
    width: 100%;

    .carousel-image-list {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;

      .carousel-image-item {
        position: relative;

        .carousel-preview-image {
          width: 120px;
          height: 120px;
          display: block;
          object-fit: cover;
          border-radius: 6px;
          border: 1px solid #dcdfe6;
        }

        .carousel-image-actions {
          margin-top: 6px;
          display: flex;
          justify-content: center;
        }
      }

      .carousel-add-btn {
        width: 120px;
        height: 120px;
      }
    }
  }

  .custom-table {
    width: 100%;
    margin-top: 10px;
  }

  .completion-card {
    min-height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;

    .completion-content {
      text-align: center;
      padding: 40px 0;

      .success-icon {
        margin-bottom: 24px;
      }

      .completion-text {
        font-size: 16px;
        color: #606266;
        margin-bottom: 32px;
        line-height: 1.6;
      }

      .completion-action {
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style>
