<template>
  <div class="product-edit-page">
    <el-card shadow="never" class="steps-card">
      <el-steps :active="activeStep" finish-status="success" align-center>
        <el-step v-for="(step, index) in steps" :key="index" :title="step" class="custom-step" @click="activeStep = index" />
      </el-steps>
    </el-card>

    <div class="content-body">
      <!-- Step 0: 基础信息 -->
      <div v-if="activeStep === 0" class="step-panel">
        <el-card shadow="never">
          <el-form label-width="100px" class="base-form">
            <el-form-item label="商品名称" required>
              <el-input v-model="form.name" placeholder="请输入商品名称，建议不超过60字" maxlength="200" show-word-limit />
            </el-form-item>
            <el-form-item label="副标题">
              <el-input v-model="form.subtitle" placeholder="简短卖点描述" maxlength="200" show-word-limit />
            </el-form-item>
            <el-form-item label="商品分类" required>
              <el-select v-model="form.category_id" placeholder="选择分类" style="width:300px" clearable>
                <el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="封面图">
              <div class="image-upload-area">
                <template v-if="form.image">
                  <el-image :src="form.image" fit="cover" class="preview-img" />
                  <el-button type="danger" size="small" circle @click="form.image = ''">×</el-button>
                </template>
                <el-upload :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false" :on-success="r => form.image = r.data.url" accept="image/*">
                  <el-button type="primary" plain>上传封面</el-button>
                </el-upload>
                <span class="upload-tip">建议尺寸 800×800px</span>
              </div>
            </el-form-item>
            <el-form-item label="商品图片">
              <div class="multi-image-area">
                <el-upload :action="uploadUrl" :headers="uploadHeaders" list-type="picture-card" :file-list="imageFileList" :on-success="handleMultiImageSuccess" :on-remove="handleImageRemove" accept="image/*" multiple>
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label="销售价" required>
              <el-input-number v-model="basePrice" :min="0.01" :precision="2" style="width:200px" @change="syncBasePrice" />
            </el-form-item>
            <el-form-item label="原价">
              <el-input-number v-model="form.original_price" :min="0" :precision="2" style="width:200px" />
            </el-form-item>
            <el-form-item label="成本价">
              <el-input-number v-model="form.cost_price" :min="0" :precision="2" style="width:200px" />
            </el-form-item>
            <el-form-item label="总库存">
              <el-input-number v-model="form.stock" :min="0" :step="10" style="width:200px" />
            </el-form-item>
            <el-form-item label="单位">
              <el-input v-model="form.unit" placeholder="件/米/套" style="width:120px" maxlength="10" />
            </el-form-item>
            <el-form-item label="排序权重">
              <el-input-number v-model="form.sort" :min="0" style="width:200px" />
              <span class="upload-tip" style="margin-left:8px">数字越小越靠前</span>
            </el-form-item>
            <el-form-item label="商品属性">
              <el-checkbox v-model="form.is_new">新品</el-checkbox>
              <el-checkbox v-model="form.is_hot">热销</el-checkbox>
              <el-checkbox v-model="form.is_recommend">推荐</el-checkbox>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- Step 1: 规格与库存 -->
      <div v-if="activeStep === 1" class="step-panel spec-inventory-panel">
        <el-card shadow="never">
          <div class="panel-section">
            <div class="section-header">
              <h3>商品规格模式</h3>
              <el-select v-model="templateId" placeholder="导入规格模板" clearable style="width:200px" @change="handleImportTemplate">
                <el-option label="灯带通用规格 (长度+色温)" value="1" />
                <el-option label="灯条防水规格 (长度+防水等级)" value="2" />
              </el-select>
            </div>
            <el-radio-group v-model="specMode" class="spec-mode-radio">
              <el-radio value="single">单规格商品</el-radio>
              <el-radio value="multi">多规格商品</el-radio>
            </el-radio-group>
          </div>
          <div v-if="specMode === 'multi'" class="panel-section">
            <h3 class="section-title">规格项管理</h3>
            <div v-for="(item, index) in specItems" :key="item.id" class="spec-item-row">
              <div class="spec-name-input"><el-input v-model="item.name" placeholder="规格名称(如:长度)" maxlength="10" /></div>
              <div class="spec-values-area">
                <el-tag v-for="(val, vIdx) in item.values" :key="vIdx" closable @close="removeSpecValue(index, vIdx)">{{ val }}</el-tag>
                <template v-if="item.showInput">
                  <el-input v-model="item.inputValue" size="small" style="width:120px" maxlength="20" placeholder="限20字" @keyup.enter="confirmSpecValue(index)" @blur="confirmSpecValue(index)" />
                </template>
                <el-button v-else size="small" @click="item.showInput = true">+ 添加</el-button>
              </div>
              <el-button type="danger" link @click="removeSpecItem(index)"><el-icon><Delete /></el-icon></el-button>
            </div>
            <div class="spec-actions">
              <el-button type="primary" plain @click="addSpecItem" :disabled="specItems.length>=3">+ 添加规格项</el-button>
              <el-button plain @click="saveAsTemplate">保存为模板</el-button>
            </div>
          </div>
          <div v-if="specMode === 'multi' && skuList.length > 0" class="panel-section">
            <div class="section-header"><h3>SKU 价格与库存</h3><el-button type="primary" @click="showBatchDialog = true">批量设置</el-button></div>
            <el-table :data="skuList" border style="width:100%" class="sku-table" max-height="400">
              <el-table-column v-for="spec in specItems" :key="spec.name" :label="spec.name" min-width="80"><template #default="{ row }">{{ row.specs[spec.name] }}</template></el-table-column>
              <el-table-column label="SKU图" width="80" align="center">
                <template #default="{ row }">
                  <el-upload :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false" :on-success="r => { row.image = r.data.url }" class="sku-img-upload">
                    <el-image v-if="row.image" :src="row.image" fit="cover" class="sku-img" /><el-icon v-else :size="20"><Plus /></el-icon>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column label="售价(元)" width="110"><template #default="{ row }"><el-input-number v-model="row.price" :min="0" :precision="2" size="small" controls-position="right" /></template></el-table-column>
              <el-table-column label="成本(元)" width="110"><template #default="{ row }"><el-input-number v-model="row.cost_price" :min="0" :precision="2" size="small" controls-position="right" /></template></el-table-column>
              <el-table-column label="库存" width="100"><template #default="{ row }"><el-input-number v-model="row.stock" :min="0" size="small" controls-position="right" /></template></el-table-column>
              <el-table-column label="编码" width="110"><template #default="{ row }"><el-input v-model="row.sku_code" placeholder="可选" size="small" /></template></el-table-column>
              <el-table-column label="操作" width="60" align="center"><template #default="{ $index }"><el-button type="danger" link @click="removeSku($index)">×</el-button></template></el-table-column>
            </el-table>
          </div>
          <div v-if="specMode === 'single'" class="panel-section">
            <h3 class="section-title">单规格设置</h3>
            <el-form label-width="100px">
              <el-form-item label="销售价"><el-input-number v-model="singleForm.price" :min="0" :precision="2" /></el-form-item>
              <el-form-item label="成本价"><el-input-number v-model="singleForm.cost_price" :min="0" :precision="2" /></el-form-item>
              <el-form-item label="库存"><el-input-number v-model="singleForm.stock" :min="0" /></el-form-item>
              <el-form-item label="SKU编码"><el-input v-model="singleForm.sku_code" placeholder="可选" maxlength="50" /></el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>

      <!-- Step 2: 详情编辑（CRMEB风格：其他设置） -->
      <div v-if="activeStep === 2" class="step-panel">
        <el-card shadow="never">
          <!-- 2a. 商品简介 -->
          <div class="panel-section">
            <div class="section-header"><h3>商品简介</h3></div>
            <el-input v-model="form.brief" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="一句话概括商品卖点，显示在商品列表和搜索结果中" />
          </div>

          <!-- 2b. 商品关键字 -->
          <div class="panel-section">
            <div class="section-header"><h3>商品关键字</h3></div>
            <el-input v-model="form.seo_keywords" placeholder="多个关键字用逗号分隔，如：LED灯带,24V低压,RGB氛围灯" maxlength="200" show-word-limit />
          </div>

          <!-- 2c. 商品口令 -->
          <div class="panel-section">
            <div class="section-header"><h3>商品口令</h3></div>
            <el-input v-model="form.command_code" placeholder="自定义分享口令/暗号，如：下单备注'灯带达人'送接头" maxlength="100" show-word-limit />
            <div class="form-tip">买家下单时可使用的优惠口令或暗号</div>
          </div>

          <!-- 2d. 商品参数（动态表格） -->
          <div class="panel-section">
            <div class="section-header">
              <h3>商品参数</h3>
              <el-button size="small" type="primary" plain @click="addParam">+ 添加参数</el-button>
            </div>
            <el-table :data="productParams" border style="width:100%" max-height="300">
              <el-table-column label="参数名" width="200">
                <template #default="{ $index }">
                  <el-input v-model="productParams[$index].name" placeholder="如：型号、电压、功率、长度" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="参数值" min-width="250">
                <template #default="{ $index }">
                  <el-input v-model="productParams[$index].value" placeholder="如：FJ-24V-100" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template #default="{ $index }">
                  <el-button type="danger" link size="small" @click="removeParam($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="form-tip">在商品详情页以参数表格形式展示，建议填写型号、电压、功率、防水等级、质保期等</div>
          </div>

          <!-- 2e. 服务保障 -->
          <div class="panel-section">
            <div class="section-header">
              <h3>服务保障</h3>
              <el-button size="small" type="primary" plain @click="addGuarantee">+ 添加保障</el-button>
            </div>
            <div class="guarantee-list">
              <div v-for="(g, i) in form.service_guarantees" :key="i" class="guarantee-item">
                <el-input v-model="form.service_guarantees[i]" placeholder="如：48小时发货" style="width:260px" size="small" maxlength="30" />
                <el-button type="danger" link @click="removeGuarantee(i)"><el-icon><Delete /></el-icon></el-button>
              </div>
              <div v-if="!form.service_guarantees.length" class="empty-tip">暂无保障项，点击上方添加。常见：48小时发货、正品保证、7天退换、包邮</div>
            </div>
          </div>

          <!-- 2f. 商品推荐图 -->
          <div class="panel-section">
            <div class="section-header"><h3>商品推荐图</h3></div>
            <div class="image-upload-area">
              <template v-if="form.recommend_image">
                <el-image :src="form.recommend_image" fit="cover" class="preview-img" />
                <el-button type="danger" size="small" circle @click="form.recommend_image = ''">×</el-button>
              </template>
              <el-upload :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false" :on-success="r => form.recommend_image = r.data.url" accept="image/*">
                <el-button type="primary" plain>上传推荐图</el-button>
              </el-upload>
              <span class="upload-tip">建议尺寸 750×750px，用于推荐/首页展示</span>
            </div>
          </div>

          <!-- 2g. 商品详情HTML -->
          <div class="panel-section">
            <div class="section-header"><h3>商品详情（HTML）</h3></div>
            <el-tabs v-model="detailTab">
              <el-tab-pane label="编辑" name="edit">
                <el-input v-model="form.description" type="textarea" :rows="12" placeholder="支持HTML代码，可插入图文混排" />
              </el-tab-pane>
              <el-tab-pane label="预览" name="preview">
                <div class="detail-preview" v-html="form.description || '<p style=\'color:#999\'>暂无内容</p>'" />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-card>
      </div>

      <!-- Step 3: 物流设置 -->
      <div v-if="activeStep === 3" class="step-panel">
        <el-card shadow="never">
          <div class="panel-section">
            <h3 class="section-title">运费设置</h3>
            <el-form label-width="120px">
              <el-form-item label="运费模板">
                <el-select v-model="form.shipping_template_id" placeholder="选择运费模板" style="width:300px" clearable>
                  <el-option label="全国包邮（默认）" :value="1" />
                  <el-option label="按件计费" :value="2" />
                  <el-option label="按重量计费" :value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="商品重量(g)"><el-input-number v-model="form.weight" :min="0" style="width:200px" /></el-form-item>
              <el-form-item label="条形码"><el-input v-model="form.bar_code" placeholder="商品条形码/ISBN" maxlength="50" style="width:300px" /></el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>

      <!-- Step 4: 会员权益 -->
      <div v-if="activeStep === 4" class="step-panel">
        <el-card shadow="never">
          <div class="panel-section">
            <div class="section-header"><h3>会员等级折扣</h3><el-tag type="warning">为不同等级会员设置专属折扣价</el-tag></div>
            <el-table :data="memberRates" border style="width:600px">
              <el-table-column label="会员等级" width="160">
                <template #default="{ row }">{{ row.name }}</template>
              </el-table-column>
              <el-table-column label="折扣率" width="160">
                <template #default="{ $index }">
                  <el-input-number v-model="memberRates[$index].rate" :min="0" :max="10" :precision="1" :step="0.5" size="small" controls-position="right" />
                </template>
              </el-table-column>
              <el-table-column label="折扣价(¥)">
                <template #default="{ row }">
                  <span style="font-weight:bold;color:#e74c3c">{{ calcMemberPrice(row.rate) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="启用" width="80" align="center">
                <template #default="{ $index }">
                  <el-switch v-model="memberRates[$index].enabled" size="small" />
                </template>
              </el-table-column>
            </el-table>
            <div class="table-tip">折扣率 10=原价, 9=9折, 8=8折... 不启用的等级按系统默认折扣计算</div>
          </div>
          <div class="panel-section">
            <div class="section-header"><h3>分销佣金</h3></div>
            <el-form label-width="140px">
              <el-form-item label="分销佣金比例(%)">
                <el-input-number v-model="form.commission_rate" :min="0" :max="100" :precision="1" style="width:200px" />
                <span class="upload-tip" style="margin-left:8px">卖出一件分给分销员的佣金比例</span>
              </el-form-item>
              <el-form-item label="限购数量">
                <el-input-number v-model="form.max_qty" :min="0" :max="99999" style="width:200px" />
                <span class="upload-tip" style="margin-left:8px">每人限购数量，0为不限</span>
              </el-form-item>
              <el-form-item label="起售数量">
                <el-input-number v-model="form.min_qty" :min="1" :max="999" style="width:200px" />
                <span class="upload-tip" style="margin-left:8px">最少购买数量</span>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>

      <!-- Step 5: 营销配置（CRMEB风格）-->
      <div v-if="activeStep === 5" class="step-panel">
        <el-card shadow="never">
          <!-- 5a. 积分+优惠券 -->
          <div class="panel-section">
            <div class="section-header"><h3>积分与优惠券</h3></div>
            <el-form label-width="150px">
              <el-form-item label="购买送积分">
                <el-input-number v-model="form.give_points" :min="0" :max="99999" style="width:200px" />
                <span class="upload-tip" style="margin-left:8px">该商品赠送的积分数量，0为不赠送</span>
              </el-form-item>
              <el-form-item label="购买送优惠券">
                <el-input-number v-model="form.give_coupon_id" :min="0" :max="999" style="width:200px" />
                <span class="upload-tip" style="margin-left:8px">填写优惠券ID，0为不赠送（功能预留）</span>
              </el-form-item>
            </el-form>
          </div>

          <!-- 5b. 限购+预售 -->
          <div class="panel-section">
            <div class="section-header"><h3>购买限制</h3></div>
            <el-form label-width="150px">
              <el-form-item label="起购数量">
                <el-input-number v-model="form.min_qty" :min="1" :max="999" style="width:200px" />
              </el-form-item>
              <el-form-item label="限购">
                <div style="display:flex;align-items:center;gap:12px">
                  <el-switch v-model="form.is_limited" />
                  <template v-if="form.is_limited">
                    <span style="font-size:13px;color:#666">每人限购</span>
                    <el-input-number v-model="form.max_qty" :min="1" :max="99999" style="width:160px" />
                    <span style="font-size:12px;color:#999">件</span>
                  </template>
                </div>
              </el-form-item>
              <el-form-item label="预售商品">
                <div style="display:flex;align-items:center;gap:12px">
                  <el-switch v-model="form.is_pre_sale" />
                  <template v-if="form.is_pre_sale">
                    <span style="font-size:13px;color:#666">预计发货</span>
                    <el-date-picker v-model="form.pre_sale_time" type="datetime" placeholder="选择预计发货时间" style="width:280px" value-format="YYYY-MM-DD HH:mm:ss" />
                  </template>
                </div>
              </el-form-item>
            </el-form>
          </div>

          <!-- 5c. 商品推荐 -->
          <div class="panel-section">
            <div class="section-header"><h3>商品推荐</h3></div>
            <div class="recommend-grid">
              <label class="recommend-item" :class="{active: form.is_hot}">
                <el-checkbox v-model="form.is_hot" />
                <span class="rec-icon">🔥</span>
                <span class="rec-label">热卖单品</span>
              </label>
              <label class="recommend-item" :class="{active: form.is_recommend}">
                <el-checkbox v-model="form.is_recommend" />
                <span class="rec-icon">⭐</span>
                <span class="rec-label">精品推荐</span>
              </label>
              <label class="recommend-item" :class="{active: form.is_new}">
                <el-checkbox v-model="form.is_new" />
                <span class="rec-icon">🆕</span>
                <span class="rec-label">首发新品</span>
              </label>
              <label class="recommend-item" :class="{active: form.is_premium}">
                <el-checkbox v-model="form.is_premium" />
                <span class="rec-icon">💎</span>
                <span class="rec-label">优品推荐</span>
              </label>
            </div>
          </div>

          <!-- 5d. 展示设置 -->
          <div class="panel-section">
            <div class="section-header"><h3>展示设置</h3></div>
            <el-form label-width="150px">
              <el-form-item label="已售数量">
                <el-input-number v-model="form.fake_sales" :min="0" :max="999999" style="width:200px" />
                <span class="upload-tip" style="margin-left:8px">前台展示的已售数量，0为显示真实销量</span>
              </el-form-item>
              <el-form-item label="排序">
                <el-input-number v-model="form.sort" :min="0" style="width:200px" />
                <span class="upload-tip" style="margin-left:8px">数字越小越靠前</span>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>

      <!-- Step 6: 高级设置 -->
      <div v-if="activeStep === 6" class="step-panel">
        <el-card shadow="never">
          <div class="panel-section">
            <h3 class="section-title">上架管理</h3>
            <el-form label-width="140px">
              <el-form-item label="商品状态">
                <el-radio-group v-model="form.status">
                  <el-radio :value="1">立即上架</el-radio>
                  <el-radio :value="0">下架（暂不展示）</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="定时上架">
                <el-switch v-model="enableSchedule" />
                <template v-if="enableSchedule">
                  <el-date-picker v-model="form.publish_time" type="datetime" placeholder="选择定时上架时间" style="width:300px;margin-left:12px" value-format="YYYY-MM-DD HH:mm:ss" />
                </template>
              </el-form-item>
              <el-form-item label="隐藏商品">
                <el-switch v-model="form.is_hidden" />
                <span class="upload-tip" style="margin-left:8px">开启后前台不展示，仅通过链接访问</span>
              </el-form-item>
            </el-form>
          </div>
          <div class="panel-section">
            <h3 class="section-title">库存预警</h3>
            <el-form label-width="140px">
              <el-form-item label="预警阈值">
                <el-input-number v-model="form.stock_warning" :min="0" style="width:200px" />
                <span class="upload-tip" style="margin-left:8px">库存低于此值时系统发送预警通知，0为不预警</span>
              </el-form-item>
            </el-form>
          </div>
          <div class="panel-section">
            <h3 class="section-title">商品二维码</h3>
            <el-form label-width="140px">
              <el-form-item label="分享链接">
                <el-input v-model="shareUrl" :readonly="true" style="width:400px">
                  <template #append><el-button @click="copyShareUrl">复制</el-button></template>
                </el-input>
              </el-form-item>
              <el-form-item label="预览二维码">
                <div id="qrcodeContainer" ref="qrcodeRef" style="width:140px;height:140px;border:1px solid #e0e0e0;border-radius:8px;">
                  <div v-if="!productId" style="padding:40px 10px;text-align:center;color:#999;font-size:12px">保存后生成</div>
                  <img v-else :src="'https://api.qrserver.com/v1/create-qr-code/?size=140x140&data=' + shareUrl" style="width:140px;height:140px;border-radius:8px;" />
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部 -->
    <div class="footer-actions">
      <el-button v-if="activeStep > 0" @click="activeStep--">上一步</el-button>
      <el-button v-if="activeStep < steps.length - 1" type="primary" @click="activeStep++">下一步</el-button>
      <el-button v-if="activeStep === steps.length - 1" type="primary" :loading="submitting" @click="submitProduct">{{ productId ? '更新商品' : '提交发布' }}</el-button>
    </div>

    <!-- 批量设置弹窗 -->
    <el-dialog v-model="showBatchDialog" title="批量设置 SKU" width="400px">
      <el-form label-width="80px">
        <el-form-item label="销售价"><el-input-number v-model="batchForm.price" :min="0" :precision="2" style="width:100%" /></el-form-item>
        <el-form-item label="成本价"><el-input-number v-model="batchForm.cost_price" :min="0" :precision="2" style="width:100%" /></el-form-item>
        <el-form-item label="库存数量"><el-input-number v-model="batchForm.stock" :min="0" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchDialog = false">取消</el-button>
        <el-button type="primary" @click="applyBatchSettings">应用到所有 SKU</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRoute } from 'vue-router'

const route = useRoute()
const API = axios.create({ baseURL: '/api/admin' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })

const productId = route.query.id || null
const activeStep = ref(0)
const steps = ['基础信息', '规格与库存', '详情编辑', '物流设置', '会员权益', '营销配置', '高级设置']
const showBatchDialog = ref(false)
const submitting = ref(false)
const detailTab = ref('edit')
const categories = ref([])
const levels = ref([])
const uploadUrl = '/api/upload/image'
const uploadHeaders = { Authorization: 'Bearer ' + localStorage.getItem('admin_token') }
const enableSchedule = ref(false)
const qrcodeRef = ref(null)

const basePrice = ref(0)
const memberRates = ref([])
const flashSale = reactive({ enabled: false, price: 0, stock: 0, start_time: '', end_time: '', limit: 1 })
const groupBuy = reactive({ enabled: false, price: 0, min_users: 2, duration: 24, limit: 1 })

const form = reactive({
  name: '', subtitle: '', category_id: null, image: '', images: [],
  price: 0, original_price: 0, cost_price: 0, stock: 0, unit: '件',
  description: '', spec_type: 0, is_new: true, is_hot: false, is_recommend: false,
  sort: 0, weight: 0, shipping_template_id: null, bar_code: '',
  seo_keywords: '', seo_description: '',
  member_rates: [], commission_rate: 0,
  is_flash_sale: 0, flash_sale_config: '', is_group_buy: 0, group_buy_config: '',
  publish_time: '', stock_warning: 0, is_hidden: false, status: 1,
  min_qty: 1, max_qty: 999,
  brief: '', command_code: '', service_guarantees: [], product_params: [], recommend_image: '',
  give_points: 0, give_coupon_id: 0, is_limited: false, is_pre_sale: false, pre_sale_time: '', is_premium: false, fake_sales: 0
})

const productParams = computed({
  get: () => form.product_params || [],
  set: v => form.product_params = v
})

const imageFileList = ref([])
const specMode = ref('multi')
const templateId = ref('')
const batchForm = reactive({ price: 0, cost_price: 0, stock: 0 })
const singleForm = reactive({ price: 0, cost_price: 0, stock: 0, sku_code: '' })
const specItems = ref([
  { id: 1, name: '规格', values: ['10盘10米'], showInput: false, inputValue: '' },
  { id: 2, name: '色温', values: ['白光', '暖光', '中性光'], showInput: false, inputValue: '' }
])

const skuList = computed(() => {
  if (specMode.value === 'single') return []
  const v = specItems.value.filter(i => i.values.length > 0)
  if (!v.length) return []
  const c = arr => arr.reduce((a, b) => { let r = []; a.forEach(x => { b.values.forEach(v => { r.push({ ...x, [b.name]: v }) }) }); return r }, [{}])
  return c(v).map((item, idx) => ({ id: idx, specs: item, image: '', price: 0, cost_price: 0, stock: 0, sku_code: '', weight: 0 }))
})

const shareUrl = computed(() => productId ? `${location.origin}/#/product/${productId}` : '')

function calcMemberPrice(rate) {
  if (!rate || rate >= 10) return (basePrice.value || form.price || 0).toFixed(2)
  return (basePrice.value * rate / 10).toFixed(2)
}

function syncBasePrice() {
  if (form.price === 0 && basePrice.value > 0) form.price = basePrice.value
}

onMounted(async () => {
  try {
    const [cr, lr] = await Promise.all([
      API.get('/categories'),
      API.get('/levels')
    ])
    categories.value = cr.data.data || []
    const levelData = lr.data.data || []
    levels.value = levelData
    memberRates.value = levelData.map(l => ({ name: l.name, level: l.level, rate: l.discount || 10, enabled: true }))
  } catch {}
  if (productId) {
    try {
      const r = await API.get('/products/' + productId)
      const p = r.data.data
      if (p) {
        Object.assign(form, p)
        form.is_new = !!p.is_new; form.is_hot = !!p.is_hot; form.is_recommend = !!p.is_recommend
        form.is_hidden = !!p.is_hidden
        basePrice.value = p.price
        imageFileList.value = (p.images || []).map(u => ({ url: u }))
        if (p.member_rates && p.member_rates.length) {
          memberRates.value = p.member_rates
        }
        if (p.flash_sale_config && Object.keys(p.flash_sale_config).length) {
          Object.assign(flashSale, { enabled: true, ...p.flash_sale_config })
        }
        if (p.group_buy_config && Object.keys(p.group_buy_config).length) {
          Object.assign(groupBuy, { enabled: true, ...p.group_buy_config })
        }
        if (p.specs && p.specs.length) {
          specItems.value = p.specs.map(s => ({ ...s, values: s.values || JSON.parse(s.spec_values || '[]'), showInput: false, inputValue: '' }))
          specMode.value = 'multi'
        }
        if (p.publish_time) enableSchedule.value = true
      }
    } catch {}
  }
})

function handleMultiImageSuccess(r, file, fileList) {
  form.images = fileList.map(f => f.response?.data?.url || f.url).filter(Boolean)
  imageFileList.value = fileList
}
function handleImageRemove(file, fileList) {
  form.images = fileList.map(f => f.response?.data?.url || f.url).filter(Boolean)
  imageFileList.value = fileList
}
function addSpecItem() { specItems.value.push({ id: Date.now(), name: '', values: [], showInput: false, inputValue: '' }) }
function removeSpecItem(i) { specItems.value.splice(i, 1) }
function removeSpecValue(i, j) { specItems.value[i].values.splice(j, 1) }
function confirmSpecValue(i) {
  const item = specItems.value[i]
  if (item.inputValue && !item.values.includes(item.inputValue)) item.values.push(item.inputValue)
  item.inputValue = ''; item.showInput = false
}
function saveAsTemplate() { ElMessage.success('规格模板保存成功') }
function handleImportTemplate(v) {
  if (!v) return
  ElMessageBox.confirm('导入模板将覆盖当前规格项？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(() => {
      if (v === '1') specItems.value = [
        { id: 1, name: '长度', values: ['5米', '10米', '20米'], showInput: false, inputValue: '' },
        { id: 2, name: '色温', values: ['白光', '暖光', '中性光'], showInput: false, inputValue: '' }
      ]
      ElMessage.success('模板导入成功')
    }).catch(() => { templateId.value = '' })
}
function applyBatchSettings() {
  skuList.value.forEach(s => {
    if (batchForm.price > 0) s.price = batchForm.price
    if (batchForm.cost_price > 0) s.cost_price = batchForm.cost_price
    if (batchForm.stock > 0) s.stock = batchForm.stock
  })
  showBatchDialog.value = false; ElMessage.success('已应用')
}
function removeSku(i) { ElMessageBox.confirm('确认删除？','提示').then(() => skuList.value.splice(i, 1)).catch(() => {}) }
function copyShareUrl() {
  navigator.clipboard.writeText(shareUrl.value).then(() => ElMessage.success('已复制')).catch(() => {})
}
function addParam() {
  if (!form.product_params) form.product_params = []
  form.product_params.push({ name: '', value: '' })
}
function removeParam(i) { if (form.product_params) form.product_params.splice(i, 1) }
function addGuarantee() {
  if (!form.service_guarantees) form.service_guarantees = []
  form.service_guarantees.push('')
}
function removeGuarantee(i) { if (form.service_guarantees) form.service_guarantees.splice(i, 1) }

async function submitProduct() {
  if (!form.name) return ElMessage.warning('请填写商品名称')
  if (!form.category_id) return ElMessage.warning('请选择商品分类')
  if ((basePrice.value || form.price) <= 0) return ElMessage.warning('销售价必须大于0')

  submitting.value = true
  try {
    const data = {
      ...form,
      is_new: form.is_new ? 1 : 0, is_hot: form.is_hot ? 1 : 0, is_recommend: form.is_recommend ? 1 : 0,
      is_hidden: form.is_hidden ? 1 : 0,
      spec_type: specMode.value === 'multi' ? 1 : 0,
      price: basePrice.value || form.price,
      member_rates: memberRates.value,
      is_flash_sale: flashSale.enabled ? 1 : 0,
      flash_sale_config: flashSale.enabled ? { price: flashSale.price, stock: flashSale.stock, start_time: flashSale.start_time, end_time: flashSale.end_time, limit: flashSale.limit } : {},
      is_group_buy: groupBuy.enabled ? 1 : 0,
      group_buy_config: groupBuy.enabled ? { price: groupBuy.price, min_users: groupBuy.min_users, duration: groupBuy.duration, limit: groupBuy.limit } : {},
      publish_time: enableSchedule.value ? form.publish_time : '',
      give_points: form.give_points || 0,
      give_coupon_id: form.give_coupon_id || 0,
      is_limited: form.is_limited ? 1 : 0,
      is_pre_sale: form.is_pre_sale ? 1 : 0,
      pre_sale_time: form.is_pre_sale ? form.pre_sale_time : '',
      is_premium: form.is_premium ? 1 : 0,
      fake_sales: form.fake_sales || 0
    }
    if (specMode.value === 'multi' && skuList.value.length > 0) {
      data.skus = skuList.value
      data.specs = specItems.value.map((s, i) => ({ name: s.name, values: s.values, sort: i }))
      data.price = flashSale.enabled ? flashSale.price : Math.min(...skuList.value.map(s => s.price || 999999))
      data.stock = skuList.value.reduce((s, i) => s + (i.stock || 0), 0)
      data.stock_warning = form.stock_warning
    } else {
      data.price = singleForm.price || data.price
      data.stock = singleForm.stock || data.stock
      data.cost_price = singleForm.cost_price || data.cost_price
    }
    let r
    if (productId) r = await API.put('/products/' + productId, data)
    else r = await API.post('/products', data)
    if (r.data.code === 0) {
      ElMessage.success(productId ? '更新成功' : '发布成功')
      setTimeout(() => { window.location.hash = '#/products' }, 1500)
    } else {
      ElMessage.error(r.data.message || '操作失败')
    }
  } catch (e) { ElMessage.error('网络错误') }
  submitting.value = false
}
</script>

<style scoped>
.product-edit-page { max-width: 960px; margin: 0 auto; padding: 20px; }
.steps-card { margin-bottom: 20px; }
.content-body { min-height: 400px; }
.footer-actions { display: flex; justify-content: center; gap: 16px; padding: 20px 0; margin-top: 20px; border-top: 1px solid #eee; }
.panel-section { margin-bottom: 24px; padding-bottom: 24px; border-bottom: 1px solid #f0f0f0; }
.panel-section:last-child { border-bottom: none; }
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.section-header h3, .section-title { font-size: 15px; font-weight: 600; color: #333; margin: 0 0 12px 0; }
.base-form { max-width: 700px; }
.image-upload-area { display: flex; align-items: flex-start; gap: 12px; flex-wrap: wrap; }
.preview-img { width: 120px; height: 120px; border-radius: 6px; border: 1px solid #e0e0e0; object-fit: cover; }
.upload-tip { font-size: 12px; color: #999; margin-left: 8px; align-self: center; }
.multi-image-area :deep(.el-upload--picture-card) { width: 100px; height: 100px; line-height: 100px; }
.multi-image-area :deep(.el-upload-list--picture-card .el-upload-list__item) { width: 100px; height: 100px; }
.spec-mode-radio { margin-bottom: 16px; }
.spec-item-row { display: flex; align-items: flex-start; gap: 10px; padding: 10px; background: #fafafa; border-radius: 8px; margin-bottom: 10px; }
.spec-name-input { width: 140px; flex-shrink: 0; }
.spec-values-area { flex: 1; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.spec-actions { display: flex; gap: 10px; margin-top: 10px; }
.sku-table { margin-top: 10px; }
.sku-img { width: 50px; height: 50px; border-radius: 4px; }
.sku-img-upload { cursor: pointer; display: flex; justify-content: center; align-items: center; width: 50px; height: 50px; border: 1px dashed #d9d9d9; border-radius: 6px; }
.detail-preview { min-height: 300px; padding: 16px; border: 1px solid #e0e0e0; border-radius: 8px; background: #fff; line-height: 1.8; }
.detail-preview img { max-width: 100%; }
.custom-step { cursor: pointer; }
.table-tip { font-size: 12px; color: #999; margin-top: 6px; }
.form-tip { font-size: 12px; color: #999; margin-top: 4px; line-height: 1.6; }
.guarantee-list { display: flex; flex-direction: column; gap: 8px; max-width: 500px; }
.guarantee-item { display: flex; align-items: center; gap: 8px; }
.empty-tip { font-size: 13px; color: #999; padding: 20px 0; }
.recommend-grid { display: flex; gap: 12px; flex-wrap: wrap; }
.recommend-item { display: flex; align-items: center; gap: 6px; padding: 10px 16px; border: 1px solid #e0e0e0; border-radius: 8px; cursor: pointer; transition: all 0.2s; }
.recommend-item.active { border-color: #409eff; background: #ecf5ff; }
.recommend-item:hover { border-color: #409eff; }
.rec-icon { font-size: 18px; }
.rec-label { font-size: 13px; color: #333; white-space: nowrap; }
</style>
