<template>
  <div class="app-container">
    <el-tabs v-model="goodsType" @tab-click="onChangeGoodsType">
      <el-tab-pane v-for="dict in dict.type.goods_type" :label="dict.label" :name="dict.value"></el-tab-pane>
    </el-tabs>
    <!-- 查询 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item prop="goodsName">
          <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item prop="brandId">
          <el-select v-model="queryParams.brandId" placeholder="请选择商品品牌" clearable>
            <el-option v-for="brand in brandList" :key="brand.id" :label="brand.brandName" :value="brand.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="goodsCategoryId">
          <el-select v-model="queryParams.goodsCategoryId" placeholder="请选择商品分类" clearable>
            <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="goodsCode">
          <el-input v-model="queryParams.goodsCode" placeholder="请输入商品编号" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['goods:commonGoods:add']"
          v-if="userInfoVO.userType == '00'">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 列表 -->
    <Page uri="/mapi/core/goods/list" :request-params="queryParams" ref="pagination">
      <el-table-column label="商品ID" align="center" prop="id" width="100" />
      <el-table-column label="商品图片" align="left" width="120">
        <template slot-scope="scope">
          <div class="goods-info">
            <el-image style="width: 90px; height: 90px; margin-right: 10px;" :src="scope.row.goodsImg" :preview-src-list="[scope.row.goodsImg]">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品编码" align="center" prop="goodsCode" width="120" />
      <el-table-column label="商品名称" align="center" prop="goodsName" min-width="180" />
      <el-table-column label="商品品牌" align="center" prop="brandName" width="150" />
      <el-table-column label="商品分类" align="center" prop="categoryName" width="150">
        <template slot-scope="scope">
          <el-tag size="mini" type="info" v-if="scope.row.goodsCategoryId" style="margin-left: 5px;">
            <span v-if="scope.row.goodsCategoryId == item.id" v-for="item in categoryList" :key="item.id">
              {{item.categoryName}}
            </span>
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="价格/库存" align="center" width="200">
                <template slot-scope="scope">
                    <div v-if="scope.row.skuList && scope.row.skuList.length > 0">
                        <div>销售价：￥{{getMinMaxPrice(scope.row.skuList, 'salePrice')}}</div>
                        <div>批发价：￥{{getMinMaxPrice(scope.row.skuList, 'purchasePrice')}}</div>
                        <div>总库存：{{getTotalStock(scope.row.skuList)}}</div>
                    </div>
                    <div v-else>
                        <div>暂无价格信息</div>
                    </div>
                </template>
            </el-table-column> -->

      <el-table-column label="规格" align="center" width="120">
        <template slot-scope="scope">
          <el-button type="text" @click="openSkuDialog(scope.row)">
            <span>{{scope.row.goodsItemNum}}种规格</span>
            <i class="el-icon-arrow-right"></i>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="支付方式" align="center" width="150">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.isBalancePay === 'Y'" size="mini" type="success">支持余额</el-tag>
            <el-tag v-else size="mini" type="info">不支持余额</el-tag>
          </div>
          <div style="margin-top: 5px;">
            <el-tag v-if="scope.row.isSell === 'Y'" size="mini" type="warning">促销标识</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" width="120">
        <template slot-scope="scope">
          <div style="margin-top: 5px;">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)">
            </el-switch>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="排序" align="center" width="120">
        <template slot-scope="scope">
          <div>排序：{{scope.row.sort}}</div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150"></el-table-column>

      <el-table-column label="操作" align="center" width="200" fixed="right" v-if="userInfoVO.userType == '00'">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['goods:commonGoods:edit']"
            v-if="userInfoVO.userType == '00'">修改</el-button>
          <el-button type="text" icon="el-icon-view" v-if="goodsType != 1" @click="gotoComment(scope.row)">评论</el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['goods:commonGoods:remove']"
            v-if="userInfoVO.userType == '00'">删除</el-button>
        </template>
      </el-table-column>
    </Page>
    <!-- 分页 -->
    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeTab">
          <!-- 基本信息 tab -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="商品名称" prop="goodsName">
                  <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品编码" prop="goodsCode">
                  <el-input v-model="form.goodsCode" placeholder="请输入商品编码" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="品牌" prop="brandId">
                  <el-select v-model="form.brandId" placeholder="请选择品牌" clearable>
                    <el-option v-for="brand in brandList" :key="brand.id" :label="brand.brandName" :value="brand.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品分类" prop="goodsCategoryId">
                  <el-select v-model="form.goodsCategoryId" placeholder="请选择商品分类" clearable>
                    <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName" :value="category.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="商品图片" prop="goodsImg">
              <image-upload v-model="form.goodsImg" />
            </el-form-item>

            <el-form-item label="商品图片集" prop="goodsImgs">
              <image-upload v-model="form.goodsImgs" :limit="limit" />
            </el-form-item>

            <el-form-item label="商品简介" prop="goodsSynopsis">
              <editor v-model="form.goodsSynopsis" :min-height="192" />
            </el-form-item>
          </el-tab-pane>

          <!-- 规格设置 tab -->
          <el-tab-pane label="规格设置" name="sku">
            <el-form-item label="规格类型">
              <el-radio-group v-model="form.skuType" @change="handleSkuTypeChange">
                <el-radio :label="0">单规格</el-radio>
                <el-radio :label="1">多规格</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 单规格设置 -->
            <template v-if="form.skuType === 0">
              <el-form-item label="销售价格" prop="singleSkuPrice">
                <el-input-number v-model="form.singleSkuPrice" :precision="2" :step="0.1" :min="0" />
              </el-form-item>
              <el-form-item label="成本价格" prop="singleSkuCostPrice">
                <el-input-number v-model="form.singleSkuCostPrice" :precision="2" :step="0.1" :min="0" />
              </el-form-item>
              <el-form-item label="采购价格" prop="singleSkuPurchasePrice">
                <el-input-number v-model="form.singleSkuPurchasePrice" :precision="2" :step="0.1" :min="0" />
              </el-form-item>
              <el-form-item label="库存数量" prop="singleSkuStock">
                <el-input-number v-model="form.singleSkuStock" :min="0" :step="1" />
              </el-form-item>
            </template>

            <!-- 多规格设置 -->
            <template v-if="form.skuType === 1">
              <!-- 规格项设置 -->
              <div class="spec-group" v-for="(spec, index) in form.specList" :key="index" v-if="form.id==null">
                <el-row :gutter="10">
                  <el-col :span="8">
                    <el-form-item :label="'规格项' + (index + 1)">
                      <el-input v-model="spec.name" placeholder="如: 颜色、尺码" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="14">
                    <el-form-item label="规格值">
                      <el-tag :key="tag" v-for="tag in spec.specValues" closable :disable-transitions="false"
                        @close="handleRemoveSpecValue(spec.specValues, tag)">
                        {{tag}}
                      </el-tag>
                      <el-input class="input-new-tag" v-if="spec.inputVisible" v-model="spec.inputValue" ref="tagInput" size="small"
                        @keyup.enter.native="handleInputConfirm(spec, index)" @blur="handleInputConfirm(spec, index)">
                      </el-input>
                      <el-button v-else class="button-new-tag" size="small" @click="showInput(spec, index)">
                        + 添加规格值
                      </el-button>
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-button type="text" @click="removeSpec(index)" icon="el-icon-delete">删除</el-button>
                  </el-col>
                </el-row>
              </div>

              <el-button type="primary" plain @click="addSpec" v-if="form.id==null">添加规格项</el-button>

              <!-- 规格组合列表 -->
              <el-table :data="form.skuList" border style="margin-top: 20px">
                <el-table-column v-for="(spec, index) in form.specList" :key="index" :label="spec.name" align="center">
                  <template slot-scope="scope">
                    {{scope.row.specValLists[index]}}
                  </template>
                </el-table-column>
                <el-table-column label="规格编码" align="center" width="150">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.skuCode" placeholder="请输入规格编码" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="销售价格" align="center" width="150">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.salePrice" :precision="2" :step="0.1" :min="0" controls-position="right" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="成本价格" align="center" width="150">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.costPrice" :precision="2" :step="0.1" :min="0" controls-position="right" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="采购价格" align="center" width="150">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.purchasePrice" :precision="2" :step="0.1" :min="0" controls-position="right" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="库存" align="center" width="150">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.stock" :min="0" :step="1" controls-position="right" size="mini" />
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-tab-pane>

          <!-- 其他设置 tab -->
          <el-tab-pane label="其他设置" name="other">
            <el-form-item label="促销标识" prop="isSell">
              <el-radio-group v-model="form.isSell">
                <el-radio-button v-for="dict in dict.type.sys_yes_no" :label="dict.value" :key="dict.code">
                  {{dict.label}}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="余额支付" prop="isBalancePay">
              <el-radio-group v-model="form.isBalancePay">
                <el-radio-button v-for="dict in dict.type.sys_yes_no" :label="dict.value" :key="dict.code">
                  {{dict.label}}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="显示顺序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :step="1" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加规格弹窗组件 -->
    <goods-sku-dialog ref="skuDialog"></goods-sku-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods, updateGoodsStatus } from '@/api/core/goods'
