<template>
  <div class="product-list-container">
    <!-- 搜索和商品列表 -->
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="商品分组">
              <el-select v-model="queryParams.good_group_id" placeholder="请选择分组" clearable style="width: 200px">
                <el-option
                  v-for="item in groupOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <el-icon><Search /></el-icon>查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
              <el-button type="success" @click="fetchProductList">
                <el-icon><Refresh /></el-icon>刷新
              </el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增商品
            </el-button>
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="table-section">
        <!-- 骨架屏 -->
        <div v-if="loading" class="skeleton-container">
          <div v-for="i in 5" :key="i" class="skeleton-row">
            <div class="skeleton-cell skeleton-checkbox"></div>
            <div class="skeleton-cell skeleton-id"></div>
            <div class="skeleton-cell skeleton-image"></div>
            <div class="skeleton-cell skeleton-name"></div>
            <div class="skeleton-cell skeleton-table"></div>
            <div class="skeleton-cell skeleton-price"></div>
            <div class="skeleton-cell skeleton-tag"></div>
            <div class="skeleton-cell skeleton-inventory"></div>
            <div class="skeleton-cell skeleton-action"></div>
          </div>
        </div>

        <el-table
          v-else
          v-loading="loading"
          :data="productList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :header-cell-style="{ background: '#f8f9fa', color: '#2c3e50', fontWeight: 600 }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="商品ID" width="100" />
          <el-table-column label="商品图片" width="100">
            <template #default="{ row }">
              <el-image
                :src="row.image || '/logo.svg'"
                fit="cover"
                style="width: 60px; height: 60px"
              />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" min-width="200">
            <template #default="{ row }">
              {{ row.name }}(ID:{{ row.id }})
            </template>
          </el-table-column>
          <el-table-column label="标签" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.tag" size="small" type="success">{{ row.tag }}</el-tag>
              <span v-else style="color:#c0c4cc;font-size:12px">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="table" label="所属表" width="130" />
          <el-table-column label="价格" width="120">
            <template #default="{ row }">
              <span class="price">¥{{ (row.price / 100).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存控制" width="100">
            <template #default="{ row }">
              <el-tag :type="row.inventoryControl ? 'success' : 'info'">
                {{ row.inventoryControl ? '已启用' : '未启用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="inventory" label="库存" width="100" />
          <el-table-column prop="payNum" label="单次数量" width="100" />
          <el-table-column label="推荐" width="80">
            <template #default="{ row }">
              <el-tag :type="row.recommend ? 'success' : 'info'" size="small">
                {{ row.recommend ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="售罄" width="80">
            <template #default="{ row }">
              <el-tag :type="row.soldOut ? 'danger' : 'success'" size="small">
                {{ row.soldOut ? '售罄' : '在售' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="success" link @click="handlePlan(row)">套餐</el-button>
              <el-button type="warning" link @click="handleParameter(row)">参数</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
          <!-- 空状态 -->
          <template #empty>
            <el-empty description="暂无商品数据" :image-size="120" />
          </template>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.count"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 商品表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增商品' : '编辑商品'"
      width="700px"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="120px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分组" prop="good_group_id">
          <div class="group-tree-selector">
            <el-input 
              :model-value="selectedGroupName" 
              placeholder="请选择商品分组" 
              readonly 
              @click="showGroupSelector = true"
            >
              <template #append>
                <el-button @click="showGroupSelector = true">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button 
              v-if="productForm.good_group_id" 
              type="danger" 
              link 
              @click="clearGroupSelect"
              class="clear-btn"
            >
              清除
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="商品所属表" prop="table">
          <el-input v-model="productForm.table" placeholder="请输入商品所属表" />
        </el-form-item>
        <el-form-item label="商品标签" prop="tag">
          <el-select v-model="productForm.tag" placeholder="请选择商品标签" style="width: 100%">
            <el-option
              v-for="item in tagOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="productForm.content" type="textarea" :rows="4" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品封面" prop="cover_id">
          <div class="recommend-user-selector">
            <div class="cover-preview-inline" v-if="productForm.cover_id && coverPreviewUrl">
              <el-image :src="coverPreviewUrl" fit="cover" style="width: 40px; height: 40px; border-radius: 4px;" />
            </div>
            <el-input 
              :model-value="productForm.cover_id ? `文件ID: ${productForm.cover_id}` : ''" 
              placeholder="点击选择封面图片" 
              readonly 
              @click="openCoverSelector"
            >
              <template #append>
                <el-button @click="openCoverSelector">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button 
              v-if="productForm.cover_id" 
              type="danger" 
              link 
              @click="clearCover"
              class="clear-btn"
            >
              清除
            </el-button>
          </div>
        </el-form-item>
        
        <!-- 封面选择器弹窗 -->
        <AvatarSelector
          v-model="coverSelectorVisible"
          :user-id="1"
          :current-cover-id="productForm.cover_id"
          title="选择封面"
          @confirm="handleCoverSelect"
        />
        <el-form-item label="库存控制" prop="inventory_control">
          <el-switch v-model="productForm.inventory_control" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="库存数量" prop="inventory">
          <el-input-number v-model="productForm.inventory" :min="0" placeholder="请输入库存" style="width: 100%" />
        </el-form-item>
        <el-form-item label="售罄状态" prop="sold_out">
          <el-switch v-model="productForm.sold_out" active-text="已售罄" inactive-text="正常" active-color="#f56c6c" />
          <div class="form-tip">开启后用户端无法选购该商品，KVM 商品可由后台定时任务根据 IP 资源自动标记</div>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <div class="unit-input-row">
            <el-input-number v-model="productForm.price" :min="0" :precision="2" :step="0.01" placeholder="请输入价格(元)" style="flex:1" />
            <span class="unit-text">元</span>
          </div>
        </el-form-item>
        <el-form-item label="单个商品数量" prop="pay_num">
          <el-input-number v-model="productForm.pay_num" :min="1" placeholder="请输入单个商品数量" style="width: 100%" />
        </el-form-item>
        <el-form-item label="有效期" prop="expire_time">
          <div class="unit-input-row">
            <el-input-number v-model="productForm.expire_time" :min="0" placeholder="请输入有效期" style="flex:1" />
            <span class="unit-text">天</span>
          </div>
        </el-form-item>
        <el-form-item label="推荐" prop="recommend">
          <el-switch v-model="productForm.recommend" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="推荐返还(%)" prop="recommend_rebate">
          <el-input-number v-model="productForm.recommend_rebate" :min="0" :max="100" placeholder="请输入返还百分比" style="width: 100%" />
        </el-form-item>
        <el-form-item label="参数类型" prop="arg_type">
          <el-select v-model="productForm.arg_type" placeholder="请选择参数类型" style="width: 100%">
            <el-option label="所有参数" value="all" />
            <el-option label="套餐" value="plan" />
            <el-option label="自定义" value="customize" />
          </el-select>
          <div class="form-tip">all: 所有参数 / plan: 套餐 / customize: 自定义</div>
        </el-form-item>
        <el-form-item label="归属项 ID" prop="attribution_id">
          <el-select v-model="productForm.attribution_id" placeholder="请选择归属项" style="width: 100%" @change="handleAttributionChange">
            <el-option label="虚拟机" value="vm" />
            <el-option label="其他" value="other" />
          </el-select>
          <div class="form-tip">选择归属项类型，虚拟机会关联相关数据</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 商品参数列表对话框 -->
    <el-dialog
      v-model="paramDialogVisible"
      title="商品参数管理"
      width="900px"
    >
      <div class="filter-section" style="border: none; padding: 0 0 16px 0;">
        <div class="action-bar">
          <el-button type="primary" @click="handleAddParameter">
            <el-icon><Plus /></el-icon>新增参数
          </el-button>
          <el-button type="success" @click="fetchParameterList">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="paramLoading"
        :data="parameterList"
        style="width: 100%"
        :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
      >
        <el-table-column prop="id" label="参数ID" width="80" />
        <el-table-column prop="name" label="参数名称" min-width="120" />
        <el-table-column prop="type" label="参数类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getArgTypeTag(row.type)">
              {{ getArgTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="数值配置" min-width="180">
          <template #default="{ row }">
            <template v-if="row.type === 'number'">
              <span class="number-config">步进: {{ row.step ?? '-' }} | 范围: {{ row.min ?? '0' }} ~ {{ row.max ?? '0' }}</span>
            </template>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" link @click="handleEditParameter(row)">编辑</el-button>
              <el-button type="success" link @click="handleViewParamValues(row)">查看参数值</el-button>
              <el-button type="danger" link @click="handleDeleteParameter(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无参数数据" :image-size="80" />
        </template>
      </el-table>
    </el-dialog>

    <!-- 商品参数表单对话框 -->
    <el-dialog
      v-model="paramFormDialogVisible"
      :title="paramFormType === 'add' ? '新增商品参数' : '编辑商品参数'"
      width="600px"
      append-to-body
      class="tk-dialog"
    >
      <el-form ref="paramFormRef" :model="paramForm" :rules="paramRules" label-width="100px">
        <div class="tk-section">
          <div class="tk-section-title">基本信息</div>
          <el-form-item label="参数名称" prop="arg_name">
            <el-input v-model="paramForm.arg_name" placeholder="请输入参数名称" />
          </el-form-item>
          <el-form-item label="参数类型" prop="arg_type">
            <el-radio-group v-model="paramForm.arg_type">
              <el-radio label="string">字符串</el-radio>
              <el-radio label="number">数字</el-radio>
              <el-radio label="select">选择</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否必选" prop="must">
            <el-switch v-model="paramForm.must" :active-value="true" :inactive-value="false" active-text="必选" inactive-text="可选" />
          </el-form-item>
        </div>
        <div class="tk-section">
          <div class="tk-section-title">权限控制</div>
          <el-form-item label="允许单独购买">
            <el-switch v-model="paramForm.user_add" active-text="允许" inactive-text="不允许" />
            <div style="font-size: 12px; color: #909399; margin-top: 4px">购买后是否允许单独追加购买</div>
          </el-form-item>
          <el-form-item label="用户组优惠">
            <el-switch v-model="paramForm.use_user_group_discount" active-text="允许" inactive-text="不允许" />
            <div style="font-size: 12px; color: #909399; margin-top: 4px">是否允许使用用户组优惠</div>
          </el-form-item>
          <el-form-item label="用户优惠">
            <el-switch v-model="paramForm.use_user_discount" active-text="允许" inactive-text="不允许" />
            <div style="font-size: 12px; color: #909399; margin-top: 4px">是否允许使用用户优惠（代金券与优惠码）</div>
          </el-form-item>
        </div>
        <template v-if="paramForm.arg_type === 'number'">
          <div class="tk-section">
            <div class="tk-section-title">数值参数配置</div>
            <el-form-item label="步进值" prop="arg_step">
              <el-input-number v-model="paramForm.arg_step" :min="1" placeholder="步进值" style="width: 100%" />
            </el-form-item>
            <el-form-item label="最小值" prop="arg_min">
              <el-input-number v-model="paramForm.arg_min" placeholder="最小值" style="width: 100%" />
            </el-form-item>
            <el-form-item label="最大值" prop="arg_max">
              <el-input-number v-model="paramForm.arg_max" placeholder="最大值" style="width: 100%" />
            </el-form-item>
          </div>
        </template>
      </el-form>
      <template #footer>
        <div class="tk-dialog-footer">
          <el-button @click="paramFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitParamForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 参数值管理对话框 -->
    <el-dialog
      v-model="paramValuesDialogVisible"
      title="参数值管理"
      width="800px"
      append-to-body
    >
      <div class="values-header">
        <span>参数：{{ currentParam?.name }}</span>
        <el-button type="primary" @click="handleAddParamValue">
          <el-icon><Plus /></el-icon>添加参数值
        </el-button>
      </div>
      
      <el-table
        v-loading="paramValuesLoading"
        :data="paramValueList"
        style="width: 100%; margin-top: 20px"
        :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
      >
        <el-table-column prop="id" label="值ID" width="80" />
        <el-table-column prop="name" label="值名称" min-width="120" />
        <el-table-column label="值/范围" min-width="150">
          <template #default="{ row }">
            <template v-if="currentParam?.type === 'select'">
              {{ row.value ?? '0' }}
            </template>
            <template v-else-if="currentParam?.type === 'number'">
              <el-tag size="small" type="info">{{ getRangeTypeText(row.rangeType) }} {{ (row.phase != null && row.phase !== '') ? row.phase : 0 }}</el-tag>
            </template>
            <template v-else>{{ row.value ?? '0' }}</template>
          </template>
        </el-table-column>
        <el-table-column prop="index" label="排序" width="80" />
        <el-table-column label="价格" width="100">
          <template #default="{ row }">
            ¥{{ (row.price / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" link @click="handleEditParamValue(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDeleteParamValue(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无参数值" :image-size="60" />
        </template>
      </el-table>
    </el-dialog>

    <!-- 参数值表单对话框 -->
    <el-dialog
      v-model="paramValueFormDialogVisible"
      :title="paramValueFormType === 'add' ? '添加参数值' : '编辑参数值'"
      width="550px"
      append-to-body
      class="tk-dialog"
    >
      <el-form ref="paramValueFormRef" :model="paramValueForm" :rules="paramValueRules" label-width="100px">
        <div class="tk-section">
          <div class="tk-section-title">参数值信息</div>
          <el-form-item label="值名称" prop="attr_name">
            <el-input v-model="paramValueForm.attr_name" placeholder="请输入值名称" />
          </el-form-item>
          <el-form-item v-if="currentParam?.type === 'select'" label="参数值" prop="attr_value">
            <el-input v-model="paramValueForm.attr_value" placeholder="请输入参数值" />
          </el-form-item>
          <el-form-item label="排序索引" prop="index">
            <el-input-number v-model="paramValueForm.index" :min="0" placeholder="排序索引" style="width: 100%" />
          </el-form-item>
          <el-form-item label="价格" prop="attr_price">
            <el-input-number v-model="paramValueForm.attr_price" :min="0" placeholder="请输入价格" style="width: 100%" />
          </el-form-item>
        </div>
        <template v-if="currentParam?.type === 'number'">
          <div class="tk-section">
            <div class="tk-section-title">数值范围配置</div>
            <el-form-item label="范围类型" prop="range_type">
              <el-select v-model="paramValueForm.range_type" placeholder="请选择范围类型" style="width: 100%">
                <el-option label="小于 (before)" value="before" />
                <el-option label="大于 (after)" value="after" />
                <el-option label="等于 (equal)" value="equal" />
              </el-select>
              <div class="form-tip">before: 数值 &lt; phase 时匹配 | after: 数值 &gt; phase 时匹配</div>
            </el-form-item>
            <el-form-item label="阈值" prop="attr_range">
              <el-input-number v-model="paramValueForm.attr_range" :min="0" placeholder="范围阈值" style="width: 100%" />
              <div class="form-tip">例如：phase=100, rangeType=before 表示 0-100 范围</div>
            </el-form-item>
          </div>
        </template>
      </el-form>
      <template #footer>
        <div class="tk-dialog-footer">
          <el-button @click="paramValueFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitParamValueForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商品套餐管理对话框 -->
    <el-dialog
      v-model="planDialogVisible"
      :title="`商品套餐管理 - ${currentPlanProductName}`"
      width="900px"
      append-to-body
    >
      <div class="plan-management">
        <div class="plan-header">
          <el-button type="primary" @click="handleAddPlan">
            <el-icon><Plus /></el-icon>新增套餐
          </el-button>
          <el-button type="success" @click="fetchPlanList">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </div>
        <el-table
          v-loading="planLoading"
          :data="planList"
          style="width: 100%"
          :header-cell-style="{ background: '#f8f9fa', color: '#2c3e50', fontWeight: 600 }"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="套餐名称" min-width="120" />
          <el-table-column label="参数配置" min-width="200">
            <template #default="{ row }">
              <div v-if="row.argsParsed && row.argsParsed.length > 0" class="args-list">
                <el-tag 
                  v-for="(arg, index) in row.argsParsed" 
                  :key="index" 
                  size="small" 
                  type="info"
                  style="margin-right: 4px; margin-bottom: 4px;"
                >
                  {{ arg.name || arg.value || `参数${arg.arg_id}` }}
                </el-tag>
              </div>
              <span v-else class="text-muted">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="note" label="说明" min-width="150" show-overflow-tooltip />
          <el-table-column prop="index" label="排序" width="70" />
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.disable ? 'danger' : 'success'" size="small">
                {{ row.disable ? '禁用' : '启用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="首页展示" width="90">
            <template #default="{ row }">
              <el-tag :type="row.showHome || row.show_home ? 'success' : 'info'" size="small">
                {{ row.showHome || row.show_home ? '展示' : '不展示' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="允许升级" width="90">
            <template #default="{ row }">
              <el-tag :type="row.canUpdate || row.can_update ? 'success' : 'info'" size="small">
                {{ row.canUpdate || row.can_update ? '允许' : '不允许' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEditPlan(row)">编辑</el-button>
              <el-button 
                :type="row.disable ? 'success' : 'warning'" 
                link 
                @click="handleTogglePlanStatus(row)"
              >
                {{ row.disable ? '启用' : '禁用' }}
              </el-button>
              <el-button type="danger" link @click="handleDeletePlan(row)">删除</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无套餐数据" :image-size="80" />
          </template>
        </el-table>
      </div>
    </el-dialog>

    <!-- 套餐表单对话框 -->
    <el-dialog
      v-model="planFormDialogVisible"
      :title="planFormType === 'add' ? '新增套餐' : '编辑套餐'"
      width="700px"
      append-to-body
      class="plan-form-dialog"
    >
      <div class="plan-form-content">
        <el-form
          ref="planFormRef"
          :model="planForm"
          :rules="planFormRules"
          label-width="100px"
        >
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="planForm.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="说明" prop="note">
          <el-input v-model="planForm.note" type="textarea" :rows="2" placeholder="请输入套餐说明" />
        </el-form-item>
        <el-form-item label="参数配置" prop="args">
          <div class="args-config-container">
            <!-- 参数选择下拉框 -->
            <div class="args-select-row">
              <el-select
                v-model="selectedArgIds"
                multiple
                placeholder="请选择需要配置的参数"
                style="width: 100%"
                @change="onSelectedArgsChange"
              >
                <el-option
                  v-for="spec in planSpecList"
                  :key="spec.id"
                  :label="spec.name"
                  :value="spec.id"
                />
              </el-select>
            </div>
            
            <!-- 已选参数的值配置区域 -->
            <div v-if="selectedArgSpecs.length > 0" class="args-selector">
              <div 
                v-for="spec in selectedArgSpecs" 
                :key="spec.id" 
                class="spec-item"
              >
                <div class="spec-label">{{ spec.name }}</div>
                <div class="spec-values">
                  <!-- select 类型：显示可选值 -->
                  <template v-if="spec.type === 'select' && spec.attrs && spec.attrs.length > 0">
                    <el-radio-group 
                      v-model="selectedArgs[spec.id]" 
                      size="small"
                      @change="updateArgsJson"
                    >
                      <el-radio-button 
                        v-for="attr in spec.attrs" 
                        :key="attr.id" 
                        :value="attr.id"
                      >
                        {{ attr.name }}
                      </el-radio-button>
                    </el-radio-group>
                  </template>
                  <!-- number 类型：数字输入 -->
                  <template v-else-if="spec.type === 'number'">
                    <div class="number-input-wrapper">
                      <el-input-number 
                        v-model="displayValues[spec.id]" 
                        :min="getSpecDisplayMin(spec)" 
                        :max="getSpecDisplayMax(spec)" 
                        :step="getSpecDisplayStep(spec)"
                        :step-strictly="true"
                        size="small"
                        @change="onNumberDisplayChange(spec)"
                      />
                      <el-select
                        v-if="hasUnit(spec)"
                        :model-value="displayUnits[spec.id]"
                        size="small"
                        style="width: 90px"
                        @change="(newUnit) => onPlanUnitChange(spec, newUnit)"
                      >
                        <el-option v-for="u in getParamUnits(spec)" :key="u" :label="u" :value="u" />
                      </el-select>
                      <span class="number-range">
                        ({{ spec.min ?? 0 }} - {{ spec.max ?? 0 }}
                        <template v-if="hasUnit(spec)"> {{ getBaseUnit(getArgKey(spec)) }}</template>，步长: {{ spec.step ?? 1 }})
                      </span>
                    </div>
                    <!-- 显示匹配的价格区间 -->
                    <div v-if="spec.attrs && spec.attrs.length > 0 && selectedArgs[spec.id]" class="matched-attr-info">
                      <el-tag type="success" size="small">
                        匹配区间: {{ getMatchedAttrName(spec, selectedArgs[spec.id]) }}
                      </el-tag>
                    </div>
                  </template>
                  <!-- string 类型：文本输入 -->
                  <template v-else>
                    <el-input 
                      v-model="selectedArgs[spec.id]" 
                      placeholder="请输入值"
                      size="small"
                      style="width: 200px"
                      @input="updateArgsJson"
                    />
                  </template>
                </div>
              </div>
            </div>
            <el-empty v-else-if="planSpecList.length > 0" description="请先选择需要配置的参数" :image-size="60" />
            <el-empty v-else description="暂无参数配置，请先为商品添加参数" :image-size="60" />
            
            <div class="args-actions" v-if="selectedArgSpecs.length > 0">
              <el-button type="info" plain size="small" @click="showArgsPreview = true">
                <el-icon><View /></el-icon>查看配置JSON
              </el-button>
              <el-button type="primary" plain size="small" @click="handleCopyArgsJson">
                <el-icon><CopyDocument /></el-icon>复制JSON
              </el-button>
              <el-button type="success" plain size="small" @click="handlePasteArgsJson">
                <el-icon><DocumentAdd /></el-icon>粘贴JSON
              </el-button>
              <el-button type="warning" plain size="small" @click="clearArgsSelection">
                <el-icon><Delete /></el-icon>清空选择
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="额外参数">
          <div class="args-config-container">
            <div class="form-tip" style="margin-bottom: 8px;">选择参数配置中未选择的参数作为额外参数（只需参数ID，不需要选择值）</div>
            <!-- 额外参数下拉选择 -->
            <el-select
              v-model="selectedExtraArgIds"
              multiple
              placeholder="请选择额外参数"
              style="width: 100%"
              @change="onSelectedExtraArgsChange"
            >
              <el-option
                v-for="spec in extraSpecList"
                :key="spec.id"
                :label="`${spec.name} (ID: ${spec.id})`"
                :value="spec.id"
              />
            </el-select>
            <!-- 已选额外参数展示 -->
            <!-- <div v-if="selectedExtraArgIds.length > 0" class="extra-args-display">
              <el-tag
                v-for="argId in selectedExtraArgIds"
                :key="argId"
                closable
                @close="removeExtraArg(argId)"
                style="margin: 4px"
              >
                {{ getSpecNameById(argId) }} (ID: {{ argId }})
              </el-tag>
            </div> -->
            <el-empty v-if="extraSpecList.length === 0" description="所有参数已在参数配置中选择" :image-size="40" />
          </div>
        </el-form-item>
        <el-form-item label="库存数量" prop="inventory">
          <el-input-number v-model="planForm.inventory" :min="0" style="width: 100%" placeholder="库存数量" />
          <div class="form-tip">0 表示没有库存</div>
        </el-form-item>
        <el-form-item label="启用固定价格" prop="enable_fixed_price">
          <el-switch 
            v-model="planForm.enable_fixed_price" 
            :active-value="true" 
            :inactive-value="false"
            active-text="启用" 
            inactive-text="禁用"
            :loading="fixedPriceLoading"
            @change="handleFixedPriceChange"
          />
          <div class="form-tip">启用后套餐价格将使用固定价格，不再根据参数计算</div>
        </el-form-item>
        <el-form-item label="固定价格" prop="fixed_price" v-if="planForm.enable_fixed_price === true">
          <div class="unit-input-row">
            <el-input-number v-model="planForm.fixed_price" :min="0" :precision="2" :step="0.01" style="flex:1" placeholder="请输入固定价格(元)" />
            <span class="unit-text">元</span>
          </div>
        </el-form-item>
        <el-form-item label="排序索引" prop="index">
          <el-input-number v-model="planForm.index" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="disable" v-if="planFormType === 'edit'">
          <el-radio-group v-model="planForm.disable">
            <el-radio :value="false">启用</el-radio>
            <el-radio :value="true">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="首页展示" prop="show_home">
          <el-switch 
            v-model="planForm.show_home" 
            active-text="展示" 
            inactive-text="不展示"
          />
          <div class="form-tip">控制商品套餐是否在首页显示</div>
        </el-form-item>
        <el-form-item label="允许升级" prop="can_update">
          <el-switch v-model="planForm.can_update" active-text="允许" inactive-text="不允许" />
          <div class="form-tip">控制用户是否可以升级到此套餐</div>
        </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="planFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPlanForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 参数配置预览对话框 -->
    <el-dialog
      v-model="showArgsPreview"
      title="参数配置预览"
      width="500px"
      append-to-body
    >
      <div class="args-preview">
        <div class="preview-header">
          <span>已选择 {{ Object.keys(selectedArgs).filter(k => selectedArgs[k] !== undefined && selectedArgs[k] !== '').length }} 个参数</span>
          <el-tag :type="isArgsValid ? 'success' : 'warning'" size="small">
            {{ isArgsValid ? '配置有效' : '部分参数未选择' }}
          </el-tag>
        </div>
        <el-divider />
        <div class="preview-list">
          <div v-for="spec in planSpecList" :key="spec.id" class="preview-item">
            <span class="preview-label">{{ spec.name }}:</span>
            <span class="preview-value" :class="{ 'not-selected': !getSelectedValueDisplay(spec) }">
              {{ getSelectedValueDisplay(spec) || '未选择' }}
            </span>
          </div>
        </div>
        <el-divider content-position="left">JSON 数据</el-divider>
        <pre class="json-preview">{{ formatArgsJsonPreview() }}</pre>
      </div>
      <template #footer>
        <el-button @click="showArgsPreview = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 手动粘贴JSON对话框 -->
    <el-dialog v-model="showPasteDialog" title="粘贴JSON" width="500px" append-to-body>
      <el-input v-model="pasteJsonText" type="textarea" :rows="8" placeholder="请将JSON粘贴到此处" />
      <template #footer>
        <el-button @click="showPasteDialog = false">取消</el-button>
        <el-button type="primary" @click="doPasteFromText">确定导入</el-button>
      </template>
    </el-dialog>

    <!-- 商品分组选择器对话框 -->
    <el-dialog
      v-model="showGroupSelector"
      title="选择商品分组"
      width="700px"
      append-to-body
    >
      <div class="group-selector-content">
        <el-table
          :data="groupTreeDisplayData"
          style="width: 100%"
          row-key="id"
          highlight-current-row
          @current-change="handleGroupSelect"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
          max-height="400"
        >
        <el-table-column prop="name" label="分组名称" min-width="250">
          <template #default="{ row }">
            <div class="group-name-cell" :style="{ paddingLeft: (row.level - 1) * 24 + 'px' }">
              <span 
                v-if="row.existSub" 
                class="expand-icon"
                @click.stop="toggleGroupExpand(row)"
              >
                <el-icon v-if="row._loading"><Loading /></el-icon>
                <el-icon v-else :class="{ 'is-expanded': row._expanded }"><ArrowRight /></el-icon>
              </span>
              <span v-else class="expand-placeholder"></span>
              <span class="group-name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="标签" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.tag" size="small">{{ row.tag.name }}</el-tag>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="层级" width="80">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)" size="small">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无分组数据" :image-size="60" />
        </template>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="showGroupSelector = false">取消</el-button>
        <el-button type="primary" @click="confirmGroupSelect">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search, Refresh, Picture, ArrowRight, Loading, View, CopyDocument, DocumentAdd } from '@element-plus/icons-vue'
import AvatarSelector from '@/components/admin/AvatarSelector.vue'
import { 
  getProductList, 
  createProduct, 
  updateProduct, 
  deleteProduct, 
  getProductGroupList,
  getProductTagList,
  getProductParameterList,
  getProductParameterDetail,
  createProductParameter, 
  updateProductParameter, 
  deleteProductParameter,
  addProductParameterValue,
  updateProductParameterValue,
  deleteProductParameterValue,
  getProductPlanList,
  getProductPlanDetail,
  createProductPlan,
  updateProductPlan,
  deleteProductPlan,
  disableProductPlan,
  enableProductPlan,
  disablePlanFixedPrice,
  enablePlanFixedPrice
} from '@/api/admin/product'
import { getUserVmList } from '@/api/admin/userVm'
import {
  hasUnit, getArgKey, getBaseUnit, getParamUnits, getParamDefaultUnit,
  toBaseUnit, fromBaseUnit, formatValueWithUnit
} from '@/utils/dynamicUnit'

// 查询参数
const queryParams = reactive({
  good_group_id: '',
  page: 1,
  count: 10
})

// 商品表单
const productForm = reactive({
  id: undefined,
  name: '',
  table: '',
  tag: '',
  content: '',
  cover_id: undefined,
  good_group_id: undefined, // 添加商品分组字段
  inventory_control: false,
  inventory: 0,
  price: 0,
  pay_num: 1,
  expire_time: 0,
  recommend: false,
  recommend_rebate: 0,
  arg_type: 'all', // 商品参数类型 all/plan/customize
  attribution_id: '', // 归属项ID
  sold_out: false
})

const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  table: [
    { required: true, message: '请输入商品所属表', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入商品内容', trigger: 'blur' }
  ],
  good_group_id: [
    { required: true, message: '请选择商品分组', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', message: '请输入数字', trigger: 'blur' }
  ]
}

// 状态数据
const loading = ref(false)
const productList = ref([])
const groupOptions = ref([])
const tagOptions = ref([])
const total = ref(0)

// 商品分组树形选择器
const showGroupSelector = ref(false)
const groupTreeData = ref([]) // 存储树形数据
const selectedGroup = ref(null)

// 计算选中的分组名称
const selectedGroupName = computed(() => {
  if (productForm.good_group_id) {
    // 递归查找分组名称
    const findGroup = (items) => {
      for (const item of items) {
        if (item.id === productForm.good_group_id) {
          return item
        }
        if (item._children && item._children.length > 0) {
          const found = findGroup(item._children)
          if (found) return found
        }
      }
      return null
    }
    const group = findGroup(groupTreeData.value)
    if (group) {
      return `${group.name} (ID: ${group.id})`
    }
    // 从groupOptions中查找
    const groupFromOptions = groupOptions.value.find(g => g.id === productForm.good_group_id)
    if (groupFromOptions) {
      return `${groupFromOptions.name} (ID: ${groupFromOptions.id})`
    }
    return `分组ID: ${productForm.good_group_id}`
  }
  return ''
})

// 树形数据扁平化显示
const groupTreeDisplayData = computed(() => {
  const result = []
  const flatten = (items) => {
    items.forEach(item => {
      result.push(item)
      if (item._expanded && item._children && item._children.length > 0) {
        flatten(item._children)
      }
    })
  }
  flatten(groupTreeData.value)
  return result
})

// 获取层级类型
const getLevelType = (level) => {
  const types = ['primary', 'success', 'warning', 'danger', 'info']
  return types[(level - 1) % types.length] || 'info'
}

// 获取层级文本
const getLevelText = (level) => {
  return `${level}级`
}

// 切换分组展开状态
const toggleGroupExpand = async (row) => {
  if (row._loading) return
  
  if (row._expanded) {
    row._expanded = false
  } else {
    // 如果还没加载子级
    if (row.existSub && (!row._children || row._children.length === 0)) {
      row._loading = true
      try {
        const childLevel = row.level + 1
        const res = await getProductGroupList({ 
          parent_id: row.id, 
          level: childLevel,
          count: 10 
        })
        if (res.data.code === 200) {
          const children = res.data.data.data || []
          row._children = children.map(child => ({
            ...child,
            _expanded: false,
            _children: [],
            _loading: false
          }))
        }
      } catch (error) {
        console.error('加载子级失败:', error)
      } finally {
        row._loading = false
      }
    }
    row._expanded = true
  }
}

// 选择分组
const handleGroupSelect = (row) => {
  selectedGroup.value = row
}

// 确认选择分组
const confirmGroupSelect = () => {
  if (selectedGroup.value) {
    productForm.good_group_id = selectedGroup.value.id
    showGroupSelector.value = false
    selectedGroup.value = null
  } else {
    ElMessage.warning('请选择一个分组')
  }
}

// 清除分组选择
const clearGroupSelect = () => {
  productForm.good_group_id = undefined
}
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const productFormRef = ref(null)

// 封面选择器相关
const coverSelectorVisible = ref(false)
const coverPreviewUrl = ref('')

// 获取商品列表
const fetchProductList = async () => {
  loading.value = true
  try {
    // 添加 delete=false 参数，让后端只返回未删除的数据
    const params = { ...queryParams, delete: false }
    const res = await getProductList(params)
    if (res.data.code === 200) {
      const allData = res.data.data.data || []
      // 数据已经是未删除的，直接使用
      productList.value = allData
      // 使用后端返回的总数
      total.value = res.data.data.all_count || allData.length
      
      productList.value.forEach(item => {
        item.image = item.cover || ''
      })
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取商品分组列表
const fetchGroupList = async () => {
  try {
    // 获取全部分组用于下拉列表
    const res = await getProductGroupList({ page: 1, count: 10 })
    if (res.data.code === 200) {
      groupOptions.value = res.data.data.data || []
      if (groupOptions.value.length === 0) {
        ElMessage.warning('暂无商品分组，请先创建商品分组')
      }
    }
    
    // 获取一级分组用于树形选择器
    const treeRes = await getProductGroupList({ level: 1, count: 10 })
    if (treeRes.data.code === 200) {
      const rootItems = treeRes.data.data.data || []
      groupTreeData.value = rootItems.map(item => ({
        ...item,
        _expanded: false,
        _children: [],
        _loading: false
      }))
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
    ElMessage.error('获取分组列表失败')
  }
}

// 获取商品标签列表
const fetchTagList = async () => {
  try {
    const res = await getProductTagList()
    if (res.data.code === 200) {
      tagOptions.value = res.data.data || []
      console.log('商品标签列表:', tagOptions.value) // 调试日志
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  fetchProductList()
}

// 重置查询
const resetQuery = () => {
  queryParams.good_group_id = ''
  queryParams.page = 1
  fetchProductList()
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页
const handleSizeChange = (size) => {
  queryParams.count = size
  fetchProductList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchProductList()
}

// 新增商品
const handleAdd = () => {
  // 检查是否有可用的商品分组
  if (!groupOptions.value || groupOptions.value.length === 0) {
    ElMessage.warning('请先创建商品分组')
    return
  }
  
  dialogType.value = 'add'
  dialogVisible.value = true
  coverPreviewUrl.value = '' // 清除封面预览
  Object.assign(productForm, {
    id: undefined,
    name: '',
    table: '',
    tag: '',
    content: '',
    cover_id: undefined,
    good_group_id: undefined,
    inventory_control: false,
    inventory: 0,
    attribution_id: '',
    price: 0,
    pay_num: 1,
    expire_time: 0,
    recommend: false,
    recommend_rebate: 0,
    arg_type: 'all'
  })
  productFormRef.value?.resetFields()
}

// 编辑商品
const handleEdit = (row) => {
  console.log("更新：",row)
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(productForm, {
    id: row.id,
    name: row.name,
    table: row.table,
    tag: row.tag,
    content: row.content,
    cover_id: row.coverId,
    good_group_id: row.goodGroupId,
    inventory_control: row.inventoryControl,
    inventory: row.inventory,
    price: row.price / 100, // 分转元
    pay_num: row.payNum,
    expire_time: row.expireTime,
    recommend: row.recommend,
    recommend_rebate: row.recommendRebate,
    arg_type: row.argType || 'all',
    sold_out: !!row.soldOut
  })
  coverPreviewUrl.value = row.cover || ''
}

// 规格管理
const handleSpec = (row) => {
  ElMessage.info(`商品 ${row.name} 的规格管理功能待实现`)
  // 可以跳转到规格管理页面或打开规格管理对话框
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除商品 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteProduct({ id: row.id })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchProductList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true
    try {
      // 使用 Promise.all 并行删除所有选中的商品
      const deletePromises = selectedRows.value.map(row => 
        deleteProduct({ id: row.id })
      )
      
      const results = await Promise.allSettled(deletePromises)
      
      // 统计成功和失败的数量
      const successCount = results.filter(r => r.status === 'fulfilled' && r.value?.data?.code === 200).length
      const failCount = results.length - successCount
      
      if (failCount === 0) {
        ElMessage.success(`批量删除成功，共删除 ${successCount} 条记录`)
      } else if (successCount === 0) {
        ElMessage.error(`批量删除失败，所有 ${failCount} 条记录删除失败`)
      } else {
        ElMessage.warning(`批量删除完成，成功 ${successCount} 条，失败 ${failCount} 条`)
      }
      
      // 刷新列表
      fetchProductList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除操作异常')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  productFormRef.value?.validate(async (valid) => {
    if (valid) {
      // 验证商品分组是否已选择
      if (!productForm.good_group_id) {
        ElMessage.error('请选择商品分组')
        return
      }
      
      try {
        let res
        // 准备提交的数据，确保所有字段都有正确的值
        const submitData = {
          ...productForm,
          good_group_id: Number(productForm.good_group_id), // 确保是数字类型
          cover_id: productForm.cover_id || 0,
          inventory: productForm.inventory || 0,
          price: productForm.price || 0, // 元转分
          pay_num: productForm.pay_num || 1,
          expire_time: productForm.expire_time || 0,
          recommend_rebate: productForm.recommend_rebate || 0,
          arg_type: productForm.arg_type || 'all', // 商品参数类型
          attribution_id: productForm.attribution_id || '' // 归属项ID
        }
        
        console.log('提交的数据:', submitData) // 调试日志
        
        if (dialogType.value === 'add') {
          res = await createProduct(submitData)
        } else {
          res = await updateProduct(submitData)
        }
        if (res.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
          dialogVisible.value = false
          fetchProductList()
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 处理归属项变化
const handleAttributionChange = async (value) => {
  if (value === 'vm' && productForm.id) {
    try {
      // 当选择虚拟机时，调用用户虚拟机列表API
      const res = await getUserVmList({ 
        page: 1, 
        count: 10,
        good_id: productForm.id // 传递当前商品ID
      })
      if (res.data.code === 200) {
        console.log('虚拟机列表:', res.data.data)
        ElMessage.success('已获取虚拟机关联数据')
      }
    } catch (error) {
      console.error('获取虚拟机列表失败:', error)
      ElMessage.error('获取虚拟机关联数据失败')
    }
  }
}

// 打开封面选择器
const openCoverSelector = () => {
  coverSelectorVisible.value = true
}

// 处理封面选择
const handleCoverSelect = async (data) => {
  productForm.cover_id = data.cover_id
  coverPreviewUrl.value = data.url
}

// 清除封面
const clearCover = () => {
  productForm.cover_id = undefined
  coverPreviewUrl.value = ''
}

const loadCoverPreview = (coverId) => {
  const item = productList.value.find(p => p.coverId === coverId)
  coverPreviewUrl.value = item?.cover || ''
}

// 初始化
onMounted(() => {
  fetchProductList()
  fetchGroupList()
  fetchTagList()
})

// ---------------------------------------------------------------------
// 参数管理相关逻辑
// ---------------------------------------------------------------------

// 状态
const paramDialogVisible = ref(false)
const paramLoading = ref(false)
const parameterList = ref([])
const currentProductId = ref(null)

const paramFormDialogVisible = ref(false)
const paramFormType = ref('add')
const paramFormRef = ref(null)
const paramForm = reactive({
  arg_id: undefined,
  arg_name: '',
  arg_type: 'string',
  must: false,
  arg_step: 1,
  arg_min: 0,
  arg_max: 100,
  user_add: false,
  use_user_group_discount: false,
  use_user_discount: false
})

const paramRules = {
  arg_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
  arg_type: [{ required: true, message: '请选择参数类型', trigger: 'change' }]
}

const paramValuesDialogVisible = ref(false)
const paramValuesLoading = ref(false)
const paramValueList = ref([])
const currentParam = ref(null)

const paramValueFormDialogVisible = ref(false)
const paramValueFormType = ref('add')
const paramValueFormRef = ref(null)
const paramValueForm = reactive({
  attr_id: undefined,
  attr_name: '',
  attr_value: '',
  attr_price: 0,
  index: 0,
  attr_range: 0,
  range_type: 'equal'
})

const paramValueRules = {
  attr_name: [{ required: true, message: '请输入值名称', trigger: 'blur' }]
}

// 打开参数管理
const handleParameter = (row) => {
  currentProductId.value = row.id
  paramDialogVisible.value = true
  fetchParameterList()
}

// 获取参数列表
const fetchParameterList = async () => {
  if (!currentProductId.value) return
  paramLoading.value = true
  try {
    const res = await getProductParameterList({ good_id: currentProductId.value })
    if (res.data.code === 200) {
      parameterList.value = res.data.data || []
    }
  } catch (error) {
    ElMessage.error('获取参数列表失败')
  } finally {
    paramLoading.value = false
  }
}

// 参数类型显示
const getArgTypeText = (type) => {
  const typeMap = { 'string': '字符串', 'number': '数字', 'select': '选择' }
  return typeMap[type] || '未知'
}

const getArgTypeTag = (type) => {
  const tagMap = { 'string': 'primary', 'number': 'success', 'select': 'warning' }
  return tagMap[type] || 'info'
}

// 范围类型显示
const getRangeTypeText = (type) => {
  const typeMap = { 'after': '大于 ＞', 'before': '小于 ＜', 'equal': '等于 ＝' }
  return typeMap[type] || type || '-'
}

// 新增参数
const handleAddParameter = () => {
  paramFormType.value = 'add'
  paramFormDialogVisible.value = true
  Object.assign(paramForm, {
    arg_id: undefined,
    arg_name: '',
    arg_type: 'string',
    must: false,
    arg_step: 1,
    arg_min: 0,
    arg_max: 100,
    user_add: false,
    use_user_group_discount: false,
    use_user_discount: false
  })
  nextTick(() => {
    paramFormRef.value?.resetFields()
  })
}

// 编辑参数
const handleEditParameter = (row) => {
  paramFormType.value = 'edit'
  paramFormDialogVisible.value = true
  Object.assign(paramForm, {
    arg_id: row.id,
    arg_name: row.name,
    arg_type: row.type,
    must: row.must || false,
    arg_step: row.step || 1,
    arg_min: row.min || 0,
    arg_max: row.max || 100,
    user_add: row.userAdd ?? row.user_add ?? false,
    use_user_group_discount: row.useUserGroupDiscount ?? row.use_user_group_discount ?? false,
    use_user_discount: row.useUserDiscount ?? row.use_user_discount ?? false
  })
}

// 删除参数
const handleDeleteParameter = (row) => {
  ElMessageBox.confirm(`确认删除参数 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteProductParameter({ good_id: currentProductId.value, arg_id: row.id })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchParameterList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交参数表单
const submitParamForm = () => {
  paramFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          good_id: Number(currentProductId.value),
          arg_name: paramForm.arg_name,
          arg_type: paramForm.arg_type,
          must: paramForm.must === true,
          user_add: paramForm.user_add === true,
          use_user_group_discount: paramForm.use_user_group_discount === true,
          use_user_discount: paramForm.use_user_discount === true
        }
        // number 类型添加额外参数
        if (paramForm.arg_type === 'number') {
          submitData.arg_step = Number(paramForm.arg_step)
          submitData.arg_min = Number(paramForm.arg_min)
          submitData.arg_max = Number(paramForm.arg_max)
        }
        if (paramFormType.value === 'edit') {
          submitData.arg_id = paramForm.arg_id
        }
        
        const res = paramFormType.value === 'add' 
          ? await createProductParameter(submitData)
          : await updateProductParameter(submitData)
          
        if (res.data.code === 200) {
          ElMessage.success(paramFormType.value === 'add' ? '新增成功' : '修改成功')
          paramFormDialogVisible.value = false
          fetchParameterList()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 查看参数值
const handleViewParamValues = (row) => {
  currentParam.value = row
  paramValuesDialogVisible.value = true
  fetchParamValuesList()
}

// 获取参数值列表
const fetchParamValuesList = async () => {
  if (!currentProductId.value || !currentParam.value) return
  paramValuesLoading.value = true
  try {
    const res = await getProductParameterDetail({ 
      good_id: currentProductId.value, 
      arg_id: currentParam.value.id 
    })
    if (res.data.code === 200) {
      paramValueList.value = res.data.data.attrs || []
    }
  } catch (error) {
    ElMessage.error('获取参数值列表失败')
  } finally {
    paramValuesLoading.value = false
  }
}

// 添加参数值
const handleAddParamValue = () => {
  paramValueFormType.value = 'add'
  paramValueFormDialogVisible.value = true
  nextTick(() => {
    paramValueFormRef.value?.resetFields()
    Object.assign(paramValueForm, {
      attr_id: undefined,
      attr_name: '',
      attr_value: '',
      attr_price: 0,
      index: 0,
      attr_range: 0,
      range_type: 'equal'
    })
  })
}

// 编辑参数值
const handleEditParamValue = (row) => {
  paramValueFormType.value = 'edit'
  paramValueFormDialogVisible.value = true
  Object.assign(paramValueForm, {
    attr_id: row.id,
    attr_name: row.name,
    attr_value: row.value || '',
    attr_price: row.price / 100 || 0,
    index: row.index || 0,
    attr_range: row.phase || 0,  // API返回的字段是 phase
    range_type: row.rangeType || 'equal'
  })
}

// 删除参数值
const handleDeleteParamValue = (row) => {
  ElMessageBox.confirm(`确认删除参数值 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteProductParameterValue({ 
        good_id: currentProductId.value, 
        attr_id: row.id 
      })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchParamValuesList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交参数值表单
const submitParamValueForm = () => {
  paramValueFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          good_id: Number(currentProductId.value),
          arg_id: Number(currentParam.value.id),
          attr_name: paramValueForm.attr_name,
          index: Number(paramValueForm.index),
          attr_price: Number(paramValueForm.attr_price)
        }
        // select 类型添加 attr_value
        if (currentParam.value.type === 'select') {
          submitData.attr_value = paramValueForm.attr_value
        }
        // number 类型添加范围参数（提交用 attr_range，获取返回 phase）
        if (currentParam.value.type === 'number') {
          submitData.attr_range = Number(paramValueForm.attr_range)
          submitData.range_type = paramValueForm.range_type
        }
        if (paramValueFormType.value === 'edit') {
          submitData.attr_id = paramValueForm.attr_id
        }
        
        const res = paramValueFormType.value === 'add'
          ? await addProductParameterValue(submitData)
          : await updateProductParameterValue(submitData)
          
        if (res.data.code === 200) {
          ElMessage.success(paramValueFormType.value === 'add' ? '添加成功' : '修改成功')
          paramValueFormDialogVisible.value = false
          fetchParamValuesList()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// ==================== 商品套餐管理 ====================
const planDialogVisible = ref(false)
const planLoading = ref(false)
const planList = ref([])
const currentPlanProductId = ref(null)
const currentPlanProductName = ref('')

// 套餐表单
const planFormDialogVisible = ref(false)
const planFormType = ref('add')
const planFormRef = ref(null)
const fixedPriceLoading = ref(false) // 固定价格开关加载状态
const planForm = reactive({
  plan_id: undefined,
  name: '',
  note: '',
  args: '',
  extra_arg_ids: '',
  extra_arg_ids_array: [],
  inventory: 0,
  fixed_price: 0,
  enable_fixed_price: false,
  index: 0,
  disable: false,
  show_home: false,
  can_update: false
})

const planFormRules = {
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }]
}

// 套餐参数选择相关
const planSpecList = ref([]) // 当前商品的参数列表
const selectedArgIds = ref([]) // 选中的参数ID列表
const selectedArgs = reactive({}) // 选中的参数值（基础单位）
const displayValues = reactive({}) // 显示值（当前选中单位）
const displayUnits = reactive({}) // 当前选中的显示单位
const showArgsPreview = ref(false)
const showPasteDialog = ref(false)
const pasteJsonText = ref('')

// 额外参数相关
const selectedExtraArgIds = ref([]) // 选中的额外参数ID列表

// 计算已选参数的spec列表
const selectedArgSpecs = computed(() => {
  return planSpecList.value.filter(spec => selectedArgIds.value.includes(spec.id))
})

// 计算额外参数列表（参数配置中未选择的参数）
const extraSpecList = computed(() => {
  return planSpecList.value.filter(spec => !selectedArgIds.value.includes(spec.id))
})

// 获取套餐表单用的参数列表
const fetchPlanSpecList = async () => {
  if (!currentPlanProductId.value) return
  try {
    const res = await getProductParameterList({ good_id: currentPlanProductId.value })
    if (res.data.code === 200) {
      planSpecList.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取参数列表失败:', error)
    planSpecList.value = []
  }
}

// 参数选择变化
const onSelectedArgsChange = () => {
  for (const key in selectedArgs) {
    if (!selectedArgIds.value.includes(Number(key))) {
      delete selectedArgs[key]
      delete displayValues[key]
      delete displayUnits[key]
    }
  }
  for (const specId of selectedArgIds.value) {
    const spec = planSpecList.value.find(s => s.id === specId)
    if (spec && spec.type === 'number' && hasUnit(spec) && !displayUnits[specId]) {
      displayUnits[specId] = getParamDefaultUnit(spec)
    }
  }
  selectedExtraArgIds.value = selectedExtraArgIds.value.filter(
    id => !selectedArgIds.value.includes(id)
  )
  updateArgsJson()
  updateExtraArgIds()
}

const getSpecDisplayMin = (spec) => {
  if (!hasUnit(spec)) return spec.min ?? 0
  const argKey = getArgKey(spec)
  const unit = displayUnits[spec.id]
  return unit ? fromBaseUnit(spec.min ?? 0, unit, argKey) : (spec.min ?? 0)
}
const getSpecDisplayMax = (spec) => {
  if (!hasUnit(spec)) return spec.max ?? 0
  const argKey = getArgKey(spec)
  const unit = displayUnits[spec.id]
  return unit ? fromBaseUnit(spec.max ?? 0, unit, argKey) : (spec.max ?? 0)
}
const getSpecDisplayStep = (spec) => {
  if (!hasUnit(spec)) return spec.step ?? 1
  const argKey = getArgKey(spec)
  const unit = displayUnits[spec.id]
  if (!unit) return spec.step ?? 1
  const converted = fromBaseUnit(spec.step ?? 1, unit, argKey)
  return converted > 0 ? converted : 1
}

const onNumberDisplayChange = (spec) => {
  if (hasUnit(spec)) {
    const argKey = getArgKey(spec)
    const unit = displayUnits[spec.id]
    selectedArgs[spec.id] = Math.round(toBaseUnit(displayValues[spec.id] || 0, unit, argKey))
  } else {
    selectedArgs[spec.id] = displayValues[spec.id]
  }
  updateArgsJson()
}

const onPlanUnitChange = (spec, newUnit) => {
  const argKey = getArgKey(spec)
  const oldUnit = displayUnits[spec.id]
  const oldDisplay = displayValues[spec.id] || 0
  const baseValue = oldUnit ? toBaseUnit(oldDisplay, oldUnit, argKey) : oldDisplay
  displayUnits[spec.id] = newUnit
  displayValues[spec.id] = fromBaseUnit(baseValue, newUnit, argKey)
  selectedArgs[spec.id] = Math.round(baseValue)
  updateArgsJson()
}

// 额外参数选择变化
const onSelectedExtraArgsChange = () => {
  updateExtraArgIds()
}

// 移除额外参数
const removeExtraArg = (argId) => {
  selectedExtraArgIds.value = selectedExtraArgIds.value.filter(id => id !== argId)
  updateExtraArgIds()
}

// 根据ID获取参数名称
const getSpecNameById = (specId) => {
  const spec = planSpecList.value.find(s => s.id === specId)
  return spec ? spec.name : `参数${specId}`
}

// 更新额外参数ID
const updateExtraArgIds = () => {
  planForm.extra_arg_ids = selectedExtraArgIds.value.join(',')
  planForm.extra_arg_ids_array = [...selectedExtraArgIds.value]
}

// 更新args JSON字符串
// 格式：{ arg_id: 参数id, name: 参数名称, attr_id: 参数值id, value/number: 参数值 }
const updateArgsJson = () => {
  const argsArray = []
  
  // 只处理已选择的参数
  for (const specId of selectedArgIds.value) {
    const spec = planSpecList.value.find(s => s.id === specId)
    if (!spec) continue
    
    const selectedValue = selectedArgs[spec.id]
    if (selectedValue === undefined || selectedValue === '') continue
    
    if (spec.type === 'select') {
      const attrObj = spec.attrs?.find(a => a.id === selectedValue)
      if (attrObj) {
        argsArray.push({
          arg_id: spec.id, name: spec.name, attr_id: attrObj.id,
          value: attrObj.value || '', key: getArgKey(spec) || undefined
        })
      }
    } else if (spec.type === 'number') {
      const numValue = Number(selectedValue)
      const matchedAttr = findMatchingNumberAttr(spec, numValue)
      argsArray.push({
        arg_id: spec.id, name: spec.name,
        attr_id: matchedAttr ? matchedAttr.id : 0,
        number: numValue, key: getArgKey(spec) || undefined
      })
    } else {
      argsArray.push({
        arg_id: spec.id, name: spec.name, attr_id: 0,
        value: String(selectedValue), key: getArgKey(spec) || undefined
      })
    }
  }
  
  planForm.args = argsArray.length > 0 ? JSON.stringify(argsArray) : ''
}

// 根据数值找到匹配的价格区间
const findMatchingNumberAttr = (spec, numValue) => {
  if (!spec.attrs || spec.attrs.length === 0) return null
  
  // 按 index 排序
  const sortedAttrs = [...spec.attrs].sort((a, b) => (a.index || 0) - (b.index || 0))
  
  for (const attr of sortedAttrs) {
    const phase = attr.phase || 0
    const rangeType = attr.rangeType || 'before'
    
    if (rangeType === 'before' && numValue < phase) {
      return attr
    } else if (rangeType === 'after' && numValue > phase) {
      return attr
    } else if (rangeType === 'equal' && numValue === phase) {
      return attr
    }
  }
  
  // 如果没有匹配的，返回最后一个区间
  return sortedAttrs[sortedAttrs.length - 1]
}

// 获取匹配的价格区间名称（用于模板显示）
const getMatchedAttrName = (spec, numValue) => {
  const matchedAttr = findMatchingNumberAttr(spec, Number(numValue))
  if (matchedAttr) {
    const priceText = matchedAttr.price ? ` (+¥${(matchedAttr.price / 100).toFixed(2)})` : ''
    return `${matchedAttr.name}${priceText}`
  }
  return '无匹配区间'
}

// 生成参数项的唯一ID（用于没有attrs的number和string类型）
const generateArgId = (argId, value) => {
  // 使用参数ID和值的组合生成一个数字ID
  const valueHash = String(value).split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return argId * 10000 + (valueHash % 10000)
}

// 更新额外参数JSON
// 清空参数选择
const clearArgsSelection = () => {
  selectedArgIds.value = []
  for (const key in selectedArgs) delete selectedArgs[key]
  for (const key in displayValues) delete displayValues[key]
  for (const key in displayUnits) delete displayUnits[key]
  selectedExtraArgIds.value = []
  planForm.args = ''
  planForm.extra_arg_ids = ''
  planForm.extra_arg_ids_array = []
}

const handleCopyArgsJson = async () => {
  if (!planForm.args) { ElMessage.warning('暂无参数配置可复制'); return }
  try {
    await navigator.clipboard.writeText(planForm.args)
    ElMessage.success('已复制参数配置JSON到剪贴板')
  } catch {
    const textarea = document.createElement('textarea')
    textarea.value = planForm.args
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)
    ElMessage.success('已复制参数配置JSON到剪贴板')
  }
}

const handlePasteArgsJson = async () => {
  let clipText = ''
  try {
    clipText = await navigator.clipboard.readText()
  } catch {
    pasteJsonText.value = ''
    showPasteDialog.value = true
    return
  }
  if (!clipText || !clipText.trim()) { ElMessage.warning('剪贴板为空'); return }
  applyPastedJson(clipText)
}

const doPasteFromText = () => {
  const text = pasteJsonText.value
  if (!text || !text.trim()) { ElMessage.warning('请输入JSON内容'); return }
  showPasteDialog.value = false
  applyPastedJson(text)
}

const applyPastedJson = (jsonText) => {
  let pastedArgs
  try {
    pastedArgs = JSON.parse(jsonText)
    if (!Array.isArray(pastedArgs)) { ElMessage.error('JSON格式错误，需要数组格式'); return }
  } catch {
    ElMessage.error('JSON解析失败，请检查格式')
    return
  }
  clearArgsSelection()
  const matchedIds = []
  for (const arg of pastedArgs) {
    let spec = null
    if (arg.key) spec = planSpecList.value.find(s => getArgKey(s) === arg.key)
    if (!spec && arg.name) spec = planSpecList.value.find(s => s.name === arg.name)
    if (!spec && arg.arg_id) spec = planSpecList.value.find(s => s.id === arg.arg_id)
    if (!spec) continue
    matchedIds.push(spec.id)
    if (spec.type === 'select') {
      if (arg.attr_id) {
        const attrObj = spec.attrs?.find(a => a.id === arg.attr_id)
        if (attrObj) selectedArgs[spec.id] = attrObj.id
        else if (arg.value) { const byVal = spec.attrs?.find(a => a.value === arg.value || a.name === arg.value); if (byVal) selectedArgs[spec.id] = byVal.id }
      } else if (arg.value) { const byVal = spec.attrs?.find(a => a.value === arg.value || a.name === arg.value); if (byVal) selectedArgs[spec.id] = byVal.id }
    } else if (spec.type === 'number') {
      const numVal = Number(arg.number !== undefined ? arg.number : arg.value)
      selectedArgs[spec.id] = numVal
      if (hasUnit(spec)) {
        const unit = getParamDefaultUnit(spec)
        displayUnits[spec.id] = unit
        displayValues[spec.id] = fromBaseUnit(numVal, unit, getArgKey(spec))
      } else {
        displayValues[spec.id] = numVal
      }
    } else {
      selectedArgs[spec.id] = arg.value || ''
    }
  }
  selectedArgIds.value = matchedIds
  updateArgsJson()
  updateExtraArgIds()
  ElMessage.success(`已从JSON导入 ${matchedIds.length} 个参数配置`)
}

const getSelectedValueDisplay = (spec) => {
  const selectedValue = selectedArgs[spec.id]
  if (selectedValue === undefined || selectedValue === '') return null
  if (spec.type === 'select') {
    const attrObj = spec.attrs?.find(a => a.id === selectedValue)
    return attrObj ? attrObj.name : null
  }
  if (hasUnit(spec)) {
    const argKey = getArgKey(spec)
    const unit = displayUnits[spec.id] || getParamDefaultUnit(spec)
    const displayVal = fromBaseUnit(Number(selectedValue), unit, argKey)
    return formatValueWithUnit(displayVal, unit)
  }
  return String(selectedValue)
}

// 检查参数配置是否有效
const isArgsValid = computed(() => {
  // 至少选择了一个参数
  return Object.keys(selectedArgs).some(k => selectedArgs[k] !== undefined && selectedArgs[k] !== '')
})

// 格式化预览JSON
const formatArgsJsonPreview = () => {
  if (!planForm.args) return '[]'
  try {
    return JSON.stringify(JSON.parse(planForm.args), null, 2)
  } catch {
    return planForm.args
  }
}

// 从已有的args JSON初始化选择状态
const initSelectedArgsFromJson = (argsJson, extraArgIds = []) => {
  // 清空现有选择
  clearArgsSelection()
  
  // 解析 args 中包含的参数ID
  const argsParamIds = []
  
  if (argsJson) {
    try {
      const argsArray = typeof argsJson === 'string' ? JSON.parse(argsJson) : argsJson
      if (Array.isArray(argsArray)) {
        for (const arg of argsArray) {
          // 通过 arg_id 找到对应的参数
          const spec = planSpecList.value.find(s => s.id === arg.arg_id)
          if (!spec) continue
          
          // 添加到已选参数ID列表
          argsParamIds.push(spec.id)
          
          if (spec.type === 'select') {
            // select 类型：优先使用 attr_id，兼容旧格式的 id
            if (arg.attr_id) {
              selectedArgs[spec.id] = arg.attr_id
            } else if (arg.id) {
              selectedArgs[spec.id] = arg.id
            } else {
              const attrObj = spec.attrs?.find(a => a.value === arg.value || a.name === arg.name)
              if (attrObj) {
                selectedArgs[spec.id] = attrObj.id
              }
            }
          } else if (spec.type === 'number') {
            const numVal = Number(arg.number !== undefined ? arg.number : arg.value)
            selectedArgs[spec.id] = numVal
            if (hasUnit(spec)) {
              const unit = getParamDefaultUnit(spec)
              displayUnits[spec.id] = unit
              displayValues[spec.id] = fromBaseUnit(numVal, unit, getArgKey(spec))
            } else {
              displayValues[spec.id] = numVal
            }
          } else {
            selectedArgs[spec.id] = arg.value
          }
        }
      }
    } catch (e) {
      console.error('解析args失败:', e)
    }
  }
  
  // 设置已选参数ID列表
  selectedArgIds.value = argsParamIds
  
  // 处理额外参数（排除已在args中的参数）
  if (extraArgIds && extraArgIds.length > 0) {
    selectedExtraArgIds.value = extraArgIds.filter(id => !argsParamIds.includes(id))
    console.log('initSelectedArgsFromJson - 额外参数已设置:', selectedExtraArgIds.value)
  } else {
    console.log('initSelectedArgsFromJson - 无额外参数或为空, extraArgIds:', extraArgIds)
  }
  
  // 根据选择状态重新生成 JSON（确保初始状态就有 JSON 展示）
  updateArgsJson()
  // 同步更新 planForm.extra_arg_ids
  updateExtraArgIds()
}

// 打开套餐管理
const handlePlan = (row) => {
  currentPlanProductId.value = row.id
  currentPlanProductName.value = row.name
  planDialogVisible.value = true
  fetchPlanList()
}

// 解析args JSON字符串
const parseArgs = (argsStr) => {
  if (!argsStr) return []
  try {
    const parsed = JSON.parse(argsStr)
    return Array.isArray(parsed) ? parsed : []
  } catch (e) {
    console.error('解析args失败:', e)
    return []
  }
}

// 格式化显示args
const formatArgs = (argsParsed) => {
  if (!argsParsed || argsParsed.length === 0) return '-'
  return argsParsed.map(arg => arg.name || arg.value).filter(Boolean).join(', ')
}

// 获取套餐列表
const fetchPlanList = async () => {
  if (!currentPlanProductId.value) return
  planLoading.value = true
  try {
    const res = await getProductPlanList({ good_id: String(currentPlanProductId.value) })
    
    if (res.data.code === 200) {
      // 兼容两种数据结构
      let data = res.data.data
      if (Array.isArray(data)) {
        // 处理args字段，将JSON字符串解析为对象
        planList.value = data.map(item => ({
          ...item,
          argsParsed: parseArgs(item.args)
        }))
      } else if (data && data.list) {
        planList.value = data.list.map(item => ({
          ...item,
          argsParsed: parseArgs(item.args)
        }))
      } else if (data && data.data) {
        planList.value = data.data.map(item => ({
          ...item,
          argsParsed: parseArgs(item.args)
        }))
      } else {
        planList.value = []
      }
    }
  } catch (error) {
    console.error('获取套餐列表失败:', error)
    ElMessage.error('获取套餐列表失败')
  } finally {
    planLoading.value = false
  }
}

// 新增套餐
const handleAddPlan = async () => {
  planFormType.value = 'add'
  
  // 先获取参数列表
  await fetchPlanSpecList()
  
  // 清空选择状态
  clearArgsSelection()
  
  // 默认选择所有参数
  selectedArgIds.value = planSpecList.value.map(spec => spec.id)
  for (const spec of planSpecList.value) {
    if (spec.type === 'number' && hasUnit(spec)) {
      displayUnits[spec.id] = getParamDefaultUnit(spec)
    }
  }
  
  Object.assign(planForm, {
    plan_id: undefined,
    name: '',
    note: '',
    args: '',
    extra_arg_ids: '',
    extra_arg_ids_array: [],
    inventory: 0,
    fixed_price: 0,
    enable_fixed_price: false,
    index: 0,
    disable: false,
    show_home: false,
    can_update: false
  })
  
  planFormDialogVisible.value = true
  
  nextTick(() => {
    planFormRef.value?.resetFields()
  })
}

// 编辑套餐
const handleEditPlan = async (row) => {
  planFormType.value = 'edit'
  
  // 先获取参数列表
  await fetchPlanSpecList()
  
  try {
    const res = await getProductPlanDetail({ good_id: String(currentPlanProductId.value), plan_id: String(row.id) })
    if (res.data.code === 200) {
      const data = res.data.data
      
      // 处理 extra_arg_ids（兼容驼峰和下划线命名，以及 extraArgs 对象数组）
      let extraArgIdsArray = []
      const extraArgIdsRaw = data.extraArgIds || data.extra_arg_ids
      const extraArgsRaw = data.extraArgs || data.extra_args
      
      if (extraArgIdsRaw) {
        // 优先使用 extra_arg_ids 字段
        if (Array.isArray(extraArgIdsRaw)) {
          extraArgIdsArray = extraArgIdsRaw.map(Number)
        } else if (typeof extraArgIdsRaw === 'string' && extraArgIdsRaw.trim()) {
          extraArgIdsArray = extraArgIdsRaw.split(',').filter(Boolean).map(Number)
        }
      } else if (extraArgsRaw && Array.isArray(extraArgsRaw)) {
        // 如果有 extraArgs 对象数组，从中提取参数ID
        extraArgIdsArray = extraArgsRaw.map(arg => arg.id || arg.arg_id || arg.argId).filter(Boolean).map(Number)
      }
      
      console.log('编辑套餐 - 原始数据:', data)
      console.log('编辑套餐 - extraArgIdsRaw:', extraArgIdsRaw)
      console.log('编辑套餐 - extraArgsRaw:', extraArgsRaw)
      console.log('编辑套餐 - extraArgIdsArray:', extraArgIdsArray)
      
      Object.assign(planForm, {
        plan_id: data.id,
        name: data.name || '',
        note: data.note || '',
        args: data.args || '',
        extra_arg_ids: extraArgIdsArray.join(','),
        extra_arg_ids_array: extraArgIdsArray,
        inventory: data.inventory || 0,
        fixed_price: ((data.fixedPrice || data.fixed_price || 0) / 100).toFixed(2) * 1, // 分转元
        enable_fixed_price: !!(data.enableFixedPrice || data.enable_fixed_price), // 转为布尔值
        index: data.index || 0,
        disable: data.disable || false,
        show_home: !!(data.showHome || data.show_home),
        can_update: !!(data.canUpdate || data.can_update)
      })
      
      // 从已有的args初始化选择状态（包括额外参数）
      initSelectedArgsFromJson(data.args, extraArgIdsArray)
      
      planFormDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取套餐详情失败')
  }
}

// 删除套餐
const handleDeletePlan = (row) => {
  ElMessageBox.confirm(`确认删除套餐 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteProductPlan({ good_id: String(currentPlanProductId.value), plan_id: String(row.id) })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchPlanList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 切换套餐状态
const handleTogglePlanStatus = async (row) => {
  try {
    const res = row.disable
      ? await enableProductPlan({ good_id: String(currentPlanProductId.value), plan_id: String(row.id) })
      : await disableProductPlan({ good_id: String(currentPlanProductId.value), plan_id: String(row.id) })
    if (res.data.code === 200) {
      ElMessage.success(row.disable ? '启用成功' : '禁用成功')
      fetchPlanList()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理固定价格开关变化（编辑模式下调用API）
const handleFixedPriceChange = async (value) => {
  // 只有编辑模式下才调用API
  if (planFormType.value !== 'edit' || !planForm.plan_id) {
    return
  }
  
  fixedPriceLoading.value = true
  try {
    const data = {
      good_id: String(currentPlanProductId.value),
      plan_id: String(planForm.plan_id)
    }
    
    let res
    if (value === true) {
      res = await enablePlanFixedPrice(data)
    } else {
      res = await disablePlanFixedPrice(data)
    }
    
    if (res.data.code === 200) {
      ElMessage.success(value ? '已启用固定价格' : '已禁用固定价格')
    } else {
      // 恢复原值
      planForm.enable_fixed_price = !value
      ElMessage.error(res.data.message || '操作失败')
    }
  } catch (error) {
    // 恢复原值
    planForm.enable_fixed_price = !value
    console.error('切换固定价格状态失败:', error)
    ElMessage.error('操作失败')
  } finally {
    fixedPriceLoading.value = false
  }
}

// 提交套餐表单
const submitPlanForm = () => {
  planFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 确保 extra_arg_ids 是最新的
        const extraArgIdsStr = selectedExtraArgIds.value.join(',')
        
        const submitData = {
          good_id: String(currentPlanProductId.value),
          name: planForm.name,
          note: planForm.note || '',
          args: planForm.args || '',
          extra_arg_ids: extraArgIdsStr || planForm.extra_arg_ids || '',
          inventory: Number(planForm.inventory) || 0,
          fixed_price: Math.round(Number(planForm.fixed_price) * 100) || 0, // 元转分
          index: Number(planForm.index) || 0,
          show_home: planForm.show_home === true,
          can_update: planForm.can_update === true
        }
        
        // 只有创建时才传递 enable_fixed_price
        if (planFormType.value === 'add') {
          submitData.enable_fixed_price = planForm.enable_fixed_price === true
        }
        
        console.log('提交套餐数据:', submitData)
        console.log('selectedExtraArgIds:', selectedExtraArgIds.value)
        
        let res
        if (planFormType.value === 'add') {
          res = await createProductPlan(submitData)
        } else {
          submitData.plan_id = String(planForm.plan_id)
          submitData.disable = planForm.disable
          res = await updateProductPlan(submitData)
        }
        
        if (res.data.code === 200) {
          ElMessage.success(planFormType.value === 'add' ? '新增成功' : '修改成功')
          planFormDialogVisible.value = false
          fetchPlanList()
        } else {
          ElMessage.error(res.data.message || '操作失败')
        }
      } catch (error) {
        console.error('套餐操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

</script>

<style scoped>
.product-list-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 400px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item__label) {
  margin-right: 8px;
  white-space: nowrap;
}

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form {
    min-width: 100%;
  }
  
  .action-bar {
    width: 100%;
    justify-content: flex-end;
  }
}

.table-section {
  padding: 0;
}

.price {
  color: #e74c3c;
  font-weight: bold;
  font-size: 14px;
}

.pagination {
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 0;
}

/* 骨架屏样式 */
.skeleton-container {
  padding: 20px;
}

.skeleton-row {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  gap: 16px;
}

.skeleton-row:last-child {
  border-bottom: none;
}

.skeleton-cell {
  height: 20px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s ease-in-out infinite;
  border-radius: 4px;
}

.skeleton-checkbox { width: 55px; }
.skeleton-id { width: 100px; }
.skeleton-image { width: 60px; height: 60px; }
.skeleton-name { width: 200px; }
.skeleton-table { width: 150px; }
.skeleton-price { width: 120px; }
.skeleton-tag { width: 100px; }
.skeleton-inventory { width: 100px; }
.skeleton-action { width: 200px; height: 32px; }

@keyframes skeleton-loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

.values-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.number-config {
  color: #909399;
  font-size: 13px;
}

.text-muted {
  color: #c0c4cc;
}

/* 封面选择器样式 */
.cover-selector {
  display: flex;
  align-items: center;
  gap: 16px;
}

.cover-preview {
  flex-shrink: 0;
}

.cover-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.cover-id-text {
  color: #909399;
  font-size: 13px;
}

/* 套餐管理样式 */
.plan-management {
  padding: 0;
}

.plan-header {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

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

.args-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 分组树形选择器样式 */
.group-tree-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.group-tree-selector .el-input {
  flex: 1;
}

.group-tree-selector .clear-btn {
  flex-shrink: 0;
}

.group-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.group-name {
  font-weight: 500;
}

.expand-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  flex-shrink: 0;
  color: #909399;
}

.expand-icon:hover {
  color: #409eff;
}

.expand-icon .el-icon {
  transition: transform 0.2s;
}

.expand-icon .el-icon.is-expanded {
  transform: rotate(90deg);
}

.expand-placeholder {
  width: 20px;
  height: 20px;
  flex-shrink: 0;
}

/* 分组选择器弹窗内容 */
.group-selector-content {
  max-height: 450px;
  overflow: hidden;
}

/* 套餐表单弹窗样式 */
.plan-form-content {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 8px;
  margin-right: -8px;
}

/* 隐形滚动条样式 */
.plan-form-content::-webkit-scrollbar {
  width: 6px;
}

.plan-form-content::-webkit-scrollbar-track {
  background: transparent;
}

.plan-form-content::-webkit-scrollbar-thumb {
  background-color: transparent;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.plan-form-content:hover::-webkit-scrollbar-thumb {
  background-color: rgba(144, 147, 153, 0.3);
}

.plan-form-content::-webkit-scrollbar-thumb:hover {
  background-color: rgba(144, 147, 153, 0.5);
}

/* 参数配置选择器样式 */
.args-config-container {
  width: 100%;
}

.args-selector {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  background: #fafafa;
  max-height: 300px;
  overflow-y: auto;
}

.spec-item {
  display: flex;
  align-items: flex-start;
  padding: 10px 0;
  border-bottom: 1px dashed #e4e7ed;
  transition: opacity 0.2s;
}

.spec-item:last-child {
  border-bottom: none;
}

.spec-label {
  width: 100px;
  flex-shrink: 0;
  font-weight: 500;
  color: #606266;
  padding-top: 4px;
}

/* 参数选择下拉行 */
.args-select-row {
  margin-bottom: 12px;
}

/* 额外参数展示 */
.extra-args-display {
  margin-top: 8px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.spec-values {
  flex: 1;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.spec-values :deep(.el-radio-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.spec-values :deep(.el-radio-button__inner) {
  padding: 6px 12px;
}

.number-input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.number-range {
  color: #909399;
  font-size: 12px;
}

.matched-attr-info {
  margin-top: 6px;
}

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

/* 参数预览样式 */
.args-preview {
  padding: 0;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-list {
  max-height: 200px;
  overflow-y: auto;
}

.preview-item {
  display: flex;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.preview-item:last-child {
  border-bottom: none;
}

.preview-label {
  width: 120px;
  flex-shrink: 0;
  color: #606266;
  font-weight: 500;
}

.preview-value {
  color: #409eff;
  font-weight: 500;
}

.preview-value.not-selected {
  color: #c0c4cc;
  font-style: italic;
}

.json-preview {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  color: #606266;
  max-height: 200px;
  overflow: auto;
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
}

.unit-input-row { display: flex; align-items: center; gap: 6px; width: 100%; }
.unit-text { font-size: 13px; color: #606266; flex-shrink: 0; white-space: nowrap; }
</style>

