<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="副标题" prop="subTitle">
        <el-input
          v-model="queryParams.subTitle"
          placeholder="请输入副标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.service_goods_status"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="价格">
        <el-input v-model="queryParams.minPrice" class="number-input" type="number" placeholder="最小值" clearable style="width: 120px;" />
        -
        <el-input v-model="queryParams.maxPrice" class="number-input" type="number" placeholder="最大值" clearable style="width: 120px;" />
      </el-form-item>

      <el-form-item label="分类" prop="cateId">
        <el-select v-model="queryParams.cateId" placeholder="请选择分类" clearable>
          <el-option
            v-for="cate in serviceCateList"
            :key="cate.id"
            :label="cate.title"
            :value="cate.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreatedAt"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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-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="['system:ServiceGoods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:ServiceGoods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:ServiceGoods:remove']"
        >删除</el-button>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:GoodsShangPin:export']"
          >导出</el-button>
        </el-col>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ServiceGoodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center"   width="55"   prop="id" />
      <el-table-column label="分类" align="center" prop="cateName"/>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="图标" align="center" prop="icon" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.icon" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="副标题" align="center" prop="subTitle" />
      <el-table-column label="价格" align="center" width="75" prop="price">
        <template slot-scope="scope">
          <div style="cursor:pointer;color:#409EFF;display:inline-block;">
            <span @click="openEditDialog(scope.row, 'price', '价格')">{{ scope.row.price }}</span>
            <svg @click="openEditDialog(scope.row, 'price', '价格')" width="14" height="14" viewBox="0 0 1024 1024" fill="#bbb" style="margin-left:4px;vertical-align:middle;cursor:pointer;"><path d="M880.64 227.84l-84.48-84.48c-25.6-25.6-67.2-25.6-92.8 0l-59.52 59.52 177.28 177.28 59.52-59.52c25.6-25.6 25.6-67.2 0-92.8zM160 736v128h128l376.32-376.32-128-128L160 736z"/></svg>
            <div style="border-bottom:1px dashed #bbb;width:100%;margin-top:2px;"></div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="销量" align="center" width="75" prop="sales">
        <template slot-scope="scope">
          <div style="cursor:pointer;color:#409EFF;display:inline-block;">
            <span @click="openEditDialog(scope.row, 'sales', '销量')">{{ scope.row.sales }}</span>
            <svg @click="openEditDialog(scope.row, 'sales', '销量')" width="14" height="14" viewBox="0 0 1024 1024" fill="#bbb" style="margin-left:4px;vertical-align:middle;cursor:pointer;"><path d="M880.64 227.84l-84.48-84.48c-25.6-25.6-67.2-25.6-92.8 0l-59.52 59.52 177.28 177.28 59.52-59.52c25.6-25.6 25.6-67.2 0-92.8zM160 736v128h128l376.32-376.32-128-128L160 736z"/></svg>
            <div style="border-bottom:1px dashed #bbb;width:100%;margin-top:2px;"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" width="75" prop="stock">
        <template slot-scope="scope">
          <div style="cursor:pointer;color:#409EFF;display:inline-block;">
            <span @click="openEditDialog(scope.row, 'stock', '库存')">{{ scope.row.stock }}</span>
            <svg @click="openEditDialog(scope.row, 'stock', '库存')" width="14" height="14" viewBox="0 0 1024 1024" fill="#bbb" style="margin-left:4px;vertical-align:middle;cursor:pointer;"><path d="M880.64 227.84l-84.48-84.48c-25.6-25.6-67.2-25.6-92.8 0l-59.52 59.52 177.28 177.28 59.52-59.52c25.6-25.6 25.6-67.2 0-92.8zM160 736v128h128l376.32-376.32-128-128L160 736z"/></svg>
            <div style="border-bottom:1px dashed #bbb;width:100%;margin-top:2px;"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" width="75" prop="sort">
        <template slot-scope="scope">
          <div style="cursor:pointer;color:#409EFF;display:inline-block;">
            <span @click="openEditDialog(scope.row, 'sort', '排序')">{{ scope.row.sort }}</span>
            <svg @click="openEditDialog(scope.row, 'sort', '排序')" width="14" height="14" viewBox="0 0 1024 1024" fill="#bbb" style="margin-left:4px;vertical-align:middle;cursor:pointer;"><path d="M880.64 227.84l-84.48-84.48c-25.6-25.6-67.2-25.6-92.8 0l-59.52 59.52 177.28 177.28 59.52-59.52c25.6-25.6 25.6-67.2 0-92.8zM160 736v128h128l376.32-376.32-128-128L160 736z"/></svg>
            <div style="border-bottom:1px dashed #bbb;width:100%;margin-top:2px;"></div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态"  width="85"  align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="handlefenleiStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>


      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:ServiceGoods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:ServiceGoods: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-drawer :title="title" :visible.sync="open" size="60%" append-to-body >
      <div style="padding:0 30px;">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="base">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="副标题" prop="subTitle">
              <el-input v-model="form.subTitle" placeholder="请输入副标题" />
            </el-form-item>
            <el-form-item label="图标" prop="icon">
              <image-upload v-model="form.icon"/>
            </el-form-item>
            <el-form-item label="轮播图" prop="imgs">
              <image-upload v-model="form.imgs"/>
            </el-form-item>
            <el-form-item label="简介" prop="info">
              <el-input v-model="form.info" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" />
            </el-form-item>
            <el-form-item label="列表价格显示" prop="priceZn">
              <el-input v-model="form.priceZn" placeholder="请输入列表价格显示" />
            </el-form-item>
            <el-form-item label="分类" prop="cateId">
              <el-select v-model="form.cateId" placeholder="请选择分类">
                <el-option v-for="cate in serviceCateList" :key="cate.id" :label="cate.title" :value="cate.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="邮费" prop="postage">
              <el-input v-model="form.postage" placeholder="请输入邮费（0或者不输入就是包邮）" />
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="营销配置" name="marketing">
            <el-form-item label="销量" prop="sales" required>
              <el-input-number
                v-model="form.sales"
                :min="0"
                :step="1"
                controls-position="both"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="排序" prop="sort" required>
              <el-input-number
                v-model="form.sort"
                :min="0"
                :step="1"
                controls-position="both"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="form.stock"
                :min="0"
                :step="1"
                controls-position="both"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
            <!-- 新增：是否关联服务 -->
            <el-form-item label="是否关联服务" prop="isforservice">
              <el-radio-group v-model="form.isforservice">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.isforservice == 1" label="关联服务" prop="forserviceid">
              <el-select v-model="form.forserviceid" placeholder="请选择服务" clearable>
                <el-option
                  v-for="item in forServiceList"
                  :key="item.id"
                  :label="item.title"
                  :value="String(item.id)"
                />
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="规格配置" name="spec">
            <el-form-item label="规格">
              <el-radio-group v-model="skuType">
                <el-radio-button :label="1">单规格</el-radio-button>
                <el-radio-button :label="2">多规格</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <div v-if="skuType === 1">
              <!-- <el-form-item label="规格名">
                <el-input v-model="form.skuName" placeholder="请输入规格名" />
              </el-form-item>
              <el-form-item label="规格值">
                <el-input v-model="form.skuValue" placeholder="请输入规格值" />
              </el-form-item> -->
            </div>
            <div v-else>
              <ShopSku :info="form.sku" ref="skuRef"></ShopSku>
            </div>
          </el-tab-pane>

          <el-tab-pane label="详情配置" name="detail">
            <el-form-item label="详情" prop="description">
              <editor v-model="form.description" :min-height="200" />
            </el-form-item>
            <el-form-item label="服务项目" prop="project">
              <editor v-model="form.project" :min-height="200" />
            </el-form-item>
            <el-form-item label="物料费用" prop="material">
              <editor v-model="form.material" :min-height="200" />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="问答配置" name="qa">
            <div class="qa-container">
              <div class="qa-header">
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="addQuestion">添加问答</el-button>
              </div>
              <div v-for="(qa, index) in form.questionsArray" :key="index" class="qa-item">
                <div class="qa-item-header">
                  <span class="qa-index">问答 #{{index + 1}}</span>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeQuestion(index)">删除</el-button>
                </div>
                <el-row :gutter="10">
                  <el-col :span="24">
                    <el-form-item :label="'问题'" :prop="'questionsArray.' + index + '.question'" :rules="[{required: true, message: '问题不能为空', trigger: 'blur'}]" label-width="50px">
                      <el-input v-model="qa.question" placeholder="请输入问题" size="small" @input="handleQuestionChange"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item :label="'答案'" :prop="'questionsArray.' + index + '.answer'" :rules="[{required: true, message: '答案不能为空', trigger: 'blur'}]" label-width="50px">
                      <el-input type="textarea" v-model="qa.answer" :rows="2" placeholder="请输入答案" size="small" @input="handleQuestionChange"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-divider></el-divider>
              </div>
            </div>
          </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>
    </div>
    </el-drawer>

    <el-dialog :visible.sync="audioDialogVisible" title="录音播放" width="400px">
      <audio v-if="currentAudioUrl" :src="currentAudioUrl" controls style="width:100%"></audio>
    </el-dialog>


    <el-dialog :visible.sync="editDialogVisible" title="编辑" width="300px">
      <el-form>
        <el-form-item :label="editFieldLabel">
          <el-input v-model="editFieldValue" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditField">保存</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { listServiceGoods, getServiceGoods, delServiceGoods, addServiceGoods, updateServiceGoods ,changefenleiStatus,selectServiceCateList,getselectTypeList} from "@/api/system/ServiceGoods"
