<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="商品编号" prop="goodsSn">
          <el-input v-model="queryParams.goodsSn" placeholder="商品编号" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="queryParams.goodsName" placeholder="商品名称" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="全部" clearable filterable style="width: 200px">
            <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.label" :value="item.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-tabs v-model="statusTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="未上架" name="0" />
        <el-tab-pane label="待审核" name="1" />
        <el-tab-pane label="出售中" name="2" />
        <el-tab-pane label="审核失败" name="3" />
        <el-tab-pane label="已下架" name="4" />
      </el-tabs>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['agri:seller:goods:add']">添加商品</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-upload2" size="mini" :disabled="!canBatchSubmit" @click="handleBatchSubmit" v-hasPermi="['agri:seller:goods:edit']">批量提交上架</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-bottom" size="mini" :disabled="!canBatchOffShelf" @click="handleBatchOffShelf" v-hasPermi="['agri:seller:goods:offshelf']">批量下架</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="!canBatchDelete" @click="handleBatchDelete" v-hasPermi="['agri:seller:goods:remove']">批量删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品编号" align="center" prop="goodsSn" width="140" />
        <el-table-column label="主图" align="center" width="80">
          <template slot-scope="scope">
            <image-preview :src="scope.row.mainPic" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="goodsName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column label="售价" align="center" prop="salePrice" width="90" />
        <el-table-column label="库存" align="center" prop="stock" width="70" />
        <el-table-column label="销量" align="center" prop="salesCount" width="70" />
        <el-table-column label="商品分类" align="center" prop="categoryPath" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="店铺分类" align="center" prop="shopCategoryName" min-width="110" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.shopCategoryName || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="goodsStatus" width="90">
          <template slot-scope="scope">
            <el-tag size="small" :type="goodsStatusTag(scope.row.goodsStatus)">{{ goodsStatusLabel(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="240" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['agri:seller:goods:query']">详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:seller:goods:edit']">编辑</el-button>
            <el-button v-if="canRowSubmit(scope.row)" size="mini" type="text" icon="el-icon-upload2" @click="handleRowSubmit(scope.row)" v-hasPermi="['agri:seller:goods:edit']">提交上架</el-button>
            <el-button v-if="scope.row.goodsStatus === '2'" size="mini" type="text" icon="el-icon-bottom" @click="handleRowOffShelf(scope.row)" v-hasPermi="['agri:seller:goods:offshelf']">下架</el-button>
            <el-button v-if="canRowDelete(scope.row)" size="mini" type="text" icon="el-icon-delete" @click="handleRowDelete(scope.row)" v-hasPermi="['agri:seller:goods:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 详情抽屉 -->
    <seller-goods-detail
      :visible.sync="detailOpen"
      :goods-id="currentGoodsId"
      @edit="handleUpdateFromDetail"
      @success="handleSuccess"
    />

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="formTitle" :visible.sync="formOpen" width="780px" append-to-body @close="cancelForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" class="goods-form">
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择平台二级分类" filterable style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.label" :value="item.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="店铺商品分类" prop="shopCategoryId">
          <el-select v-model="form.shopCategoryId" placeholder="选填，本店二级分类" clearable filterable style="width: 100%">
            <el-option v-for="item in shopCategoryOptions" :key="item.shopCategoryId" :label="item.label" :value="item.shopCategoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="属性模版" prop="attrTemplateId">
          <el-select
            v-model="form.attrTemplateId"
            placeholder="选填，选用后预填属性/规格"
            clearable
            filterable
            style="width: 100%"
            @change="handleAttrTemplateChange"
          >
            <el-option
              v-for="item in attrTemplateOptions"
              :key="item.templateId"
              :label="item.templateName + (item.nameList ? '（' + item.nameList + '）' : '')"
              :value="item.templateId"
            />
          </el-select>
        </el-form-item>

        <div class="section-title">属性</div>
        <div v-for="(item, index) in form.attributes" :key="'attr-' + index" class="item-block">
          <div class="item-head">
            <span class="item-label">属性名：</span>
            <el-input v-model="item.itemName" placeholder="属性项名称" maxlength="64" class="item-name-input" />
            <el-button type="text" icon="el-icon-delete" class="item-remove" @click="removeAttributeItem(index)">删除</el-button>
          </div>
          <div class="value-row">
            <span class="item-label">属性值：</span>
            <div class="value-list">
              <div v-for="(val, vIndex) in item.values" :key="'attr-val-' + index + '-' + vIndex" class="value-item">
                <el-input v-model="item.values[vIndex]" placeholder="属性值" maxlength="128" size="small" />
                <el-button v-if="item.values.length > 1" type="text" icon="el-icon-close" @click="removeAttributeValue(index, vIndex)" />
              </div>
              <el-button type="text" icon="el-icon-plus" @click="addAttributeValue(index)">增加属性值</el-button>
            </div>
          </div>
        </div>
        <el-button plain icon="el-icon-plus" class="add-item-btn" @click="addAttributeItem">添加属性项</el-button>

        <div class="section-title">规格</div>
        <div v-for="(item, index) in form.specs" :key="'spec-' + index" class="item-block">
          <div class="item-head">
            <span class="item-label">规格名：</span>
            <el-input v-model="item.itemName" placeholder="规格项名称" maxlength="64" class="item-name-input" />
            <el-button type="text" icon="el-icon-delete" class="item-remove" @click="removeSpecItem(index)">删除</el-button>
          </div>
          <div class="value-row">
            <span class="item-label">规格值：</span>
            <div class="value-list">
              <div v-for="(val, vIndex) in item.values" :key="'spec-val-' + index + '-' + vIndex" class="value-item">
                <el-input v-model="item.values[vIndex]" placeholder="规格值" maxlength="128" size="small" />
                <el-button v-if="item.values.length > 1" type="text" icon="el-icon-close" @click="removeSpecValue(index, vIndex)" />
              </div>
              <el-button type="text" icon="el-icon-plus" @click="addSpecValue(index)">增加规格值</el-button>
            </div>
          </div>
        </div>
        <el-button plain icon="el-icon-plus" class="add-item-btn" @click="addSpecItem">添加规格项</el-button>

        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" maxlength="200" />
        </el-form-item>
        <el-form-item label="商品主图" prop="mainPic">
          <image-upload v-model="form.mainPic" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
        </el-form-item>
        <el-form-item label="商品副图">
          <image-upload
            :key="'subpics-' + (form.goodsId || 'new')"
            v-model="form.subPics"
            :limit="10"
            :file-size="5"
            :file-type="['png', 'jpg', 'jpeg']"
          />
          <div class="form-tip">选填，最多 10 张，不含主图</div>
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="销售价" prop="salePrice">
              <el-input-number v-model="form.salePrice" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="form.stock"
                :min="0"
                :precision="0"
                :disabled="!!form.goodsId"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="配送运费" prop="freightType">
          <el-radio-group v-model="form.freightType" @change="handleFreightTypeChange">
            <el-radio label="1">固定运费</el-radio>
            <el-radio label="2">运费模版</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.freightType === '1'" label="固定金额" prop="fixedFreightAmount">
          <el-input-number v-model="form.fixedFreightAmount" :min="0" :precision="2" controls-position="right" style="width: 200px" />
        </el-form-item>
        <el-form-item v-if="form.freightType === '2'" label="运费模版" prop="freightTemplateId">
          <el-select v-model="form.freightTemplateId" placeholder="请选择运费模版" filterable clearable style="width: 100%">
            <el-option
              v-for="item in freightTemplateOptions"
              :key="item.templateId"
              :label="formatFreightTemplateLabel(item)"
              :value="item.templateId"
            />
          </el-select>
          <div v-if="!freightTemplateOptions.length" class="form-tip">暂无可用运费模版，请先在「运费模版」中创建</div>
        </el-form-item>
        <el-form-item label="商品详情" prop="detailContent">
          <editor v-model="form.detailContent" :min-height="200" />
        </el-form-item>
        <el-form-item label="服务说明">
          <el-checkbox-group v-model="form.serviceIds">
            <el-checkbox v-for="item in serviceOptions" :key="item.serviceId" :label="item.serviceId">{{ item.serviceName }}</el-checkbox>
          </el-checkbox-group>
          <div v-if="!serviceOptions.length" class="form-tip">暂无可用服务项</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSellerGoods,
  sellerGoodsCategoryOptions,
  sellerGoodsShopCategoryOptions,
  sellerGoodsServiceOptions,
  sellerAttrTemplateOptions,
  getSellerAttrTemplateDetail,
  sellerFreightTemplateOptions,
  getSellerFreightDefault,
  getSellerGoods,
  addSellerGoods,
  updateSellerGoods,
  submitSellerGoods,
  submitSellerGoodsBatch,
  offShelfSellerGoods,
  offShelfSellerGoodsBatch,
  delSellerGoods
} from "@/api/agri/seller/goods"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"
import SellerGoodsDetail from "./detail"

export default {
  name: "AgriSellerGoods",
  components: { SellerGoodsDetail },
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      goodsList: [],
      selection: [],
      detailOpen: false,
      currentGoodsId: null,
      formOpen: false,
      formTitle: "",
      statusTab: "all",
      categoryOptions: [],
      shopCategoryOptions: [],
      attrTemplateOptions: [],
      freightTemplateOptions: [],
      serviceOptions: [],
      defaultServiceIds: [],
      prevAttrTemplateId: undefined,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsSn: undefined,
        goodsName: undefined,
        categoryId: undefined,
        goodsStatusQuery: undefined
      },
      form: {},
      rules: {
        categoryId: [{ required: true, message: "请选择商品分类", trigger: "change" }],
        goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        mainPic: [{ required: true, message: "请上传商品主图", trigger: "change" }],
        salePrice: [{ required: true, message: "请输入销售价", trigger: "blur" }],
        stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
        freightType: [{ required: true, message: "请选择配送运费方式", trigger: "change" }],
        fixedFreightAmount: [{
          validator: (rule, value, callback) => {
            if (this.form.freightType !== "1") {
              callback()
              return
            }
            if (value == null || value === "") {
              callback(new Error("请输入固定运费"))
              return
            }
            if (Number(value) < 0) {
              callback(new Error("固定运费不能小于 0"))
              return
            }
            callback()
          },
          trigger: "blur"
        }],
        freightTemplateId: [{
          validator: (rule, value, callback) => {
            if (this.form.freightType !== "2") {
              callback()
              return
            }
            if (!value) {
              callback(new Error("请选择运费模版"))
              return
            }
            callback()
          },
          trigger: "change"
        }],
        detailContent: [{ required: true, message: "请填写商品详情", trigger: "blur" }]
      }
    }
  },
  computed: {
    /** 所选是否均可提交上架 */
    canBatchSubmit() {
      return this.selection.length > 0 && this.selection.every(item => this.canRowSubmit(item))
    },
    /** 所选是否均可下架 */
    canBatchOffShelf() {
      return this.selection.length > 0 && this.selection.every(item => item.goodsStatus === "2")
    },
    /** 所选是否均可删除 */
    canBatchDelete() {
      return this.selection.length > 0 && this.selection.every(item => this.canRowDelete(item))
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    /** 初始化：店铺上下文 + 下拉 + 列表 */
    initPage() {
      this.loadShopContext().then(() => {
        this.loadFormOptions()
        this.getList()
      }).catch(() => {
        this.loadFormOptions()
        this.getList()
      })
    },
    /** 写入 X-Shop-Id 缓存 */
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    /** 加载发品/检索用下拉 */
    loadFormOptions() {
      sellerGoodsCategoryOptions().then(response => {
        this.categoryOptions = response.data || []
      }).catch(() => {})
      sellerGoodsShopCategoryOptions(false).then(response => {
        this.shopCategoryOptions = response.data || []
      }).catch(() => {})
      sellerGoodsServiceOptions().then(response => {
        const data = response.data || {}
        this.serviceOptions = data.all || []
        const defaults = data.defaultShow || []
        this.defaultServiceIds = defaults.map(item => item.serviceId)
      }).catch(() => {})
      sellerAttrTemplateOptions().then(response => {
        this.attrTemplateOptions = response.data || []
      }).catch(() => {})
      sellerFreightTemplateOptions().then(response => {
        this.freightTemplateOptions = response.data || []
      }).catch(() => {})
    },
    /** 运费模版下拉展示文案 */
    formatFreightTemplateLabel(item) {
      let name = item.templateName || "—"
      if (item.isDefault === "1") {
        name += "（默认）"
      }
      if (item.freeFlag === "1") {
        name += " · 包邮"
      }
      return name
    },
    /** 新建时预填默认运费模版 */
    applyFreightDefault() {
      getSellerFreightDefault().then(response => {
        const data = response.data
        if (data && data.freightType === "2" && data.freightTemplateId) {
          this.form.freightType = "2"
          this.form.freightTemplateId = data.freightTemplateId
        } else {
          this.form.freightType = "1"
          this.form.fixedFreightAmount = 0
        }
      }).catch(() => {
        this.form.freightType = "1"
        this.form.fixedFreightAmount = 0
      })
    },
    /** 切换配送运费方式 */
    handleFreightTypeChange(val) {
      if (val === "1") {
        this.form.freightTemplateId = undefined
        if (this.form.fixedFreightAmount == null) {
          this.form.fixedFreightAmount = 0
        }
      } else if (val === "2") {
        this.form.fixedFreightAmount = undefined
        if (!this.form.freightTemplateId) {
          const defaultOpt = this.freightTemplateOptions.find(item => item.isDefault === "1")
          if (defaultOpt) {
            this.form.freightTemplateId = defaultOpt.templateId
          }
        }
      }
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate(["fixedFreightAmount", "freightTemplateId"])
        }
      })
    },
    /** 副图归一化为 URL 数组 */
    normalizeSubPics(val) {
      if (!val || (Array.isArray(val) && !val.length)) {
        return []
      }
      if (Array.isArray(val)) {
        return val.filter(item => item && String(item).trim())
      }
      return String(val).split(",").map(item => item.trim()).filter(Boolean)
    },
    /** 副图绑定 image-upload（多图组件使用逗号分隔字符串） */
    joinSubPicsForUpload(subPics) {
      const list = this.normalizeSubPics(subPics)
      return list.length ? list.join(",") : ""
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true
      listSellerGoods(this.queryParams).then(response => {
        this.goodsList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    goodsStatusLabel(row) {
      if (row.goodsStatusLabel) {
        return row.goodsStatusLabel
      }
      const map = { "0": "未上架", "1": "待审核", "2": "出售中", "3": "审核失败", "4": "已下架" }
      return map[row.goodsStatus] || "—"
    },
    goodsStatusTag(status) {
      const map = { "0": "", "1": "warning", "2": "success", "3": "danger", "4": "info" }
      return map[status] || "info"
    },
    /** 是否可提交上架 */
    canRowSubmit(row) {
      return row.goodsStatus === "0" || row.goodsStatus === "3" || row.goodsStatus === "4"
    },
    /** 是否可删除 */
    canRowDelete(row) {
      return this.canRowSubmit(row)
    },
    handleTabClick() {
      this.queryParams.goodsStatusQuery = this.statusTab === "all" ? undefined : this.statusTab
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.statusTab = "all"
      this.queryParams.goodsStatusQuery = undefined
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    handleDetail(row) {
      this.currentGoodsId = row.goodsId
      this.detailOpen = true
    },
    /** 创建空属性/规格项 */
    createEmptyItem() {
      return { itemName: "", values: [""] }
    },
    /** 详情项转为表单结构 */
    mapDetailItems(items) {
      const list = items || []
      if (!list.length) {
        return []
      }
      return list.map(item => ({
        itemName: item.itemName || "",
        values: (item.values && item.values.length) ? [...item.values] : [""]
      }))
    },
    /** 是否存在已填写的属性/规格 */
    hasAttrSpecContent() {
      const check = (items) => {
        return (items || []).some(item => {
          const name = (item.itemName || "").trim()
          const hasValue = (item.values || []).some(val => (val || "").trim())
          return name || hasValue
        })
      }
      return check(this.form.attributes) || check(this.form.specs)
    },
    /** 选用属性模版变更 */
    handleAttrTemplateChange(templateId) {
      const prevId = this.prevAttrTemplateId
      const applyTemplate = () => {
        if (!templateId) {
          this.prevAttrTemplateId = undefined
          return
        }
        getSellerAttrTemplateDetail(templateId).then(response => {
          const data = response.data || {}
          this.form.attributes = this.mapDetailItems(data.attributes)
          this.form.specs = this.mapDetailItems(data.specs)
          this.prevAttrTemplateId = templateId
        }).catch(() => {
          this.form.attrTemplateId = prevId
        })
      }
      if (templateId && this.hasAttrSpecContent() && templateId !== prevId) {
        this.$modal.confirm("切换模版将覆盖当前属性/规格内容，是否继续？").then(() => {
          applyTemplate()
        }).catch(() => {
          this.form.attrTemplateId = prevId
        })
      } else {
        applyTemplate()
      }
    },
    /** 属性/规格项增删 */
    addAttributeItem() {
      this.form.attributes.push(this.createEmptyItem())
    },
    removeAttributeItem(index) {
      this.form.attributes.splice(index, 1)
    },
    addAttributeValue(index) {
      this.form.attributes[index].values.push("")
    },
    removeAttributeValue(itemIndex, valueIndex) {
      this.form.attributes[itemIndex].values.splice(valueIndex, 1)
    },
    addSpecItem() {
      this.form.specs.push(this.createEmptyItem())
    },
    removeSpecItem(index) {
      this.form.specs.splice(index, 1)
    },
    addSpecValue(index) {
      this.form.specs[index].values.push("")
    },
    removeSpecValue(itemIndex, valueIndex) {
      this.form.specs[itemIndex].values.splice(valueIndex, 1)
    },
    /** 规范化属性/规格提交体 */
    normalizeAttrItems(items) {
      const result = []
      ;(items || []).forEach(item => {
        const name = (item.itemName || "").trim()
        if (!name) {
          return
        }
        const values = (item.values || []).map(val => (val || "").trim()).filter(val => val)
        result.push({ itemName: name, values: values })
      })
      return result
    },
    /** 校验属性/规格（有内容时） */
    buildAttrSpecPayload() {
      if (this.hasInvalidPartialItems(this.form.attributes) || this.hasInvalidPartialItems(this.form.specs)) {
        this.$modal.msgWarning("请填写属性项/规格项名称")
        return false
      }
      const attributes = this.normalizeAttrItems(this.form.attributes)
      const specs = this.normalizeAttrItems(this.form.specs)
      const attrNames = attributes.map(item => item.itemName)
      const specNames = specs.map(item => item.itemName)
      if (attrNames.length && new Set(attrNames).size !== attrNames.length) {
        this.$modal.msgWarning("属性项名称不可重复")
        return false
      }
      if (specNames.length && new Set(specNames).size !== specNames.length) {
        this.$modal.msgWarning("规格项名称不可重复")
        return false
      }
      const cross = [...attrNames, ...specNames]
      if (cross.length && new Set(cross).size !== cross.length) {
        this.$modal.msgWarning("属性项与规格项名称不可相同")
        return false
      }
      for (let i = 0; i < attributes.length; i++) {
        if (!this.validateAttrItemValues(attributes[i], "属性")) {
          return false
        }
      }
      for (let i = 0; i < specs.length; i++) {
        if (!this.validateAttrItemValues(specs[i], "规格")) {
          return false
        }
      }
      return { attributes: attributes, specs: specs }
    },
    hasInvalidPartialItems(items) {
      return (items || []).some(item => {
        const name = (item.itemName || "").trim()
        const hasValue = (item.values || []).some(val => (val || "").trim())
        return !name && hasValue
      })
    },
    validateAttrItemValues(item, label) {
      if (!item.values || !item.values.length) {
        this.$modal.msgWarning("请为每项至少添加一个" + label + "值")
        return false
      }
      if (new Set(item.values).size !== item.values.length) {
        this.$modal.msgWarning("同一项下" + label + "值不可重复")
        return false
      }
      return true
    },
    /** 重置表单 */
    resetFormData() {
      this.form = {
        goodsId: undefined,
        categoryId: undefined,
        shopCategoryId: undefined,
        attrTemplateId: undefined,
        attributes: [],
        specs: [],
        goodsName: undefined,
        mainPic: undefined,
        subPics: "",
        detailContent: undefined,
        salePrice: undefined,
        stock: undefined,
        freightType: "1",
        fixedFreightAmount: 0,
        freightTemplateId: undefined,
        serviceIds: [...this.defaultServiceIds]
      }
      this.prevAttrTemplateId = undefined
      this.resetForm("form")
    },
    /** 打开添加商品 */
    handleAdd() {
      this.resetFormData()
      this.formOpen = true
      this.formTitle = "添加商品"
      this.applyFreightDefault()
    },
    /** 打开编辑商品 */
    handleUpdate(row) {
      getSellerGoods(row.goodsId).then(response => {
        const data = response.data || {}
        this.form = {
          goodsId: data.goodsId,
          categoryId: data.categoryId,
          shopCategoryId: data.shopCategoryId,
          attrTemplateId: data.attrTemplateId,
          attributes: this.mapDetailItems(data.attributes),
          specs: this.mapDetailItems(data.specs),
          goodsName: data.goodsName,
          mainPic: data.mainPic || "",
          subPics: this.joinSubPicsForUpload(data.subPics),
          detailContent: data.detailContent,
          salePrice: data.salePrice,
          stock: data.stock,
          freightType: data.freightType || "1",
          fixedFreightAmount: data.freightType === "1" ? data.fixedFreightAmount : undefined,
          freightTemplateId: data.freightType === "2" ? data.freightTemplateId : undefined,
          serviceIds: (data.services || []).map(item => item.serviceId)
        }
        this.prevAttrTemplateId = data.attrTemplateId
        this.formTitle = "编辑商品"
        this.formOpen = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      }).catch(() => {})
    },
    /** 详情抽屉跳转编辑 */
    handleUpdateFromDetail(detail) {
      this.handleUpdate({ goodsId: detail.goodsId })
    },
    cancelForm() {
      this.formOpen = false
      this.resetFormData()
    },
    /** 保存商品 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const attrPayload = this.buildAttrSpecPayload()
        if (attrPayload === false) {
          return
        }
        const payload = { ...this.form, ...attrPayload }
        payload.subPics = this.normalizeSubPics(payload.subPics)
        if (payload.freightType === "1") {
          payload.freightTemplateId = null
        } else {
          payload.fixedFreightAmount = null
        }
        if (!payload.shopCategoryId) {
          payload.shopCategoryId = null
        }
        if (!payload.attrTemplateId) {
          payload.attrTemplateId = null
        }
        const submitFn = payload.goodsId != null ? updateSellerGoods : addSellerGoods
        submitFn(payload).then(() => {
          this.$modal.msgSuccess(payload.goodsId != null ? "修改成功" : "添加成功，商品状态为未上架")
          this.formOpen = false
          this.getList()
        })
      })
    },
    /** 单条提交上架 */
    handleRowSubmit(row) {
      this.$modal.confirm("确认提交上架商品「" + row.goodsName + "」？").then(() => {
        return submitSellerGoods(row.goodsId)
      }).then(response => {
        const data = response.data || {}
        const label = data.goodsStatusLabel || "操作成功"
        this.$modal.msgSuccess("提交成功，当前状态：" + label)
        this.handleSuccess()
      }).catch(() => {})
    },
    /** 批量提交上架 */
    handleBatchSubmit() {
      const ids = this.selection.map(item => item.goodsId)
      this.$modal.confirm("确认批量提交上架所选 " + ids.length + " 件商品？").then(() => {
        return submitSellerGoodsBatch({ goodsIds: ids })
      }).then(() => {
        this.$modal.msgSuccess("批量提交成功")
        this.handleSuccess()
      }).catch(() => {})
    },
    /** 单条下架 */
    handleRowOffShelf(row) {
      this.$modal.confirm("下架后 C 端不可购买，是否继续？").then(() => {
        return offShelfSellerGoods(row.goodsId)
      }).then(() => {
        this.$modal.msgSuccess("下架成功")
        this.handleSuccess()
      }).catch(() => {})
    },
    /** 批量下架 */
    handleBatchOffShelf() {
      const ids = this.selection.map(item => item.goodsId)
      this.$modal.confirm("确认批量下架所选 " + ids.length + " 件商品？").then(() => {
        return offShelfSellerGoodsBatch({ goodsIds: ids })
      }).then(() => {
        this.$modal.msgSuccess("批量下架成功")
        this.handleSuccess()
      }).catch(() => {})
    },
    /** 单条删除 */
    handleRowDelete(row) {
      this.$modal.confirm("确认删除商品「" + row.goodsName + "」？").then(() => {
        return delSellerGoods(row.goodsId)
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.handleSuccess()
      }).catch(() => {})
    },
    /** 批量删除 */
    handleBatchDelete() {
      const ids = this.selection.map(item => item.goodsId)
      this.$modal.confirm("确认批量删除所选 " + ids.length + " 件商品？").then(() => {
        return delSellerGoods(ids.join(","))
      }).then(() => {
        this.$modal.msgSuccess("批量删除成功")
        this.handleSuccess()
      }).catch(() => {})
    },
    handleSuccess() {
      this.getList()
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
.form-tip {
  color: #909399;
  font-size: 13px;
}
.goods-form {
  max-height: 65vh;
  overflow-y: auto;
  padding-right: 8px;
}
.section-title {
  margin: 12px 0 8px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}
.item-block {
  margin-bottom: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}
.item-head,
.value-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
}
.item-label {
  flex-shrink: 0;
  width: 56px;
  line-height: 32px;
  color: #606266;
  font-size: 13px;
}
.item-name-input {
  flex: 1;
  max-width: 280px;
}
.item-remove {
  margin-left: 8px;
  color: #F56C6C;
}
.value-list {
  flex: 1;
}
.value-item {
  display: inline-flex;
  align-items: center;
  margin: 0 8px 8px 0;
  width: 140px;
}
.add-item-btn {
  width: 100%;
  margin-bottom: 12px;
}
</style>
