<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
                  />
                </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-v2
                    v-model="productForm.brandId"
                    :options="brandOptionsFormatted"
                    placeholder="请选择商品品牌"
                    clearable
                    filterable
                    class="w-full"
                    :loading="brandLoading"
                    @visible-change="handleBrandVisibleChange"
                  />
                </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-input v-model="productForm.taxRate" placeholder="请输入商品税率" type="number" />
                </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">
                <el-option label="选项1" value="1" />
                <el-option label="选项2" value="2" />
                <el-option label="选项3" value="3" />
              </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" 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="请输入市场价"
                  />
                </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="请输入平台售价"
                  />
                </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="请输入最低售价"
                  />
                </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" 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="请输入采购价"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="暂估采购价:">
                  <el-input
                    v-model="productForm.estimatedPurchasePrice"
                    type="number"
                    placeholder="请输入暂估采购价"
                  />
                </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" 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">
                    <el-option label="自营" value="1" />
                    <el-option label="代销" value="2" />
                    <el-option label="定制" value="3" />
                  </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">
                    <el-option label="采购员1" value="1" />
                    <el-option label="采购员2" value="2" />
                    <el-option label="采购员3" value="3" />
                  </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="商品详情:">
              <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"
    />
  </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/pmsProduct/category/types';
import { BrandVO } from '@/api/pmsProduct/brand/types';
import { BaseForm } from '@/api/pmsProduct/base/types';
import { AttributesVO } from '@/api/pmsProduct/attributes/types';
import { addBase, updateBase, getBase, brandList, categoryTree, categoryAttributeList, getAfterSaleList, getServiceList, getUnitList } from '@/api/pmsProduct/base';

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 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,
  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: '1',
  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: 'blur' }],
  minOrderQuantity: [{ required: true, message: '请输入最低起订量', trigger: 'blur' }],
};

// 分类和品牌选项
const categoryOptions = ref<categoryTreeVO[]>([]);
const brandOptions = ref<BrandVO[]>([]);
const brandLoading = ref(false);
const brandOptionsFormatted = computed(() => {
  return brandOptions.value.slice(0, 500).map(item => ({
    label: item.brandName,
    value: item.id
  }));
});

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

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

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

// 搜索关键词
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(','),
      // 将商品属性值转换为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 getCategoryTree = async () => {
  try {
    const res = await categoryTree();
    categoryOptions.value = res.data || [];
  } catch (error) {
    console.error('获取分类树失败:', error);
  }
};

// 获取品牌列表（实时请求，每次只加载500条）
const getBrandList = async () => {
  try {
    brandLoading.value = true;
    const res = await brandList({ pageNum: 1, pageSize: 500 });
    brandOptions.value = res.data || [];
    // 如果是新增模式且有选项，设置第一个为默认值
    if (!route.params.id && brandOptions.value.length > 0 && !productForm.brandId) {
      productForm.brandId = brandOptions.value[0].id;
    }
  } catch (error) {
    console.error('获取品牌列表失败:', error);
  } finally {
    brandLoading.value = false;
  }
};

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

// 获取售后服务列表
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 || [];
    // 如果是新增模式且有选项，设置第一个为默认值
    if (!route.params.id && unitOptions.value.length > 0 && !productForm.unitId) {
      productForm.unitId = unitOptions.value[0].id;
    }
  } 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);

      // 回显分类选择
      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 loadProductDetail();
});
</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;
  }

  .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>