import Editor from '@/components/Editor'

export default {
  name: "ServiceGoods",
  dicts: ['service_goods_status'],
  components: { Editor },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数

      serviceCateList: [],

      total: 0,
      // 服务内容表格数据
      ServiceGoodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        type: '2',
        minPrice: null,
        maxPrice: null,
        createdStart: null,
        createdEnd: null,
        cateId: null,
        pageSize: 10,
        title: null,
        subTitle: null,
        status: null,
        project: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        subTitle: [
          { required: true, message: "副标题不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        sales: [
          { required: true, message: "销量不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        sku: [
          { required: true, message: "规格信息不能为空", trigger: "blur" }
        ],
        isforservice: [
          { required: true, message: "请选择是否关联服务", trigger: "change" }
        ],
        forserviceid: [
          { required: function() { return this.form && this.form.isforservice == 1 }, message: "请选择关联服务", trigger: "change" }
        ],
      },
      audioDialogVisible: false,
      currentAudioUrl: '',
      editDialogVisible: false,
      editFieldValue: '',
      editField: '',
      editFieldLabel: '',
      editRow: null,
      daterangeCreatedAt: [],
      activeTab: 'base',
      skuType: 1,
      skuList: [ { name: '', value: '' } ],
      specList: [ { name: '', values: [''] } ],
      skuTable: [],
      saveTimeout: null, // 用于防抖的定时器
      isforservice: 2, // 默认2
      forServiceList: [], // 关联服务下拉数据
    }
  },
  created() {
    this.getList()
    this.getserviceCateList();
    this.getForServiceList(); // 新增
  },
  methods: {
    /** 查询服务内容列表 */
    getList() {
      this.loading = true
      listServiceGoods(this.queryParams).then(response => {
        this.ServiceGoodsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        icon: null,
        imgs: null,
        subTitle: null,
        info: null,
        price: null,
        priceZn: null,
        sales: 0,
        stock: 0,
        status: "1",
        description: null,
        skuType: 1,
        sku: "{}",
        skuName: null,
        skuValue: null,
        latitude: null,
        longitude: null,
        type: 2,
        cateId: null,
        project: null,
        sort: 50,
        material: null,
        postage: null,
        basic: null,
        margin: null,
        skillIds: null,
        createdAt: null,
        updatedAt: null,
        deletedAt: null,
        questionsArray: [], // 问答数组
        questions: null, // 问答JSON字符串
        isforservice: 2,
        forserviceid: null,
      }
      // 重置skuType为默认值
      this.skuType = 1;
      this.form.skuType = 1;
      // 重置活动标签页
      this.activeTab = 'base';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 处理创建时间
      if (this.daterangeCreatedAt && this.daterangeCreatedAt.length === 2) {
        this.queryParams.createdStart = this.daterangeCreatedAt[0];
        this.queryParams.createdEnd = this.daterangeCreatedAt[1];
      } else {
        this.queryParams.createdStart = null;
        this.queryParams.createdEnd = null;
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreatedAt = [];
      this.resetForm("queryForm")
      this.handleQuery()
    },


    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

        // 任务状态修改
        handlefenleiStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用"
      this.$modal.confirm('确认要' + text + '' + row.title + '状态吗？').then(function() {
        return changefenleiStatus(row.id, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.skuType = 1; // 新增时默认单规格
      this.form.skuType = 1;
      this.open = true
      this.title = "添加服务内容"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getServiceGoods(id).then(response => {
        this.form = response.data
        // 处理icon字段为单图字符串
        if (Array.isArray(this.form.icon)) {
          this.form.icon = this.form.icon.length > 0 ? this.form.icon[0] : '';
        }
        // 处理imgs字段为多图数组
        if (typeof this.form.imgs === 'string' && this.form.imgs) {
          if (this.form.imgs.includes(',')) {
            this.form.imgs = this.form.imgs.split(',').filter(Boolean);
          } else {
            this.form.imgs = [this.form.imgs];
          }
        } else if (!Array.isArray(this.form.imgs)) {
          this.form.imgs = [];
        }

        // 处理问答数据
        if (this.form.questions) {
          try {
            const questionsArray = JSON.parse(this.form.questions);
            if (Array.isArray(questionsArray)) {
              this.$set(this.form, 'questionsArray', questionsArray);
            } else {
              this.$set(this.form, 'questionsArray', []);
            }
          } catch (e) {
            console.error('问答数据解析失败:', e);
            this.$set(this.form, 'questionsArray', []);
          }
        } else {
          this.$set(this.form, 'questionsArray', []);
        }

        // 设置skuType，如果没有则默认为1
        this.skuType = this.form.skuType || 1;
        // 如果是单规格且sku有数据，尝试解析
        if (this.skuType === 1 && this.form.sku && this.form.sku !== '{}') {
          try {
            const skuData = JSON.parse(this.form.sku);
            if (skuData.name && skuData.value) {
              this.form.skuName = skuData.name;
              this.form.skuValue = skuData.value;
            }
          } catch (e) {
            console.warn('解析单规格数据失败:', e);
          }
        }
        this.open = true
        this.title = "修改服务内容"
        this.form.isforservice = response.data.isforservice || 2;
        // forserviceid转为字符串
        this.form.forserviceid = response.data.forserviceid !== undefined && response.data.forserviceid !== null ? String(response.data.forserviceid) : null;
        // 确保forserviceid在下拉数据中
        this.getForServiceList(() => {
          if (this.form.forserviceid && !this.forServiceList.find(item => String(item.id) === this.form.forserviceid)) {
            this.form.forserviceid = null;
          }
        });
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理icon字段为单图字符串
          if (Array.isArray(this.form.icon)) {
            this.form.icon = this.form.icon.length > 0 ? this.form.icon[0] : '';
          }
          // 处理imgs字段为字符串（逗号分隔），如后台只收字符串
          if (Array.isArray(this.form.imgs)) {
            this.form.imgs = this.form.imgs.filter(Boolean).join(',');
          }
          // 处理问答数据
          if (this.form.questionsArray && Array.isArray(this.form.questionsArray)) {
            const validQuestions = this.form.questionsArray.filter(qa =>
              qa && qa.question && qa.question.trim() && qa.answer && qa.answer.trim()
            ).map(qa => ({
              question: qa.question.trim(),
              answer: qa.answer.trim()
            }));
            this.form.questions = validQuestions.length > 0 ? JSON.stringify(validQuestions) : null;
          } else {
            this.form.questions = null;
          }

          // 处理规格信息
          if (this.skuType === 2) {
            // 多规格模式
            if (this.$refs.skuRef && this.$refs.skuRef.submit) {
              const skuData = this.$refs.skuRef.submit();
              if (!skuData) {
                this.$modal.msgError("请完善规格信息");
                return;
              }
              this.form.sku = typeof skuData === 'string' ? skuData : JSON.stringify(skuData);
            } else {
              this.$modal.msgError("规格信息不能为空");
              return;
            }
          } else {
            // 单规格模式，直接设置为{"type":"single"}
            this.form.sku = JSON.stringify({ type: "single" });
            this.form.skuType = 1;
          }

          // 验证sku不能为空
          if (!this.form.sku || this.form.sku === '{}') {
            this.$modal.msgError("规格信息不能为空");
            return;
          }

          // 提交时带上isforservice和forserviceid
          this.form.isforservice = this.form.isforservice || 2;
          if (this.form.isforservice == 1 && this.form.forserviceid) {
            this.form.forserviceid = String(this.form.forserviceid);
          } else {
            this.form.forserviceid = null;
          }

          if (this.form.id != null) {
            updateServiceGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              // 不自动关闭弹窗，让用户手动关闭
              this.getList(); // 刷新列表数据
            }).catch(error => {
              console.error('修改失败:', error);
              this.$modal.msgError("修改失败，请检查输入数据");
            });
          } else {
            addServiceGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              // 不自动关闭弹窗，让用户手动关闭
              this.getList(); // 刷新列表数据
            }).catch(error => {
              console.error('新增失败:', error);
              this.$modal.msgError("新增失败，请检查输入数据");
            });
          }
        } else {
          console.log('表单验证失败');
          this.$message.error('请完善必填信息');
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.title || this.ServiceGoodsList.filter(item => this.ids.includes(item.id)).map(item => item.title).join('、');

      this.$modal.confirm('是否确认删除商品"' + names + '"？').then(function() {
        return delServiceGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((error) => {
        console.error('删除失败:', error);
        this.$modal.msgError("删除失败，请稍后重试");
      });
    },
    getserviceCateList(){
     selectServiceCateList(2).then(response => {
      this.serviceCateList = response.data
     })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/ServiceGoods/export', {
        ...this.queryParams,
        type: '2' // 确保传递商品类型参数
      }, `商品数据_${new Date().getTime()}.xlsx`);
    },
    // 添加问答
    addQuestion() {
      this.form.questionsArray.push({
        question: '',
        answer: ''
      });
    },
    // 删除问答
    removeQuestion(index) {
      this.form.questionsArray.splice(index, 1);
    },
    // 问答内容变化
    handleQuestionChange() {
      // 当问答内容变化时，重新验证表单
      this.$nextTick(() => {
        this.$refs.form.validateField('questionsArray');
      });
    },
    // 打开编辑对话框
    openEditDialog(row, field, label) {
      // 深拷贝，避免直接引用导致视图未更新
      this.editRow = JSON.parse(JSON.stringify(row));
      this.editField = field;
      this.editFieldLabel = label;
      this.editFieldValue = row[field];
      this.editDialogVisible = true;
    },
    // 保存编辑的值
    saveEditField() {
      // 更新本地数据
      this.editRow[this.editField] = this.editFieldValue;
      // 调用后端接口保存
      updateServiceGoods(this.editRow).then(response => {
        this.$modal.msgSuccess("保存成功");
        this.editDialogVisible = false;
        this.getList(); // 刷新主表
      }).catch(error => {
        this.$modal.msgError("保存失败，请稍后重试");
      });
    },
    // 取消编辑
    cancelEdit() {
      this.editDialogVisible = false;
    },
    // 获取关联服务列表
    getForServiceList(callback) {
      getselectTypeList(1).then(response => {
        this.forServiceList = response.data;
        if (callback) {
          callback();
        }
      });
    },
  }
}
</script>

<style scoped>
/* 你的样式代码 */
</style>