import { listCategory } from '@/api/core/category'
import { listBrand } from '@/api/core/brand'
import { status } from 'nprogress'
import GoodsSkuDialog from '@/components/GoodsSkuDialog'

export default {
  name: 'appGoods',
  components: {
    GoodsSkuDialog
  },
  dicts: ['goods_type', 'sys_yes_no'],
  data() {
    return {
      userInfoVO: null,
      uploadAction: `${process.env.VUE_APP_BASE_API}` + '/common/uploadOSS',
      imgsList: [],
      fileSize: 3,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      goodsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        goodsName: null,
        goodsType: null,
        status: null,
        goodsCategoryId: null,
        goodsCode: null
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 9999,
        status: '0',
        goodsType: null
      },
      // 表单参数
      form: {
        id: null,
        goodsName: null,
        goodsCategoryId: null,
        goodsSynopsis: null,
        brandId: null,
        goodsImg: null,
        goodsImgs: [],
        goodsCode: null,
        isSell: 'N',
        isCashPay: 'Y',
        cashMoney: null,
        isBalancePay: 'Y',
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        remark: null,
        skuType: 0,
        status: '0',
        specList: [],
        skuList: [],
        sort: '0',
        singleSkuPrice: 0,
        singleSkuCostPrice: 0,
        singleSkuPurchasePrice: 0,
        singleSkuStock: 0
      },
      // 表单校验
      rules: {
        goodsName: [
          {
            required: true,
            message: '商品名称不能为空',
            trigger: 'blur'
          }
        ],

        goodsCode: [
          {
            required: true,
            message: '商品编号不能为空',
            trigger: 'blur'
          }
        ],
        goodsSynopsis: [
          {
            required: true,
            message: '商品简介不能为空',
            trigger: 'blur'
          }
        ],
        goodsImg: [
          {
            required: true,
            message: '商品头图不能为空',
            trigger: 'blur'
          }
        ],
        goodsImgs: [
          {
            required: true,
            message: '商品图片集不能为空',
            trigger: 'blur'
          }
        ],
        isBalancePay: [
          {
            required: true,
            message: '是否余额支付不能为空',
            trigger: 'blur'
          }
        ],
        isCashPay: [
          {
            required: true,
            message: '是否现金支付不能为空',
            trigger: 'blur'
          }
        ],
        isSell: [
          {
            required: true,
            message: '是否促销不能为空',
            trigger: 'blur'
          }
        ],
        cashMoney: [
          {
            required: true,
            message: '现金金额不能为空',
            trigger: 'blur'
          }
        ]
      },
      categoryList: [],
      brandList: [],
      goodsType: '',
      limit: 9,
      activeTab: 'basic',
      skuType: 0
    }
  },
  created() {
    this.handleUser()
    this.goodsType = this.getUrlParam('goodsType')
    this.form.goodsType = this.goodsType
    this.getList()
    this.getCategoryList()
    this.getBrandList()
  },
  methods: {
    handleUser() {
      this.userInfoVO = this.getUserInfo()
    },
    onChangeGoodsType() {
      this.queryParams.goodsType = this.goodsType
      this.handleQuery()
      // 重新获取品牌和分类列表
      this.getBrandList()
      this.getCategoryList()
    },
    getBrandList() {
      listBrand({ ...this.queryParams2, goodsType: this.goodsType }).then(response => {
        this.brandList = response.rows || []
      })
    },
    getCategoryList() {
      listCategory({ ...this.queryParams2, goodsType: this.goodsType }).then(response => {
        this.categoryList = response.rows || []
      })
    },
    /** 查询商品管理列表 */
    getList() {
      this.queryParams.goodsType = this.goodsType
      this.$nextTick(() => {
        this.$refs.pagination.handleSearch(true)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsType: this.goodsType,
        goodsName: null,
        goodsCategoryId: null,
        goodsSynopsis: null,
        brandId: null,
        goodsImg: null,
        goodsImgs: [],
        goodsCode: null,
        isSell: 'N',
        skuType: 0,
        isCashPay: 'Y',
        cashMoney: null,
        isBalancePay: 'Y',
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        remark: null,
        status: '0',
        sort: '0',
        specList: [],
        skuList: [],
        singleSkuPrice: 0,
        singleSkuCostPrice: 0,
        singleSkuPurchasePrice: 0,
        singleSkuStock: 0
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加商品管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.imgsList = []
      const id = row.id || this.ids
      getGoods(id).then((response) => {
        this.form = response.data
        this.form.brandId = Number(this.form.brandId)
        this.form.goodsCategoryId = Number(this.form.goodsCategoryId)
        if (this.form.goodsImgs != null && this.form.goodsImgs != '') {
          this.form.goodsImgs.split(',').forEach((item) => {
            const vo = {
              name: '',
              url: item
            }
            this.imgsList.push(vo)
          })
        }
        this.open = true
        this.title = '修改商品管理'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const formData = { ...this.form }

          // 处理SKU数据
          if (this.form.skuType === 0) {
            formData.skuList = [{
              specValLists: [],
              salePrice: this.form.singleSkuPrice,
              costPrice: this.form.singleSkuCostPrice,
              purchasePrice: this.form.singleSkuPurchasePrice,
              stock: this.form.singleSkuStock
            }]
          } else {
            formData.skuList = this.form.skuList
          }

          // 提交数据
          if (formData.id) {
            updateGoods(formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addGoods(formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除商品管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delGoods(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'commonGoods/commonGoods/export',
        {
          ...this.queryParams
        },
        `goods_${new Date().getTime()}.xlsx`
      )
    },
    checkClose(done) {
      this.$confirm('是否关闭表单，关闭后数据将丢失？')
        .then(function () {
          done()
        })
        .then(() => { })
        .catch(() => { })
    },
    handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用'
      this.$confirm('确认要' + text + '吗？')
        .then(function () {
          return updateGoodsStatus(row.id, row.status)
        })
        .then(() => {
          this.$modal.msgSuccess(text + '成功')
        })
        .catch(function () {
          row.status = row.status === '0' ? '1' : '0'
        })
    },
    /** 设置物料 */
    handleSkuUpdate(row) {
      this.openSkuDialog(row)
    },
    openSkuDialog(row) {
      this.$refs.skuDialog.show(row.id)
    },
    handleRemove(file, fileList) {
      console.log(fileList)
      this.imgsList = []
      fileList.forEach((item) => {
        const vo = {
          name: item.name,
          url: item.url
        }
        this.imgsList.push(vo)
        console.log(fileList)
      })
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      return true
    },
    handleUploadSuccessByImg(res, file) {
      // 获取富文本组件实例
      let quill = this.Quill
      // 如果上传成功
      if (res.code == 200) {
        // 获取光标所在位置
        this.form.goodsImg = res.data.src
        this.$forceUpdate()
      } else {
        this.$message.error('图片插入失败')
      }
    },
    handleUploadSuccessByImgs(res, file, fileList) {
      // 获取富文本组件实例
      let quill = this.Quill
      // 如果上传成功
      if (res.code == 200) {
        const vo = {
          name: '',
          url: res.data.src
        }
        this.imgsList.push(vo)
        this.$forceUpdate()
      } else {
        this.$message.error('图片插入失败')
      }
    },
    handleUploadError() {
      this.$message.error('图片插入失败')
    },
    handleExceed() {
      //提示最多只能上传9个
      this.$message.error('最多上传9个图片！')
    },
    gotoComment(row) {
      this.$router.push({ path: `/system/goodsComment/appGoodsComment?goodsType=${this.goodsType}&goodsId=${row.id}` })
    },
    handleSkuTypeChange(val) {
      if (val === 0) {
        this.form.specList = []
        this.form.skuList = []
      } else {
        // 如果已有规格数据，重新生成组合
        if (this.form.specList.length > 0) {
          this.generateSkuList()
        }
      }
    },
    addSpec() {
      if (!this.form.specList) {
        this.form.specList = []
      }
      this.form.specList.push({
        name: '',
        specValues: [],
        inputVisible: false,
        inputValue: ''
      })
    },
    removeSpec(index) {
      this.form.specList.splice(index, 1)
      this.$nextTick(() => {
        this.generateSkuList()
      })
    },
    handleRemoveSpecValue(values, tag) {
      values.splice(values.indexOf(tag), 1)
      this.$nextTick(() => {
        this.generateSkuList()
      })
    },
    showInput(spec, index) {
      // 先重置其他所有输入框的状态
      this.form.specList.forEach(item => {
        this.$set(item, 'inputVisible', false);
      });

      // 设置当前输入框可见
      this.$set(spec, 'inputVisible', true);

      // 强制更新视图
      this.$forceUpdate();

      // 等待 DOM 更新后设置焦点
      this.$nextTick(() => {
        if (this.$refs.tagInput && this.$refs.tagInput.length > 0) {
          const inputs = this.$refs.tagInput;
          // 找到最后一个输入框（应该是刚刚显示的那个）
          const input = Array.isArray(inputs) ? inputs[inputs.length - 1] : inputs;
          if (input && input.$el.querySelector('input')) {
            input.$el.querySelector('input').focus();
          }
        }
      });
    },
    handleInputConfirm(spec, index) {
      let inputValue = spec.inputValue
      if (inputValue && spec.specValues.indexOf(inputValue) === -1) {
        if (!spec.specValues) {
          spec.specValues = []
        }
        spec.specValues.push(inputValue)
        this.$nextTick(() => {
          this.generateSkuList()
        })
      }
      spec.inputVisible = false
      spec.inputValue = ''
    },
    generateSkuList() {
      const specs = this.form.specList
      if (specs.length === 0 || specs.some(spec => spec.specValues.length === 0)) {
        this.form.skuList = []
        return
      }

      // 获取所有规格值的组合
      const values = specs.map(spec => spec.specValues)
      const combinations = this.cartesianProduct(values)

      // 保存现有的价格和库存数据
      const existingSkus = this.form.skuList || []

      // 生成新的SKU列表，保留已存在的价格和库存
      this.form.skuList = combinations.map(specs => {
        // 查找是否存在相同规格的旧数据
        const existingSku = existingSkus.find(old =>
          JSON.stringify(old.specValLists) === JSON.stringify(specs)
        )

        return {
          specValLists: specs,
          skuCode: existingSku ? existingSku.skuCode : '',
          salePrice: existingSku ? existingSku.salePrice : 0,
          costPrice: existingSku ? existingSku.costPrice : 0,
          purchasePrice: existingSku ? existingSku.purchasePrice : 0,
          stock: existingSku ? existingSku.stock : 0
        }
      })
    },
    cartesianProduct(arrays) {
      return arrays.reduce((a, b) => {
        return a.map(x => {
          return b.map(y => {
            return Array.isArray(x) ? [...x, y] : [x, y]
          })
        }).flat()
      }, [[]])
    },
    /**
     * @description 添加规格值
     * @param {number} index 规格索引
     */
    addSpecValue(index) {
      // 确保规格值数组已初始化
      if (!this.form.specList[index].specValueList) {
        this.$set(this.form.specList[index], 'specValueList', [])
      }

      this.form.specList[index].specValueList.push({
        specValue: '',
        image: ''
      })
    },
    getMinMaxPrice(skuList, priceType) {
      if (!skuList || skuList.length === 0) return '0.00';
      const prices = skuList.map(sku => sku[priceType] || 0);
      const min = Math.min(...prices);
      const max = Math.max(...prices);
      return min === max ? min.toFixed(2) : `${min.toFixed(2)} ~ ${max.toFixed(2)}`;
    },

    getTotalStock(skuList) {
      if (!skuList || skuList.length === 0) return 0;
      return skuList.reduce((total, sku) => total + (sku.stock || 0), 0);
    }
  }
}
</script>

<style lang="scss" scoped>
.spec-group {
    padding: 10px;
    border: 1px solid #EBEEF5;
    margin-bottom: 10px;
}

.el-tag + .el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}

.goods-info {
    display: flex;
    align-items: flex-start;
    padding: 10px 0;
}

.goods-detail {
    flex: 1;
    overflow: hidden;
}

.goods-name {
    font-size: 14px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.goods-code {
    font-size: 12px;
    color: #909399;
    margin-bottom: 5px;
}

.goods-category {
    margin-top: 5px;
}
</style>
