<template>
  <div class="baseBox">
    <div class="form-content">
      <!-- <div class="formHeader">基础信息</div> -->
      <el-form>
        <!-- 基础信息 -->
        <el-card class="cardStyle" v-if="showImage">
          <template #header>
            <div @click="categoryDialogOpen = true">
              <span class="cardTitle">基础信息</span>
              <span class="chooseClass" v-if="categoryName">{{ categoryName }}</span>
              <span class="editTxt">修改</span>
            </div>
          </template>
          <div>
            <el-row>
              <el-col :span="12">
                <div class="commonHeader">产品标题</div>
                <el-select
                  v-model="form['apiProductLaunchDto'].title"
                  filterable
                  remote
                  allow-create
                  default-first-option
                  :reserve-keyword="false"
                  placeholder="请选择产品名称"
                  @blur="handleSelectChange"
                  :remote-method="searchProduct"
                  clearable
                  remote-show-suffix
                >
                  <el-option
                    v-for="item in productList"
                    :key="item.productBizId"
                    :label="item.productName"
                    :value="item.productBizId"
                  />
                </el-select>
              </el-col>
              <el-col :span="24" :class="showNameTip ? '' : 'colBottomGap'">
                <div class="nameTip">
                  <span style="color: #ccc">标题需包含产品名称。</span>

                  <el-tooltip placement="bottom" effect="light" trigger="click">
                    <template #content>
                      <div style="width: 300px">
                        <div
                          v-for="item in nameRequireList"
                          :key="item.key"
                          style="margin-bottom: 8px"
                        >
                          <span style="font-size: 13px">•</span>
                          <span style="margin-left: 5px">{{ item.label }}</span>
                        </div>
                      </div>
                    </template>
                    <span style="color: #576b95; cursor: pointer">查看命名要求</span>
                  </el-tooltip>
                </div>
              </el-col>
              <el-col :span="24" v-if="showNameTip">
                <div class="tipCon">
                  <el-icon color="red" :size="20" style="margin-right: 5px"><Warning /></el-icon>
                  <span>标题信息过少，请至少输入5个有效字数（含中文、英文、数字）</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="commonHeader">产品短标题</div>
                <el-input
                  v-model="form['apiProductLaunchDto'].shortTitle"
                  placeholder="请输入"
                  maxlength="20"
                  show-word-limit
                />
              </el-col>
              <el-col :span="24" class="colBottomGap">
                <div class="nameTip">
                  <span style="color: #ccc">短标题会展示在对话、朋友圈分享等场景。</span>
                </div>
              </el-col>
              <el-col :span="24">
                <div class="commonHeader">产品参数</div>
                <el-row :gutter="20">
                  <template v-if="form.apiAttributeSettingDtoList.length">
                    <el-col
                      :span="item.isCustomize == '1' ? 24 : 8"
                      v-for="(item, index) in form.apiAttributeSettingDtoList"
                    >
                      <div
                        class="paramsItem"
                        v-if="item.isCustomize == '0'"
                        :style="{ marginBottom: item.errorMsg ? '0px' : '20px' }"
                      >
                        <div class="paramsLeft" style="width: 30%">
                          <el-select
                            v-model="item.name"
                            placeholder="请选择"
                            @change="changeLeft(item, index)"
                          >
                            <el-option
                              v-for="left in item.leftOptions"
                              :key="left.value"
                              :label="left.fieldCnName"
                              :value="left.fieldBizId"
                            />
                          </el-select>
                        </div>
                        <div class="paramsMiddle" style="width: 63%">
                          <el-input
                            v-model="item.value"
                            placeholder="请输入"
                            @blur="paramsErr"
                            v-if="item.textBoxType == 'text'"
                          />
                          <el-input-number
                            v-if="item.textBoxType == 'number'"
                            v-model="item.value"
                            :min="1"
                            style="width: 100%"
                          />
                          <!-- 单选下拉框 -->
                          <el-select
                            v-model="item.value"
                            @blur="paramsErr"
                            placeholder="请选择"
                            v-if="item.textBoxType == 'select'"
                          >
                            <el-option
                              v-for="middle in item.middleOptions"
                              :key="middle.fieldValueBizId"
                              :label="middle.value"
                              :value="middle.fieldValueBizId"
                              clearable
                            />
                          </el-select>
                          <!-- 多选下拉框 -->
                          <el-select
                            v-model="item.value"
                            @blur="paramsErr"
                            multiple
                            collapse-tags
                            collapse-tags-tooltip
                            :max-collapse-tags="2"
                            placeholder="请选择"
                            v-if="item.textBoxType == 'multipleSelect'"
                            clearable
                          >
                            <el-option
                              v-for="middle in item.middleOptions"
                              :key="middle.fieldValueBizId"
                              :label="middle.value"
                              :value="middle.fieldValueBizId"
                            />
                          </el-select>
                          <!-- 带时分的时间框 -->
                          <el-date-picker
                            @blur="paramsErr"
                            v-model="item.value"
                            style="width: 100%"
                            v-if="item.textBoxType == 'dateTime'"
                            type="datetime"
                            placeholder="请选择"
                            @change="handleDateChange()"
                            format="YYYY-MM-DD HH:mm"
                            value-format="YYYY-MM-DD HH:mm:ss"
                          />
                          <!-- 不带时分 -->
                          <el-date-picker
                            @blur="paramsErr"
                            v-model="item.value"
                            style="width: 100%"
                            v-if="item.textBoxType == 'date'"
                            type="date"
                            placeholder="请选择"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            @change="handleDateChange()"
                          />
                        </div>
                        <div
                          class="paramsRight"
                          style="width: 8%"
                          @click="deleteParams(item, index)"
                        >
                          <el-icon><Delete /></el-icon>
                        </div>
                      </div>
                      <div
                        class="paramsItem"
                        v-else
                        :style="{ marginBottom: item.errorMsg ? '0px' : '20px' }"
                      >
                        <div class="paramsLeft" style="width: 30%">
                          <el-select
                            v-model="item.customValue"
                            placeholder="请选择"
                            @change="changeCustomLeft(item, index)"
                          >
                            <el-option
                              v-for="left in item.leftOptions"
                              :key="left.value"
                              :label="left.fieldCnName"
                              :value="left.fieldBizId"
                            />
                          </el-select>
                        </div>
                        <div class="paramsMiddle" style="width: 63%">
                          <el-input
                            v-model="item.name"
                            placeholder="请输入参数名"
                            @blur="paramsErr"
                          />
                        </div>
                        <div class="paramsMiddle customMiddle" style="width: 63%">
                          <el-input
                            v-model="item.value"
                            placeholder="请输入参数值"
                            @blur="paramsErr"
                          />
                        </div>
                        <div
                          class="paramsRight"
                          style="width: 8%"
                          @click="deleteCustomParams(item, index)"
                        >
                          <el-icon><Delete /></el-icon>
                        </div>
                      </div>
                      <div class="errorParams" v-if="item.errorMsg">
                        <el-icon color="red" :size="20" style="margin-right: 5px"
                          ><Warning
                        /></el-icon>
                        <span>{{ item.errorMsg }}</span>
                      </div>
                    </el-col>
                  </template>
                  <el-col :span="24" class="addTxt" @click="addParams">
                    <el-icon :size="24"><CirclePlus /></el-icon>
                    <span style="margin-left: 5px">添加新参数</span>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <!-- 配图 -->
        <el-card class="cardStyle" v-if="showImage">
          <template #header>
            <div>
              <span class="cardTitle">产品展示与介绍</span>
            </div>
          </template>
          <div>
            <el-row>
              <!-- 主图 -->
              <el-col :span="24" style="margin: 20px 0">
                <div class="commonHeader">
                  图片和视频
                  <span style="color: rgb(111, 111, 111); font-size: 15px"
                    >({{ imageInfo.count }}/9)</span
                  >
                </div>

                <image-upload
                  v-model="form['apiProductLaunchDto'].mainUrlsList"
                  :action="'/oss/api/oss/upload'"
                  :limit="9"
                  :image-size="10"
                  :video-size="500"
                  :file-type="['png', 'jpg', 'jpeg', 'mp4']"
                  :is-show-tip="false"
                  source="main"
                  @file-change="handleFileChange"
                />
              </el-col>
              <el-col :span="24">
                <div v-for="(item, index) in imageRequireList" :key="item.key" class="imgTip">
                  <span>{{ index + 1 }}.</span>
                  <span>{{ item.label }}</span>
                  <el-tooltip placement="bottom" effect="light" trigger="click" v-if="item.showTip">
                    <template #content>
                      <div style="width: 300px">
                        <div
                          v-for="item in imageTipList"
                          :key="item.key"
                          style="margin-bottom: 8px"
                        >
                          <span style="font-size: 13px">•</span>
                          <span style="margin-left: 5px">{{ item.label }}</span>
                        </div>
                      </div>
                    </template>
                    <span style="color: #576b95; cursor: pointer">{{ item.tipContent }}</span>
                  </el-tooltip>
                </div>
              </el-col>
              <el-col :span="24" v-if="imageInfo.count > 0 && imageInfo.count < 3">
                <div class="tipCon">
                  <el-icon color="red" :size="20" style="margin-right: 5px"><Warning /></el-icon>
                  <span>请上传至少3张产品主图</span>
                </div>
              </el-col>
              <!-- 详情图 -->
              <el-col :span="24" style="margin: 20px 0">
                <div class="commonHeader">
                  详情图和描述
                  <span style="color: rgb(111, 111, 111); font-size: 15px"
                    >({{ subImageInfo.count }}/50)</span
                  >
                </div>

                <image-upload
                  v-model="form['apiProductLaunchDto'].detailUrlsList"
                  :action="'/oss/api/oss/upload'"
                  :limit="50"
                  :image-size="10"
                  :file-type="['png', 'jpg', 'jpeg']"
                  :is-show-tip="false"
                  source="sub"
                  @file-change="handleFileChange"
                />
              </el-col>
              <el-col :span="24">
                <div v-for="(item, index) in desRequireList" :key="item.key" class="imgTip">
                  <span>{{ index + 1 }}.</span>
                  <span>{{ item.label }}</span>
                  <el-tooltip placement="bottom" effect="light" trigger="click" v-if="item.showTip">
                    <template #content>
                      <div style="width: 310px">
                        <div v-for="item in desTipList" :key="item.key" style="margin-bottom: 8px">
                          <span style="font-size: 13px">•</span>
                          <span style="margin-left: 5px">{{ item.label }}</span>
                        </div>
                      </div>
                    </template>
                    <span style="color: #576b95; cursor: pointer">{{ item.tipContent }}</span>
                  </el-tooltip>
                </div>
              </el-col>
              <el-col :span="24" v-if="subImageInfo.count == 0">
                <div class="tipCon">
                  <el-icon color="red" :size="20" style="margin-right: 5px"><Warning /></el-icon>
                  <span>请上传至少1张产品详情图</span>
                </div>
              </el-col>
              <el-col :span="24" style="margin-top: 10px">
                <el-input
                  v-model="form['apiProductLaunchDto'].detailDescription"
                  type="textarea"
                  placeholder="产品描述(选填)"
                />
              </el-col>
            </el-row>
          </div>
        </el-card>
        <!-- 规格和库存价格 -->
        <el-card class="cardStyle" v-if="showImage">
          <template #header>
            <div>
              <span class="cardTitle">规格和库存价格</span>
            </div>
          </template>
          <div>
            <el-row>
              <el-col :span="24">规格</el-col>
              <el-col :span="24">
                <div
                  class="speciesItem"
                  v-for="(item, index) in form.speciesData"
                  :key="item.speciesTypeBizId"
                >
                  <div class="speciesTop">
                    <div class="speciesTopLeft">
                      <el-select
                        v-model="item.speciesName"
                        placeholder="请选择"
                        @change="changeSpeciesSelect(item, index)"
                        style="width: 300px"
                      >
                        <el-option
                          v-for="left in item.options"
                          :key="left.speciesTypeBizId"
                          :label="left.typeName"
                          :value="left.speciesTypeBizId"
                        />
                      </el-select>
                      <!-- 自定义规格名称 -->
                      <div class="customizeInput" v-if="item.isCustomize == '1'">
                        <el-input
                          v-model="item.typeName"
                          placeholder="请输入规格名称"
                          @blur="changCustomSpecies(item)"
                          style="width: 300px"
                        />
                        <div class="customizeErrorMsg" v-if="item.errorMsg">
                          {{ item.errorMsg }}
                        </div>
                      </div>
                      <!-- 切换配图得switch -->
                      <template v-if="index == 0">
                        <el-popconfirm
                          v-if="item.isIllustration == '1'"
                          width="300"
                          class="box-item"
                          title="关闭开关会清空现在的配图"
                          placement="bottom"
                          hide-icon
                          @confirm="switchChange(item, 'close')"
                        >
                          <template #reference>
                            <div>
                              <el-switch
                                v-model="item.isIllustration"
                                active-value="1"
                                inactive-value="0"
                                style="margin: 0 5px 0px 15px"
                                :before-change="switchBeforeChange"
                              ></el-switch>
                              <span class="imgSwitch">配图</span>
                            </div>
                          </template>
                        </el-popconfirm>
                        <div v-else>
                          <el-switch
                            v-model="item.isIllustration"
                            active-value="1"
                            inactive-value="0"
                            style="margin: 0 5px 0px 15px"
                            @change="switchChange(item, 'open')"
                          ></el-switch>
                          <span class="imgSwitch">配图</span>
                        </div>
                      </template>
                    </div>
                    <div class="speciesTopRight" @click="deleteSpecies(item)">
                      <el-icon :size="18"><Delete /></el-icon>
                    </div>
                  </div>
                  <el-row :gutter="20" style="margin-top: 15px">
                    <el-col
                      :span="8"
                      v-for="(species, sIndex) in item.apiSpeciesSettingDtoList"
                      :key="species.speciesId"
                    >
                      <div class="paramsItem" style="margin-bottom: 20px">
                        <div
                          class="paramsLeft speciesLeft"
                          style="width: 8%"
                          v-if="species.isIllustration == '1'"
                        >
                          <el-upload
                            :action="uploadUrl"
                            style="display: flex"
                            list-type="picture"
                            :headers="headers"
                            :show-file-list="false"
                            :on-success="(res, file) => handleUploadSuccess(res, file, species)"
                            :before-upload="handleBeforeUpload"
                          >
                            <el-icon v-if="!species.illustrationUrl" :size="24" color="#969696"
                              ><Picture
                            /></el-icon>
                            <!-- <el-popconfirm
                              width="300"
                              class="box-item"
                              title="关闭开关会清空现在的配图"
                              placement="bottom"
                              hide-icon
                            >
                            </el-popconfirm> -->
                            <img v-else :src="species.illustrationUrl" style="width: 100%; height:
                            32px;object-fit: cover"
                          </el-upload>
                        </div>
                        <div
                          class="paramsMiddle speciesMiddle"
                          :style="{ width: getSpeciesMiddleWidth(species, item) }"
                        >
                          <el-input
                            v-model="species.value"
                            placeholder="请输入"
                            @keydown="speciesInputChange(species, sIndex, item)"
                          />
                        </div>

                        <div
                          v-if="item.apiSpeciesSettingDtoList.length > 1"
                          class="paramsRight speciesRight"
                          style="width: 8%"
                          @click="deleteSpeciesValue(species)"
                        >
                          <el-icon><Delete /></el-icon>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
              <el-col :span="24" class="addTxt">
                <el-icon :size="22"><CirclePlus /></el-icon>
                <span style="margin-left: 5px" @click="addSpecies">创建新规格</span>
              </el-col>
              <el-col :span="24" style="margin-top: 20px">价格与库存</el-col>
              <!-- 规格价格得设置 -->
              <el-col
                :span="24"
                style="margin-top: 10px; margin-bottom: 10px"
                v-if="speciesSelectList.length > 0"
              >
                <!-- 规格值得选择 -->
                <div class="speciesSelect">
                  <div v-for="item in speciesSelectList">
                    <el-select
                      placeholder="请选择"
                      style="width: 220px; margin-right: 20px"
                      v-model="selectedValues[item.speciesTypeBizId]"
                    >
                      <el-option
                        v-for="left in item.options"
                        :key="left.speciesId"
                        :label="left.value"
                        :value="left.speciesId"
                      />
                    </el-select>
                  </div>
                </div>
                <!-- 产品价格等得固定设置 -->
                <div class="settingBox">
                  <div class="paramsItem settingItem">
                    <div class="paramsLeft settingLeft">售卖价</div>
                    <div class="paramsMiddle settingRight">
                      <el-input type="number" v-model="batchPrice" placeholder="请输入售卖价" />
                    </div>
                  </div>
                  <div class="paramsItem settingItem">
                    <div class="paramsLeft settingLeft">库存</div>
                    <div class="paramsMiddle settingRight">
                      <el-input type="number" v-model="batchInventory" placeholder="请输入库存" />
                    </div>
                  </div>
                  <el-button
                    type="primary"
                    plain
                    @click="handleBatchSet"
                    :disabled="!batchPrice && !batchInventory"
                    >设置</el-button
                  >
                </div>
              </el-col>
              <!-- 规格表格部分 -->
              <el-table
                :data="tableData"
                :span-method="objectSpanMethod"
                border
                style="width: 100%; margin-top: 20px"
                height="250"
              >
                <!-- 动态规格列 -->
                <el-table-column
                  v-for="spec in form.speciesData.filter(
                    item => item.typeName && item.apiSpeciesSettingDtoList[0].value
                  )"
                  :key="spec.speciesTypeBizId"
                  :prop="spec.speciesTypeBizId"
                  :label="spec.typeName"
                  align="center"
                  :width="form.speciesData.length > 5 ? 150 : 'auto'"
                  fixed="left"
                >
                  <template #default="scope">
                    {{ scope.row[spec.speciesTypeBizId] }}
                  </template>
                </el-table-column>

                <!-- 价格列 -->
                <el-table-column
                  prop="price"
                  label="价格"
                  :width="tableData.length > 0 ? 120 : 'auto'"
                  align="center"
                >
                  <template #header>
                    <span class="required-label">价格</span>
                  </template>
                  <template #default="scope">
                    <el-input v-model="scope.row.price" type="number" />
                    <div class="errMsg" v-if="scope.row.priceErrorMsg">
                      {{ scope.row.priceErrorMsg }}
                    </div>
                  </template>
                </el-table-column>

                <!-- 库存列 -->
                <el-table-column
                  prop="inventory"
                  label="库存"
                  :width="tableData.length > 0 ? 120 : 'auto'"
                  align="center"
                >
                  <template #header>
                    <span class="required-label">库存</span>
                  </template>
                  <template #default="scope">
                    <el-input v-model="scope.row.inventory" type="number" />
                    <div class="errMsg" v-if="scope.row.inventoryErrorMsg">
                      {{ scope.row.inventoryErrorMsg }}
                    </div>
                  </template>
                </el-table-column>
                <!-- 配图列 -->
                <el-table-column
                  prop="illustrationUrl"
                  label="配图"
                  :width="tableData.length > 0 ? 120 : 'auto'"
                  align="center"
                >
                  <template #default="scope">
                    <div style="display: flex; align-items: center; justify-content: center">
                      <img
                        v-if="scope.row.illustrationUrl"
                        :src="scope.row.illustrationUrl"
                        style="width: 60%; height: 60%; object-fit: cover"
                      />
                      <el-icon v-else :size="24" color="#969696">
                        <Picture />
                      </el-icon>
                    </div>
                  </template>
                </el-table-column>
                <!-- 状态列 -->
                <el-table-column
                  prop="status"
                  label="状态"
                  :width="tableData.length > 0 ? 120 : 'auto'"
                  align="center"
                  fixed="right"
                >
                  <template #default="scope">
                    <el-switch v-model="scope.row.status" active-value="1" inactive-value="0" />
                    <span style="margin-left: 8px">
                      {{ scope.row.status === '1' ? '上架' : '下架' }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </div>
        </el-card>
        <!-- 更多设置 -->
        <el-card class="cardStyle">
          <template #header>
            <div>
              <span class="cardTitle">更多设置</span>
            </div>
          </template>
          <el-row>
            <el-col :span="24">
              <div class="moreBox">
                <div class="moreTitle">定时开售</div>
                <div class="moreItem">
                  <div class="moreLeft">设置定时</div>
                  <div class="moreRight">
                    <el-switch
                      v-model="form.apiProductLaunchDto['isTiming']"
                      active-value="1"
                      inactive-value="0"
                      style="margin: 0 5px 0px 15px"
                    ></el-switch>
                    <span class="imgSwitch">{{
                      form.apiProductLaunchDto['isTiming'] == '1' ? '已开启' : '已关闭'
                    }}</span>
                  </div>
                </div>
                <div class="moreItem" v-if="form.apiProductLaunchDto['isTiming'] == '1'">
                  <div class="moreLeft">开售日期</div>
                  <div class="moreRight" style="margin-left: 15px">
                    <el-date-picker
                      v-model="form.apiProductLaunchDto['releaseDate']"
                      style="width: 100%"
                      type="datetime"
                      placeholder="请选择开售日期"
                      format="YYYY-MM-DD HH:mm"
                      value-format="YYYY-MM-DD HH:mm:ss"
                    />
                  </div>
                </div>
                <div class="moreItem" v-if="form.apiProductLaunchDto['isTiming'] == '1'">
                  <div class="moreLeft">隐藏信息</div>
                  <div class="moreRight" style="margin-left: 15px">
                    <el-checkbox
                      v-model="form.apiProductLaunchDto['isHiddenPrice']"
                      label="价格"
                      size="large"
                    />
                  </div>
                </div>
              </div>
              <div class="moreBox">
                <div class="moreTitle">购买设置</div>
                <div class="moreItem">
                  <div class="moreLeft">
                    {{ form.apiProductLaunchDto['isPurchaseLimit'] == '1' ? '购买限制' : '限购' }}
                  </div>
                  <div class="moreRight">
                    <el-switch
                      v-model="form.apiProductLaunchDto['isPurchaseLimit']"
                      active-value="1"
                      inactive-value="0"
                      style="margin: 0 5px 0px 15px"
                    ></el-switch>
                    <span class="imgSwitch">{{
                      form.apiProductLaunchDto['isPurchaseLimit'] == '1' ? '开启限购' : '未开启'
                    }}</span>
                  </div>
                </div>
                <div class="moreItem" v-if="form.apiProductLaunchDto['isPurchaseLimit'] == '1'">
                  <div class="moreLeft"></div>
                  <div class="moreRight" style="margin-left: 15px">
                    <span>每人</span>
                    <el-select
                      placeholder="请选择"
                      style="width: 100px; margin-right: 5px"
                      v-model="form.apiProductLaunchDto['limitDateUnit']"
                    >
                      <el-option
                        v-for="option in limitoptions"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                      />
                    </el-select>
                    <span>限购</span>
                    <el-input
                      v-model="form.apiProductLaunchDto['limitQuantity']"
                      placeholder="件数"
                      type="number"
                      style="width: 120px; margin-right: 20px"
                    >
                      <template #append>
                        <span>件</span>
                      </template>
                    </el-input>
                  </div>
                </div>
              </div>
              <div class="moreBox">
                <div class="moreTitle">上架平台</div>
                <el-button
                  type="primary"
                  plain
                  @click="choosePlatform"
                  style="margin-top: 10px; margin-bottom: 10px"
                  >选择平台</el-button
                >
                <el-table :data="choosePlatformList" border>
                  <el-table-column
                    label="项目名称"
                    prop="projectName"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column label="项目编号" prop="projectCode" />
                  <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                    width="200"
                    fixed="right"
                  >
                    <template #default="scope">
                      <el-button
                        link
                        type="danger"
                        icon="Delete"
                        @click="deletePlatform(scope.row, scope.$index)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>
    <div class="bottomBtn">
      <el-button type="primary" size="large" @click="submitProduct">提交</el-button>
    </div>
    <!-- 选择平台 -->
    <el-dialog title="平台" v-model="platFormOpen" width="700px" append-to-body>
      <el-form
        :model="platFormQueryParams"
        ref="platFormQueryRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="platFormQueryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchPlatformTable">搜索</el-button>
          <el-button icon="Refresh" @click="paltformReset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格数据 -->
      <el-table
        v-loading="platFormLoading"
        :data="platFormList"
        @selection-change="platformSelectionChange"
        :row-key="row => row.projectBizId"
        :reserve-selection="true"
        ref="platformTableRef"
      >
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="项目名称" prop="projectName" />
        <el-table-column label="项目编号" prop="projectCode" />
      </el-table>
      <pagination
        v-show="platformTotal > 0"
        :total="platformTotal"
        v-model:page="platFormQueryParams.pageNo"
        v-model:limit="platFormQueryParams.pageSize"
        @pagination="getPlatFormList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmPlatform">确 定</el-button>
          <el-button @click="closePlatform">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改分类类目 -->
    <el-dialog title="修改产品类目" v-model="categoryDialogOpen" width="1000px" append-to-body>
      <CategoryTable
        style="height: 300px"
        type="edit"
        ref="categoryRef"
        :data="selectCategoryData"
      />
      <template #footer>
        <div class="categoryDialogFooter">
          <el-button type="primary" @click="categoryConfirm">确 定</el-button>
          <el-button @click="categoryDialogOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="`${errorList.length}处需修改`"
      v-model="errorDialogOpen"
      width="800px"
      append-to-body
    >
      <div class="errorContent">
        <div class="errorTitle">以下问题会导致提交不通过，建议修改完再提交</div>
        <div class="errorItem" v-for="error in errorList">
          <el-icon class="errMsg" :size="22" style="margin-right: 5px"><Warning /></el-icon>
          <span>{{ error.msg }}</span>
        </div>
      </div>
      <template #footer>
        <div class="categoryDialogFooter">
          <el-button type="primary" @click="errorDialogOpen = false">去修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="InsuranceProduct">
import { assign, cloneDeep } from 'lodash-es'

import {
  getProductList,
  addProduct,
  getProductDetail,
  productParams,
  ParamRightOptions,
  productSpecies,
  querySelectCategory,
  saveProductLaunch
} from '@/api/product/index'
import { listProject } from '@/api/system/project'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'
import { ref, computed, watch, nextTick } from 'vue'
import ImageUpload from '@/components/ImageUpload/index.vue' //图片上传组件
import CategoryTable from '@/components/CategoryTable/index.vue' //图片上传组件
const emit = defineEmits(['handleSuccess'])
const props = defineProps({
  // 类型，是新增还是编辑,
  activeName: {
    type: String,
    default: ''
  },
  detailInfo: {
    type: Object,
    default: () => {}
  }
})
const headers = ref({ Authorization: 'Bearer ' + getToken() })
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/oss/api/oss/upload')
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()
const showImage = ref(true)
const SummaryRightOptions = ref([]) //产品参数右侧下拉框汇总列表
const paramsList = ref([]) //产品参数总列表
const subImageInfo = ref({ count: 0, fileList: [] }) //详情图信息
const showNameTip = ref(false)
const imageInfo = ref({ count: 0, fileList: [] })
const productList = ref([])
const errorList = ref([]) //存储错误信息
const errorDialogOpen = ref(false)
const showOnce = ref(false)
const allProductList = ref([])
const nameRequireList = ref([
  {
    label: '标题中必须包含产品名称',
    key: '1'
  },
  {
    label: '标题禁止出现连续重复的关键词',
    key: '2'
  },
  {
    label: '标题字数不少于5个字，包括中文、 英文、数字',
    key: '3'
  },
  {
    label: '标题为非中文时需要附带与产品对应一致的中文翻译',
    key: '4'
  },
  {
    label: '标题中需避免填写错别字',
    key: '5'
  }
])
const imageRequireList = ref([
  {
    label: '商品主图须符合平台要求，否则将无法通过审核。',
    key: '1',
    showTip: true,
    tipContent: '查看主图要求'
  },
  {
    label: '最少上传3个素材，最多上传9个素材，其中最多上传1个视频(mp4格式)，拖拽图片可排序。',
    key: '2'
  },
  {
    label: '视频时长不超过180秒，视频大小不超过500M；单张图片需限制在10M以内。',
    key: '3'
  }
])
const desRequireList = ref([
  {
    label: '商品详情图须符合平台要求，否则将无法通过审核。',
    key: '1',
    showTip: true,
    tipContent: '查看详情图要求'
  },
  {
    label: '至少上传1个素材，最多上传50个素材，拖拽可进行排序。',
    key: '2'
  },
  {
    label: '单张图片需限制在10M以内。',
    key: '3'
  }
])
const imageTipList = ref([
  {
    label: '全类目的产品主图要求提供不少于3张产品相关图片',
    key: '1'
  },
  {
    label: '主图第一张需为产品实物图',
    key: '2'
  },
  {
    label: '产品主图中不可包含相同的图片',
    key: '3'
  },
  {
    label: '产品图片不允许为手机截图、空白图',
    key: '4'
  },
  {
    label: '图片需清晰，不允许打码、遮挡/ps',
    key: '5'
  }
])
const desTipList = ref([
  {
    label: '商品详情图不得少于1张',
    key: '1'
  },
  {
    label: '详情图需为与商品相关的图片',
    key: '2'
  },
  {
    label: '商品详情图中不可包含相同的图片',
    key: '3'
  },
  {
    label: '商品图片不允许为手机截图、空白图',
    key: '4'
  },
  {
    label: '图片需清晰，不允许打码、遮挡/ps、第三方平台信息等',
    key: '5'
  }
])
const data = reactive({
  form: {
    apiProductLaunchDto: {},
    apiAttributeSettingDtoList: [],
    speciesData: [], //规格设置的数据
    apiSpeciesPriceDtoList: []
  },
  queryParams: {},
  platFormQueryParams: {
    pageNo: 1,
    pageSize: 10
  }
})

const { queryParams, form, platFormQueryParams } = toRefs(data)
const handleDateChange = () => {}
// ===========更多设置开始===========
const choosePlatformList = ref([]) // 表格数据
const platFormOpen = ref(false)
const platFormLoading = ref(false)
const platFormList = ref([])
const platformSelectRows = ref([])
const platformTotal = ref(0)
const platformTableRef = ref()
const selectedRows = ref([])
// 使用 Set 来管理已选择的ID，方便查找
const selectedPlatformIds = ref(new Set())

const limitoptions = ref([
  {
    label: '每日',
    value: 'DAILY',
    key: '1'
  },
  {
    label: '每周',
    value: 'WEEKLY',
    key: '2'
  },
  {
    label: '每月',
    value: 'MONTHLY',
    key: '3'
  },
  {
    label: '每年',
    value: 'YEARLY',
    key: '4'
  }
])

const platformSelectionChange = rows => {
  platformSelectRows.value = rows

  // 实时更新ID集合
  selectedPlatformIds.value = new Set(rows.map(item => item.projectBizId))
}
const paltformReset = () => {
  platFormQueryParams.value = {
    pageNo: 1,
    pageSize: 10
  }
  getPlatFormList()
}
const closePlatform = () => {
  platFormQueryParams.value = {
    pageNo: 1,
    pageSize: 10
  }
  platFormOpen.value = false
}
// 确定选择的平台
const confirmPlatform = () => {
  choosePlatformList.value = cloneDeep(platformSelectRows.value)
  // 更新已选择的ID集合
  selectedPlatformIds.value = new Set(choosePlatformList.value.map(item => item.projectBizId))
  closePlatform()
}

// 2. 修改弹窗打开函数
const choosePlatform = async () => {
  platFormOpen.value = true
  platFormQueryParams.value.pageNo = 1

  // 获取列表数据
  await getPlatFormList()
}

const getPlatFormList = () => {
  platFormLoading.value = true
  try {
    listProject(platFormQueryParams.value).then(response => {
      platFormList.value = response.data.records
      platformTotal.value = response.data.total
      // 数据加载后，设置选择状态
      nextTick(() => {
        if (platformTableRef.value) {
          // 先清空所有选择
          // platformTableRef.value.clearSelection()
          platFormList.value.forEach(row => {
            // 不可删除，删除会有bug
            choosePlatformList.value.forEach(item => {
              if (item.projectBizId == row.projectBizId) {
                platformTableRef.value.toggleRowSelection(row, true)
              }
            })
            const isSelected = selectedPlatformIds.value.has(row.projectBizId)

            platformTableRef.value.toggleRowSelection(row, isSelected)
          })
        }
      })
    })
  } catch (error) {
    platFormList.value = []
  } finally {
    platFormLoading.value = false
  }
}
const searchPlatformTable = () => {
  platFormQueryParams.value.pageNo = 1
  getPlatFormList()
}
const deletePlatform = (row, index) => {
  proxy.$modal
    .confirm('是否确认删除平台名称为"' + row.projectName + '"的数据项?')
    .then(function () {
      if (choosePlatformList.value.length > 0) {
        choosePlatformList.value.splice(index, 1)
        platformSelectRows.value.splice(index, 1)
        // 从已选择的ID集合中移除
        selectedPlatformIds.value.delete(row.projectBizId)
      }
    })
    .catch(() => {})
}

// ===========更多设置结束===========

// ===========产品规格与库存相关操作开始===========
const tableData = ref([]) // 表格数据
const tableColumns = ref([]) // 表格列配置
const comboData = ref({}) // 存储每个规格组合的数据（价格、库存等）
const speciesList = ref([])
const speciesSelectList = ref([])
const isSettingSpeciesPrice = ref(false) //是否根据详情值回显规格价格的值
// 存储每个规格下拉框选中的值
const selectedValues = ref({})
// 价格和库存输入
const batchPrice = ref('')
const batchInventory = ref('')

/** 获取产品的所有规格 */
function getProductSpeciesInfo() {
  productSpecies({ objectBizIdList: form.value.apiProductLaunchDto.categoryBizIdList }).then(
    response => {
      if (response.code == 200) {
        // 应该做获取右侧的下拉框值了
        speciesList.value = []
        speciesList.value = response.data
        let obj = {
          speciesTypeBizId: `customSpecies${Date.now() + Math.floor(Math.random() * 1000)}`, //字段表唯一业务ID
          isCustomize: '1', //是否自定义 0-否 1-是
          typeName: '自定义规格'
        }
        speciesList.value.push(obj)
        if (
          props.detailInfo.apiSpeciesTypeDtoList &&
          props.detailInfo.apiSpeciesTypeDtoList.length > 0
        ) {
          form.value.speciesData = cloneDeep(props.detailInfo.apiSpeciesTypeDtoList)
          // 回显规格数据，处理每一项规格的options和自定义规格
          form.value.speciesData.forEach(item => {
            if (item.isCustomize == '1') {
              item.speciesTypeBizId = `customSpecies${
                Date.now() + Math.floor(Math.random() * 1000)
              }`
              item.speciesName = obj.speciesTypeBizId
            } else {
              item.speciesName = item.speciesTypeBizId
            }
            let options = getResidueSpecies()
            // 非自定义规格的options需要从speciesList中获取
            speciesList.value.forEach(item3 => {
              if (item3.speciesTypeBizId == item.speciesTypeBizId) {
                options.unshift(item3)
                item.typeCode = item3.typeCode
              }
            })

            item.apiSpeciesSettingDtoList.forEach((item2, index2) => {
              item2.speciesTypeBizId = item.speciesTypeBizId
              item2.speciesId = item2.speciesSettingBizId
              item2.typeCode = item.typeCode
              if (index2 == item.apiSpeciesSettingDtoList.length - 1) {
                item2.isAdd = true
              } else {
                item2.isAdd = false
              }
            })
            item.options = options
          })
        }
      } else {
        proxy.$modal.msgError(response.msg)
      }
    }
  )
}
// 获取剩余的规格
function getResidueSpecies() {
  const remainData = speciesList.value.filter(species => {
    // 检查当前规格是否已经在 form.value.speciesList 中
    return !form.value.speciesData.some(item => item.speciesTypeBizId === species.speciesTypeBizId)
  })
  return remainData
}
// 添加规格
function addSpecies() {
  const residueSpecies = cloneDeep(getResidueSpecies())

  if (residueSpecies.length > 1) {
    const newSpecies = residueSpecies[0]
    let speciesId = Date.now() + Math.floor(Math.random() * 1000)
    newSpecies.speciesName = newSpecies.speciesTypeBizId
    newSpecies.options = cloneDeep(residueSpecies)
    newSpecies.isCustomize = '0'
    //因为只有第一个规格需要添加图片，所以这里先判断一下，如果长度为0，则添加图片
    if (form.value.speciesData.length == 0) {
      newSpecies.isIllustration = '1'
      newSpecies.illustrationUrl = ''
    } else {
      newSpecies.isIllustration = '0'
      newSpecies.illustrationUrl = ''
    }
    newSpecies.apiSpeciesSettingDtoList = [
      {
        isIllustration: newSpecies.isIllustration,
        speciesName: newSpecies.speciesName,
        speciesTypeBizId: newSpecies.speciesTypeBizId,
        typeName: newSpecies.typeName,
        speciesId: speciesId,
        isAdd: true,
        isCustomize: '0'
      }
    ]
    form.value.speciesData.push(newSpecies)
  } else {
    // 如果只剩下一个规格，则直接添加自定义规格
    let newObj = {
      speciesTypeBizId: `customSpecies${Date.now() + Math.floor(Math.random() * 1000)}`, //字段表唯一业务ID
      isCustomize: '1', //是否自定义 0-否 1-是
      typeName: ''
    }
    if (form.value.speciesData.length == 0) {
      newObj.isIllustration = '1'
    } else {
      newObj.isIllustration = '0'
    }
    newObj.apiSpeciesSettingDtoList = [
      {
        ...newObj,
        speciesId: Date.now() + Math.floor(Math.random() * 1000),
        isAdd: true
      }
    ]
    form.value.speciesData.push(newObj)
  }

  // 由于新增的时候，规格值会重置，所以需要更新规格下拉框的值
  getNewSpeciesOptions()
}
// 处理规格值得宽度
function getSpeciesMiddleWidth(species, item) {
  if (species.isIllustration == '1' && item.apiSpeciesSettingDtoList.length < 2) {
    // 有配图，但规格数量只有一个
    return '92%'
  } else if (species.isIllustration == '0' && item.apiSpeciesSettingDtoList.length > 1) {
    // 无配图，但规格数量有多个
    return '92%'
  } else if (species.isIllustration == '0' && item.apiSpeciesSettingDtoList.length == 1) {
    // 无配图，但规格数量只有一个
    return '100%'
  } else if (species.isIllustration == '1' && item.apiSpeciesSettingDtoList.length > 1) {
    // 有配图，但规格数量有多个
    return '84%'
  } else {
    return '100%'
  }
}
// 规格上传图片前得校验
function handleBeforeUpload(file) {
  const isLt = file.size / 1024 / 1024 < 2
  if (!isLt) {
    proxy.$modal.msgError(`上传文件大小不能超过 2 MB!`)
    return false
  }
  return true
}
// 规格上传图片成功
const handleUploadSuccess = (res, file, species) => {
  if (res.code == 200) {
    form.value.speciesData.forEach(item => {
      if (item.speciesTypeBizId == species.speciesTypeBizId) {
        item.apiSpeciesSettingDtoList.forEach(item2 => {
          if (item2.speciesId == species.speciesId) {
            item2.illustrationUrl = res.data.url
          }
        })
      }
    })
  }
}
// 添加规格值
const speciesInputChange = (species, sIndex) => {
  let speciesObj = { ...species }
  // 添加规格值
  let speciesId = Date.now() + Math.floor(Math.random() * 1000)
  let newSpeciesValue = {
    speciesId: speciesId,
    speciesTypeBizId: speciesObj.speciesTypeBizId,
    isAdd: true,
    value: '',
    typeName: speciesObj.typeName,
    isCustomize: speciesObj.isCustomize
  }
  if (species.isIllustration == '1') {
    newSpeciesValue.isIllustration = '1'
    newSpeciesValue.illustrationUrl = ''
  } else {
    newSpeciesValue.isIllustration = '0'
    newSpeciesValue.illustrationUrl = ''
  }
  form.value.speciesData.forEach((item, index) => {
    if (item.speciesTypeBizId == speciesObj.speciesTypeBizId) {
      item.apiSpeciesSettingDtoList.forEach((item2, i) => {
        if (item2.speciesId == speciesObj.speciesId && item2.isAdd) {
          item.apiSpeciesSettingDtoList.push(newSpeciesValue)
          item2.isAdd = false
        }
      })
    }
  })
}
// 配图开关切换
const switchBeforeChange = obj => {
  return false
}
// 配图开关
const switchChange = (obj, type) => {
  form.value.speciesData.forEach((item, index) => {
    if (item.speciesTypeBizId == obj.speciesTypeBizId) {
      if (type == 'close') {
        if (obj.isIllustration == '0') {
          item.isIllustration = '1'
        } else if (obj.isIllustration == '1') {
          item.isIllustration = '0'
        }
      } else {
        item.isIllustration = obj.isIllustration
      }

      item.apiSpeciesSettingDtoList.forEach((item2, i) => {
        item2.isIllustration = item.isIllustration
        if (item.isIllustration == '0') {
          item2.illustrationUrl = ''
        }
      })
    }
  })
}
// 规格下拉框切换
const changeSpeciesSelect = (obj, index) => {
  //自定义规格只是把当前的规格给替换掉，并不是新增，写到这里了
  let slefObj = { ...obj }
  let newForm = { ...form.value }

  const sameItem = speciesList.value.filter(item => {
    if (item.speciesTypeBizId == slefObj.speciesName) {
      return item
    }
  })
  //更新form里对应的数据
  newForm.speciesData.forEach((item, i) => {
    let newSpecies = {}
    if (item.speciesTypeBizId == slefObj.speciesTypeBizId) {
      if (slefObj.speciesName.includes('customSpecies')) {
        // 如果是自定义的要把自定义的数据替换成新的，
        item.speciesTypeBizId = `customSpecies${Date.now() + Math.floor(Math.random() * 1000)}`
        item.typeName = ''
        item.isCustomize = '1'
        newSpecies = { ...item }
      } else {
        item.isCustomize = '0'
        item.speciesTypeBizId = slefObj.speciesName
        item.typeName = sameItem[0].typeName
        newSpecies = { ...sameItem[0] }
      }
      if (index == 0) {
        newSpecies.isIllustration = '1'
      } else {
        newSpecies.isIllustration = '0'
      }
      item.apiSpeciesSettingDtoList = [
        { ...newSpecies, speciesId: Date.now() + Math.floor(Math.random() * 1000), isAdd: true }
      ]
    }
  })
  form.value = newForm
  // 由于规格下拉框切换的时候，规格值会重置，所以需要更新规格下拉框的值
  getNewSpeciesOptions()
}
// 得到最新的规格下拉框数据
const getNewSpeciesOptions = () => {
  const remainSpeciesOptins = getResidueSpecies()

  if (remainSpeciesOptins.length > 0) {
    form.value.speciesData.forEach(item => {
      if (item.options) {
        let newOptions = cloneDeep(remainSpeciesOptins)
        item.options.forEach(option => {
          if (item.speciesTypeBizId == option.speciesTypeBizId) {
            newOptions.unshift(option)
          }
        })
        item.options = newOptions
      } else {
        item.speciesName = remainSpeciesOptins[0].speciesTypeBizId
        item.options = remainSpeciesOptins
      }
    })
  }
}
// 改变规格自定义名字得时候，规格值得typeName要同步
const changCustomSpecies = obj => {
  let newObj = { ...obj }
  // 自定义规格的时候要看一下有没有重复的，如果有重复的就加错误信息，没有重复的就清空错误信息
  let repeat = form.value.speciesData.filter(item => item.typeName == newObj.typeName)
  form.value.speciesData.forEach((item, index) => {
    if (item.speciesTypeBizId == newObj.speciesTypeBizId) {
      if (repeat.length > 1) {
        item.errorMsg = '规格名称不能重复'
      } else if (!newObj.typeName && item.apiSpeciesSettingDtoList[0].value) {
        item.errorMsg = '规格名称不能为空'
      } else {
        item.errorMsg = ''
      }
      item.apiSpeciesSettingDtoList.forEach((item2, i) => {
        item2.typeName = newObj.typeName
      })
    }
  })
}
// 删除规格
const deleteSpecies = obj => {
  let slefObj = { ...obj }
  form.value.speciesData.forEach((item, index) => {
    if (item.speciesTypeBizId == slefObj.speciesTypeBizId) {
      form.value.speciesData.splice(index, 1)
    }
  })
  if (form.value.speciesData.length > 0) {
    form.value.speciesData[0].isIllustration = '1'
    form.value.speciesData[0].apiSpeciesSettingDtoList.forEach((item2, i) => {
      item2.isIllustration = '1'
    })
  }
}
// 删除规格值
const deleteSpeciesValue = obj => {
  let slefObj = { ...obj }
  form.value.speciesData.forEach((item, index) => {
    if (item.speciesTypeBizId == slefObj.speciesTypeBizId) {
      item.apiSpeciesSettingDtoList.forEach((item2, i2) => {
        if (item2.speciesId == slefObj.speciesId) {
          item.apiSpeciesSettingDtoList.splice(i2, 1)
        }
      })
    }
  })
}
//规格设置下拉框
const getSpeciesSelect = () => {
  speciesSelectList.value = []
  let newArray = cloneDeep(form.value.speciesData)
  newArray.forEach(item => {
    if (item.typeName && item.apiSpeciesSettingDtoList[0].value) {
      let newOptions = item.apiSpeciesSettingDtoList.filter(item2 => {
        return item2.value
      })
      newOptions.unshift({
        value: `全部${item.typeName}`,
        speciesId: item.speciesTypeBizId,
        type: 'all'
      })
      item.options = newOptions
      speciesSelectList.value.push(item)
    }
  })
}

// 初始化选中状态，默认选中"全部"
const initSelectedValues = () => {
  speciesSelectList.value.forEach(item => {
    // 找到"全部"选项，类型为'all'
    const allOption = item.options.find(opt => opt.type === 'all')
    if (allOption) {
      selectedValues.value[item.speciesTypeBizId] = allOption.speciesId
    }
  })
}
// 批量设置价格和库存
const handleBatchSet = () => {
  if (!batchPrice.value && !batchInventory.value) {
    proxy.$modal.msgError('请输入价格或库存')
    return
  }

  // 获取当前选中的规格值
  const currentSelections = {}
  speciesSelectList.value.forEach(item => {
    const speciesTypeBizId = item.speciesTypeBizId
    const selectedValue = selectedValues.value[speciesTypeBizId]
    currentSelections[speciesTypeBizId] = selectedValue
  })

  // 过滤需要更新的表格行
  const filteredRows = tableData.value.filter(row => {
    // 检查每一行是否满足所有规格条件
    return Object.keys(currentSelections).every(speciesTypeBizId => {
      const selectedValue = currentSelections[speciesTypeBizId]

      // 如果选择的是"全部"（speciesId等于speciesTypeBizId）
      if (selectedValue === speciesTypeBizId) {
        // "全部"意味着匹配该规格的所有值
        return true
      }

      // 否则检查具体值是否匹配
      // 通过_id字段来匹配
      const rowSpeciesId = row[`${speciesTypeBizId}_id`]
      return rowSpeciesId === selectedValue
    })
  })

  // 更新匹配的行
  filteredRows.forEach(row => {
    if (batchPrice.value !== '') {
      row.price = Number(batchPrice.value)
    }
    if (batchInventory.value !== '') {
      row.inventory = Number(batchInventory.value)
    }
  })
  tableData.value.forEach(item => {
    if (!item.price) {
      item.priceErrorMsg = '请输入价格'
    } else {
      item.priceErrorMsg = ''
    }
    if (!item.inventory) {
      item.inventoryErrorMsg = '请输入库存'
    } else {
      item.inventoryErrorMsg = ''
    }
  })
}
// 在生成speciesSelectList后调用
watch(
  () => speciesSelectList.value,
  () => {
    if (speciesSelectList.value.length > 0) {
      initSelectedValues()
    }
  },
  { immediate: true, deep: true }
)
// 生成所有规格组合（笛卡尔积）
const generateAllCombinations = specs => {
  if (specs.length === 0) return []

  const result = []
  const firstSpec = specs[0]

  const restSpecs = specs.slice(1)

  // 如果还有剩余的规格，递归生成剩余规格的组合
  const restCombinations = restSpecs.length > 0 ? generateAllCombinations(restSpecs) : [{}]

  // 遍历第一个规格的每个值
  for (let valueObj of firstSpec.apiSpeciesSettingDtoList) {
    // 跳过空值（新增的空白项）
    if (valueObj.value === '') continue

    for (let restComb of restCombinations) {
      let row = {
        // 存储每个规格的值和ID
        [firstSpec.speciesTypeBizId]: valueObj.value,
        [`${firstSpec.speciesTypeBizId}_id`]: valueObj.speciesId,
        speciesId: valueObj.speciesId,
        speciesTypeBizId: firstSpec.speciesTypeBizId,
        // 存储规格信息用于合并计算
        _specs: {
          [firstSpec.speciesTypeBizId]: {
            value: valueObj.value,
            typeName: firstSpec.typeName,
            isIllustration: firstSpec.isIllustration,
            speciesId: firstSpec.speciesId,
            speciesTypeBizId: firstSpec.speciesTypeBizId,
            isCustomize: firstSpec.isCustomize
          }
        }
      }

      // 添加剩余规格的值
      for (let spec of restSpecs) {
        row[spec.speciesTypeBizId] = restComb[spec.speciesTypeBizId]
        row[`${spec.speciesTypeBizId}_id`] = restComb[`${spec.speciesTypeBizId}_id`]
        row._specs[spec.speciesTypeBizId] = {
          value: restComb[spec.speciesTypeBizId],
          typeName: spec.typeName,
          isIllustration: spec.isIllustration,
          illustrationUrl: spec.illustrationUrl || '',
          isCustomize: spec.isCustomize,
          speciesTypeBizId: spec.speciesTypeBizId
        }
        if (!spec.speciesTypeBizId.includes('customSpecies')) {
          row._specs[spec.speciesTypeBizId].speciesTypeBizId = spec.speciesTypeBizId
        }
      }

      // 生成组合ID
      const comboId = specs.map(spec => row[`${spec.speciesTypeBizId}_id`]).join('_')
      row.comboId = comboId

      // 如果有存储的数据，使用存储的数据
      if (comboData.value[comboId]) {
        row = { ...row, ...comboData.value[comboId] }
      } else {
        // 默认值
        row.price = 0
        row.inventory = 0
        row.status = '1' // 1:上架, 0:下架
        row.illustrationUrl = ''
      }

      if (valueObj.isIllustration && valueObj.isIllustration == '1') {
        row.isIllustration = valueObj.isIllustration
      }
      if (valueObj.illustrationUrl) {
        row.illustrationUrl = valueObj.illustrationUrl
      }
      if (valueObj.speciesId) {
        row.speciesId = valueObj.speciesId
      }
      result.push(row)
    }
  }
  return result
}

// 生成表格列配置
const generateTableColumns = specs => {
  const columns = []

  // 动态规格列
  specs.forEach(spec => {
    if (spec.typeName) {
      columns.push({
        prop: spec.speciesTypeBizId,
        label: spec.typeName,
        isSpec: true
      })
    }
  })

  return columns
}
// 计算合并单元格
const computeSpans = (data, specs) => {
  const spans = []
  let pos = 0

  // 初始化
  for (let i = 0; i < data.length; i++) {
    spans[i] = []
    for (let j = 0; j < specs.length; j++) {
      spans[i][j] = { rowspan: 1, colspan: 1 }
    }
  }

  // 对每个规格列进行处理
  for (let j = 0; j < specs.length; j++) {
    const specId = specs[j].speciesTypeBizId
    let startRow = 0

    for (let i = 1; i <= data.length; i++) {
      // 需要比较当前行和上一行的值，以及前面规格的值
      let same = true
      for (let k = 0; k <= j; k++) {
        const prevSpecId = specs[k].speciesTypeBizId
        if (i < data.length && data[i][prevSpecId] !== data[i - 1][prevSpecId]) {
          same = false
          break
        }
      }

      if (i === data.length || !same) {
        // 从startRow到i-1行合并
        for (let k = startRow; k < i; k++) {
          if (k === startRow) {
            spans[k][j].rowspan = i - startRow
          } else {
            spans[k][j].rowspan = 0
            spans[k][j].colspan = 0
          }
        }
        startRow = i
      }
    }
  }

  return spans
}

// 合并单元格方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  let newArray = cloneDeep(form.value.speciesData)
  const specs = newArray.filter(item => item.typeName && item.apiSpeciesSettingDtoList[0].value)

  if (columnIndex < specs.length && spans.value[rowIndex]) {
    return [spans.value[rowIndex][columnIndex].rowspan, spans.value[rowIndex][columnIndex].colspan]
  }
  return [1, 1]
}
const spans = ref([])

// 生成表格数据
const generateTable = () => {
  tableColumns.value = []
  let newArray = cloneDeep(form.value.speciesData)
  const specs = newArray.filter(item => item.typeName && item.apiSpeciesSettingDtoList[0].value)
  // 生成列
  tableColumns.value = generateTableColumns(specs)

  // 生成行数据
  tableData.value = generateAllCombinations(specs)

  // 计算合并单元格
  spans.value = computeSpans(tableData.value, specs)

  if (isSettingSpeciesPrice.value) {
    // 刚进来的时候，要根据详情中的apiSpeciesPriceDtoList去更新tableData中的价格和库存
    let apiSpeciesPriceDtoList = cloneDeep(props.detailInfo.apiSpeciesPriceDtoList)
    tableData.value.forEach((item1, index1) => {
      apiSpeciesPriceDtoList.forEach((item2, index2) => {
        if (index1 == index2) {
          item1.status = String(item2.status)
          item1.illustrationUrl = item2.illustrationUrl
          item1.inventory = item2.inventory
          item1.price = item2.price
        }
      })
    })
    isSettingSpeciesPrice.value = false
  }
}
// 监听规格数据变化
watch(
  () => form.value.speciesData,
  (newVal, oldVal) => {
    // 更新规格表格数据
    generateTable()
    //设置规格设置下拉框
    getSpeciesSelect()
  },
  { deep: true }
)
// ===========产品规格与库存相关操作结束===========

// ===========产品参数相关操作开始===========
const deleteParams = (item, index) => {
  form.value.apiAttributeSettingDtoList.splice(index, 1)
  // 还要处理每一项的leftOptions
  getNewLeftOptions()
}
const deleteCustomParams = (item, index) => {
  form.value.apiAttributeSettingDtoList.splice(index, 1)
}
const addParams = changeItem => {
  let changeParam = { ...changeItem }
  // 不要随意切换代码位置，会出现时机问题，会出现bug
  // 正确的筛选逻辑：过滤出 form.value.apiAttributeSettingDtoList 中不存在的参数
  const remainParams = getRemainData()
  // 因为最后一个是自定义参数，所以加参加到最后一个直接走自定义参数的逻辑
  if (!(changeParam.name && changeParam.name.includes('custom')) && remainParams.length > 1) {
    // 按照 paramsList.value 的顺序，只添加第一个未添加的参数
    form.value.apiAttributeSettingDtoList.push({
      ...remainParams[0],
      isCustomize: '0',
      leftOptions: remainParams, // 所有剩余参数作为 leftOptions
      name: remainParams[0].fieldBizId
    })
    // 还要处理每一项的leftOptions
    getNewLeftOptions()
  } else {
    let leftOptions = getRemainData()
    // 因为这里添加自定义参数的时候，需要把之前的自定义参数先删除，在增加新的自定义参数，这样左侧的下拉框中的才能对应上
    leftOptions.splice(leftOptions.length - 1, 1)
    let fieldBizId = `custom${Date.now() + Math.floor(Math.random() * 1000)}`
    // 如果没有剩余参数，则添加自定义参数
    const customParam = {
      productLaunchBizId: route.query.productLaunchBizId, //产品上架信息表唯一业务ID
      fieldBizId: fieldBizId, //字段表唯一业务ID
      fieldValueBizId: '', //字段值表唯一业务ID
      name: '', //字段名称
      value: '', //字段值
      isCustomize: '1', //是否自定义 0-否 1-是
      fieldCnName: '自定义参数',
      customValue: fieldBizId //自定义值
    }
    leftOptions.push(customParam)
    customParam.leftOptions = leftOptions
    form.value.apiAttributeSettingDtoList.push(customParam)

    // 还要处理每一项的leftOptions,自定义的参数不需要处理,先暂时不处理，先放在这，需要处理的
    // let remainLeftOptins = getRemainData().map(item => {
    //   if (!item.isCustomize) return item
    // })
    // remainLeftOptins.push(customParam)
    // if (remainLeftOptins.length > 0) {
    //   form.value.apiAttributeSettingDtoList.forEach(item => {
    //     if (item.leftOptions && !item.isCustomize) {
    //       let newOptions = JSON.parse(JSON.stringify(remainLeftOptins))
    //       item.leftOptions.forEach(option => {
    //         if (item.fieldBizId == option.fieldBizId) {
    //           newOptions.unshift(option)
    //         }
    //       })
    //       item.leftOptions = newOptions
    //     }
    //   })
    // }
  }
  // 处理必填提示
  paramsErr()
}
// 给产品参数加必填提示
const paramsErr = () => {
  let errorList = []
  form.value.apiAttributeSettingDtoList.forEach(item => {
    if (item.isCustomize == '0' && item.value.length == 0) {
      item.fieldCnName = item.leftOptions[0].fieldCnName
      item.errorMsg = `参数${item.fieldCnName}为必填项`
      errorList.push({ msg: item.errorMsg })
    } else if (item.isCustomize == '1') {
      if (!item.name && !item.value) {
        item.errorMsg = `参数名称不能为空，参数值不能为空`
        errorList.push({ msg: item.errorMsg })
      } else if (!item.name) {
        item.errorMsg = `参数名称不能为空`
        errorList.push({ msg: item.errorMsg })
      } else if (!item.value) {
        item.errorMsg = `参数值不能为空`
        errorList.push({ msg: item.errorMsg })
      } else {
        item.errorMsg = ``
      }
    } else {
      item.errorMsg = ``
    }
  })

  return errorList
}
const getRemainData = () => {
  const remainData = paramsList.value.filter(param => {
    // 检查当前参数是否已经在 form.value.apiAttributeSettingDtoList 中
    return !form.value.apiAttributeSettingDtoList.some(item => item.fieldBizId === param.fieldBizId)
  })
  return remainData
}
const getNewLeftOptions = () => {
  const remainLeftOptins = getRemainData()

  if (remainLeftOptins.length > 0) {
    form.value.apiAttributeSettingDtoList.forEach(item => {
      if (item.leftOptions) {
        let newOptions = cloneDeep(remainLeftOptins)
        item.leftOptions.forEach(option => {
          if (item.fieldBizId == option.fieldBizId) {
            newOptions.unshift(option)
          }
        })
        item.leftOptions = newOptions
      } else {
        let newOptions = cloneDeep(remainLeftOptins)
        let option = cloneDeep(paramsList.value).filter(
          item2 => item.isCustomize == '0' && item2.fieldBizId == item.fieldBizId
        )
        if (option.length > 0) {
          newOptions.unshift(option[0])
        }
        if (item.isCustomize == '1') {
          item.customValue = '自定义参数'
        }
        item.leftOptions = newOptions
      }
    })
  }
}
const changeLeft = (changeItem, index) => {
  const currentItem = cloneDeep(changeItem)
  //如果选择的是自定义参数，则走添加参数的流程
  if (currentItem.name.includes('custom')) {
    // 先删除掉form中的当前项
    if (form.value.apiAttributeSettingDtoList.length > 0) {
      form.value.apiAttributeSettingDtoList.splice(index, 1)
    }
    // 再添加自定义参数
    addParams(currentItem)
    return
  }

  // return
  // 非自定义参数，切换下拉框的值
  // 1.先在 paramsList.value 中查找是否有相同的项
  const identicalItem = paramsList.value.find(item => item.fieldBizId === currentItem.name) //选择的当前项
  // 判断form中fieldBizId和changeItem.fieldBizId，一致就更新掉form中的当前项的数据
  form.value.apiAttributeSettingDtoList.forEach(item => {
    if (item.fieldBizId == currentItem.fieldBizId) {
      item.name = currentItem.name
      for (const key in identicalItem) {
        item[key] = identicalItem[key]
      }
    }
  })
  getNewLeftOptions()
}
const changeCustomLeft = (item, index) => {
  const currentItem = { ...item }
  //如果选择的是自定义参数，则走添加参数的流程
  if (currentItem.customValue.includes('custom')) {
    return
  } else {
    // 先删除掉form中的当前项
    if (form.value.apiAttributeSettingDtoList.length > 0) {
      form.value.apiAttributeSettingDtoList.splice(index, 1)
    }
    // 依据当前选择的customValue，去paramsList中查找对应的项再添加到form中
    const identicalItem = paramsList.value.find(item => item.fieldBizId === currentItem.customValue) //选择的当前项
    identicalItem.name = currentItem.customValue
    identicalItem.leftOptions = getRemainData()
    form.value.apiAttributeSettingDtoList.push(identicalItem)
    // 还要处理每一项的leftOptions
    getNewLeftOptions()
  }
}
/** 获取产品参数信息 */
function getProductParamsInfo() {
  productParams({ objectBizIdList: form.value.apiProductLaunchDto.categoryBizIdList }).then(
    response => {
      if (response.code == 200) {
        // 应该做获取右侧的下拉框值了
        paramsList.value = []
        form.value.apiAttributeSettingDtoList = []
        paramsList.value = response.data
        const fieldBizIdList = response.data.map(item => item.fieldBizId)

        if (paramsList.value.length > 0) {
          paramsList.value.forEach(item => {
            item.isCustomize = '0'
          })
        }
        paramsList.value.push({
          productLaunchBizId: route.query.productLaunchBizId, //产品上架信息表唯一业务ID
          fieldBizId: `custom${Date.now() + Math.floor(Math.random() * 1000)}`, //字段表唯一业务ID
          fieldValueBizId: '', //字段值表唯一业务ID
          name: '', //字段名称
          value: '', //字段值
          isCustomize: '1', //是否自定义 0-否 1-是
          fieldCnName: '自定义参数'
        })
        // 赋值
        if (props.detailInfo.apiAttributeSettingDtoList.length == 0) {
          if (paramsList.value.length == 0) {
            form.value.apiAttributeSettingDtoList.push({
              ...paramsList.value[0],
              leftOptions: paramsList.value,
              name: '',
              customValue: paramsList.value[0].fieldBizId
            })
          }
          // else {
          //   form.value.apiAttributeSettingDtoList.push({
          //     ...paramsList.value[0],
          //     leftOptions: paramsList.value,
          //     name: paramsList.value[0].fieldBizId
          //   })
          // }
        } else {
          // 回显的时候没有leftOptions和middleOptions，需要赋值
          form.value.apiAttributeSettingDtoList = cloneDeep(
            props.detailInfo.apiAttributeSettingDtoList
          )
          form.value.apiAttributeSettingDtoList.forEach(item => {
            if (item.isCustomize == '0' && item.textBoxType !== 'multipleSelect') {
              item.name = item.fieldBizId
              if (item.fieldValueBizId) {
                item.value = item.fieldValueBizId
              }
            }

            if (item.textBoxType == 'multipleSelect') {
              item.value = item.value.split(';')
            }
          })
        }
        getNewLeftOptions()
        RightParamsOptionList(fieldBizIdList)
      } else {
        proxy.$modal.msgError(response.msg)
      }
    }
  )
}
/** 获取产品参数右侧汇总options */
function RightParamsOptionList(fieldBizIdList) {
  ParamRightOptions({ fieldBizIdList }).then(response => {
    if (response.code == 200) {
      SummaryRightOptions.value = response.data
      paramsList.value.forEach(item => {
        SummaryRightOptions.value.forEach(item2 => {
          if (item.fieldBizId == item2.fieldBizId) {
            item.middleOptions = item2.fieldValueListResponseList
          }
        })
      })
      form.value.apiAttributeSettingDtoList.forEach(item => {
        SummaryRightOptions.value.forEach(item2 => {
          if (item.fieldBizId == item2.fieldBizId) {
            item.middleOptions = item2.fieldValueListResponseList
          }
        })
      })
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}
// ===========产品参数相关操作结束===========
const handleFileChange = info => {
  if (info.source == 'main') {
    imageInfo.value = cloneDeep(info)
    form.value['apiProductLaunchDto'].mainUrlsList = info.fileList.map(item => item.url)
  } else if (info.source == 'sub') {
    subImageInfo.value = cloneDeep(info)
    form.value['apiProductLaunchDto'].detailUrlsList = info.fileList.map(item => item.url)
  }
}

const handleSelectChange = () => {
  if (
    form.value['apiProductLaunchDto'].title &&
    form.value['apiProductLaunchDto'].title.length < 5
  ) {
    showNameTip.value = true
  } else if (!form.value['apiProductLaunchDto'].title) {
    showNameTip.value = true
  } else {
    showNameTip.value = false
  }
}

/** 查询产品列表 */
function searchProduct(query) {
  let productName = query ? query.trim() : ''

  let data = {
    productName: productName,
    pageSize: showOnce.value ? 9999 : 10,
    pageNo: 1
  }
  getProductList(data).then(response => {
    if (response.code === 200) {
      productList.value = response.data.records
      if (showOnce.value) {
        allProductList.value = response.data.records
        showOnce.value = false
        console.log('allProductList.value', allProductList.value)
      }
    } else {
      productList.value = []
      proxy.$modal.msgError(response.msg)
    }
  })
}

// ===========基础信息相关操作开始===========
const selectCategoryData = ref([]) //已经选择的分类数据
const categoryDialogOpen = ref(false) //已经选择的分类数据
const categoryRef = ref(null)
// 选择的分类名称
const categoryName = computed(() => {
  let result = []
  selectCategoryData.value.forEach(item => {
    item.data.forEach(c => {
      if (c.isSelected) result.push(c.name)
    })
  })

  if (result.length > 0) {
    return result.join(' > ')
  } else {
    return ''
  }
})
/** 查询已经选中的分类列表 */
function getSelectCategory() {
  let data = {
    objectBizId: form.value['apiProductLaunchDto'].productLaunchBizId,
    type: 'PRODUCT'
  }
  querySelectCategory(data).then(response => {
    if (response.code === 200) {
      response.data = response.data.map(item => {
        item.data = item.selectedResponseList
        return item
      })
      selectCategoryData.value = response.data
    } else {
      selectCategoryData.value = []
      proxy.$modal.msgError(response.msg)
    }
  })
}
const categoryConfirm = () => {
  selectCategoryData.value = categoryRef.value.categoryList
  categoryDialogOpen.value = false
}
// ===========基础信息相关操作结束===========
/** 上架产品 保存接口*/
function submitProduct() {
  let submitObj = {}
  errorList.value = []
  // 产品
  // 类目信息form.value['apiProductLaunchDto'].categoryBizIdList对应的是   selectCategoryData
  if (!form.value['apiProductLaunchDto'].title) {
    errorList.value.push({ msg: '标题信息过少，请至少输入5个有效字数（含中文、英文、数字）' })
  }

  // 处理图片
  if (
    !form.value['apiProductLaunchDto'].mainUrlsList ||
    form.value['apiProductLaunchDto'].mainUrlsList.length == 0
  ) {
    errorList.value.push({ msg: '请上传至少三张产品主图' })
  }
  if (
    !form.value['apiProductLaunchDto'].detailUrlsList ||
    form.value['apiProductLaunchDto'].detailUrlsList.length == 0
  ) {
    errorList.value.push({ msg: '请上传至少一张产品详情图' })
  }

  //处理产品参数
  let paramsErrors = paramsErr()
  if (paramsErrors.length > 0) {
    errorList.value.push(...paramsErrors)
  }
  // 处理产品参数
  let apiAttributeSettingDtoList = cloneDeep(form.value.apiAttributeSettingDtoList)

  apiAttributeSettingDtoList.forEach(item => {
    if (!item.isCustomize) {
      item.isCustomize = '0'
    }
    if (item.leftOptions) {
      item.leftOptions.forEach(item2 => {
        if (item.name == item2.fieldBizId) {
          item.name = item2.fieldCnName
        }
      })
    }
    if (item.middleOptions) {
      item.middleOptions.forEach(item2 => {
        if (item.value == item2.fieldValueBizId) {
          item.fieldValueBizId = item2.fieldValueBizId
          item.value = item2.value
        }
      })
    }
    if (item.textBoxType == 'multipleSelect') {
      item.value = item.value.join(';')
    }
    item.productLaunchBizId = form.value['apiProductLaunchDto'].productLaunchBizId
    delete item.leftOptions
    delete item.middleOptions
  })
  // 处理产品规格和库存
  // 处理规格列表
  let apiSpeciesSettingDtoList = []
  let newData = cloneDeep(form.value.speciesData)
  if (newData.length == 0) {
    proxy.$modal.msgError('请添加产品规格')
    return
  }
  newData.forEach(item => {
    if (item.errorMsg) {
      errorList.value.push({ msg: item.errorMsg })
    }
    item.apiSpeciesSettingDtoList.forEach(item2 => {
      item2.productLaunchBizId = form.value['apiProductLaunchDto'].productLaunchBizId
      if (item2.isCustomize == '1' && item2.value) {
        apiSpeciesSettingDtoList.push({
          typeName: item2.typeName,
          value: item2.value,
          isIllustration: item2.isIllustration,
          illustrationUrl: item2.illustrationUrl,
          isCustomize: item2.isCustomize,
          productLaunchBizId: form.value['apiProductLaunchDto'].productLaunchBizId
        })
      } else if (item2.isCustomize == '0' && item2.value) {
        apiSpeciesSettingDtoList.push(item2)
      }
    })
  })

  // 处理价格库存列表
  let apiSpeciesPriceDtoList = []
  tableData.value.forEach(item => {
    if (!item.price) {
      item.priceErrorMsg = '请输入价格'
    } else {
      item.priceErrorMsg = ''
    }
    if (!item.inventory) {
      item.inventoryErrorMsg = '请输入库存'
    } else {
      item.inventoryErrorMsg = ''
    }
    if (!item.price || !item.inventory) {
      errorList.value.push({ msg: item.priceErrorMsg || item.inventoryErrorMsg })
    }
  })
  let newPrice = cloneDeep(tableData.value)

  newPrice.forEach(item => {
    item.apiSpeciesSettingDtoList = []
    for (let key in item._specs) {
      speciesList.value.forEach(spec => {
        if (spec.speciesTypeBizId == key) {
          item._specs[key].typeCode = spec.typeCode
        }
      })
      item.apiSpeciesSettingDtoList.push(item._specs[key])
    }
    apiSpeciesPriceDtoList.push({
      productLaunchBizId: form.value['apiProductLaunchDto'].productLaunchBizId,
      price: item.price, //价格
      inventory: item.inventory, //库存
      illustrationUrl: item.illustrationUrl, //配图url
      status: item.status, //状态：0=下架，1=上架
      apiSpeciesSettingDtoList: item.apiSpeciesSettingDtoList
    })
  })
  if (errorList.value.length > 0) {
    errorDialogOpen.value = true
    return
  } else {
    errorDialogOpen.value = false
  }
  // 处理类目数据
  form.value['apiProductLaunchDto'].categoryBizIdList = []
  selectCategoryData.value.forEach(item => {
    if (item.data) {
      item.data.forEach(item2 => {
        if (item2.isSelected) {
          form.value['apiProductLaunchDto'].categoryBizIdList.push(item2.categoryBizId)
        }
      })
    }
  })
  // 处理平台数据
  let projectBizIdList = []
  choosePlatformList.value.forEach(item => {
    projectBizIdList.push(item.projectBizId)
  })
  form.value['apiProductLaunchDto'].projectBizIdList = projectBizIdList

  // 处理定期开售
  if (form.value['apiProductLaunchDto'].isTiming == '0') {
    form.value['apiProductLaunchDto'].releaseDate = ''
    form.value['apiProductLaunchDto'].isHiddenPrice = ''
  } else if (form.value['apiProductLaunchDto'].isTiming == '1') {
    form.value['apiProductLaunchDto'].isHiddenPrice = form.value['apiProductLaunchDto']
      .isHiddenPrice
      ? '1'
      : '0'
  }
  // 处理限购
  if (form.value['apiProductLaunchDto'].isPurchaseLimit == '0') {
    form.value['apiProductLaunchDto'].limitDateUnit = ''
    form.value['apiProductLaunchDto'].limitQuantity = ''
  }
  submitObj.apiAttributeSettingDtoList = apiAttributeSettingDtoList
  submitObj.apiSpeciesSettingDtoList = apiSpeciesSettingDtoList
  submitObj.apiSpeciesPriceDtoList = apiSpeciesPriceDtoList
  submitObj.apiProductLaunchDto = form.value['apiProductLaunchDto']
  if (route.query.source && route.query.source == 'copy') {
    submitObj.source = 1
  } else {
    submitObj.source = null
  }
  if (form.value['apiProductLaunchDto'].title) {
    allProductList.value.forEach(item => {
      if (item.productBizId == form.value['apiProductLaunchDto'].title) {
        submitObj.apiProductLaunchDto.title = item.productName
        submitObj.apiProductLaunchDto.productBizId = item.productBizId
      }
    })
  }
  // return
  saveProductLaunch(submitObj).then(response => {
    if (response.code === 200) {
      if (route.query.source && route.query.source == 'copy') {
        proxy.$modal.msgSuccess('产品复制成功')
        emit('handleSuccess', 'baseInfo', response.data)
      } else {
        proxy.$modal.msgSuccess('产品上架成功')
        emit('handleSuccess', 'baseInfo')
      }
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}
watch(
  () => props.detailInfo,
  newVal => {
    if (newVal) {
      form.value.apiProductLaunchDto = cloneDeep(newVal.apiProductLaunchDto)
      imageInfo.value.count = form.value['apiProductLaunchDto'].mainUrlsList.length
      subImageInfo.value.count = form.value['apiProductLaunchDto'].detailUrlsList.length
      // 给平台赋值
      if (form.value['apiProductLaunchDto'].apiProjectDtoList) {
        choosePlatformList.value = cloneDeep(form.value['apiProductLaunchDto'].apiProjectDtoList)
        // 更新已选择的ID集合
        selectedPlatformIds.value = new Set(choosePlatformList.value.map(item => item.projectBizId))
      }
      if (newVal.apiSpeciesPriceDtoList.length > 0) {
        isSettingSpeciesPrice.value = true
      }
      if (form.value['apiProductLaunchDto'].isHiddenPrice) {
        form.value['apiProductLaunchDto'].isHiddenPrice =
          form.value['apiProductLaunchDto'].isHiddenPrice == '1' ? true : false
      }

      getSelectCategory() // 获取已经选中的分类
      /**
       * 参数操作：
       * 1.先拿到所有参数信息，默认只展示参数列表的第一个，用拿到的所有参数的fieldBizId去请求所有右侧下拉框的options
       * 2.第一个参数列表的options也就是左侧的下拉框是参数列表的所有数据，当选了某一个option,下拉框里就没有当前选择的这个option了
       * 3.当点击添加参数时，左侧下拉框是除了已经添加的参数外的paramsList外剩余的参数，右侧下拉框是当前参数对应的options
       * 回显注意：
       * 4.当回显的时候需要依据详情的值对form进行赋值,这一步还未做，等做编辑的时候再做
       */
      getProductParamsInfo()
      /**
       * 产品规格操作
       * 1.先拿到所有规格信息，创建新规格默认只展示规格列表的第一个
       */
      getProductSpeciesInfo()
      showOnce.value = true
      searchProduct()
    }
  }
)
watch(
  () => props.activeName,
  newVal => {
    if (newVal == 'baseInfo') {
      // searchProduct()
    }
  }
)
</script>
<style lang="scss" scoped>
.baseBox {
  width: 100%;
  box-sizing: border-box;
  height: 100%;
  /* background-color: rgb(247 247 247) !important; */
  /* padding: 0 !important; */
  /* height: 500px !important;
  overflow: hidden;
  overflow-y: scroll; */
}
.cardStyle {
  margin-bottom: 20px;
  border: none !important;
}
.cardTitle {
  font-size: 17px;
  font-weight: 600;
}
.chooseClass {
  font-size: 14px;
  margin: 0px 10px;
}
.editTxt {
  font-size: 14px;
  color: #576b95;
}
.colBottomGap {
  margin-bottom: 30px;
}
.form-content {
  width: 100%;
  box-sizing: border-box;
  height: 73vh;
  overflow: hidden;
  overflow-y: scroll;
  padding: 10px 10px;
}
.form-content :deep(.el-card) {
  border: none !important;
}
.formHeader {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: 600;
}
.nameTip {
  font-size: 13px;
  margin-top: 10px;
}
.tipCon {
  /* width: 450px; */
  width: fit-content;
  /* 为了更好的兼容性，可以加上带前缀的版本 */
  width: -moz-fit-content;
  width: -webkit-fit-content;
  margin: 5px 0;
  padding: 10px 10px;
  border-radius: 5px;
  background-color: rgb(247 247 247);
  font-size: 14px;
  display: flex;
  align-items: center;
  span {
    color: rgb(111 111 111);
  }
}
.commonHeader {
  font-size: 16px;
  margin-bottom: 15px;
}
.imgTip {
  color: #ccc;
  font-size: 14px;
  margin-bottom: 10px;
}
.classTip {
  color: #ccc;
  font-size: 14px;
}
.bottomBtn {
  border-top: 1px solid rgb(247 247 247);
  width: 100%;
  padding: 10px 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background-color: #fff;
}
.paramsItem {
  display: flex;
  align-items: center;
  border: 1px solid rgb(0 0 0 / 10%);
  border-radius: 3px;
  /* margin-bottom: 20px; */
}
.paramsItem:hover {
  border-color: rgba(64, 158, 255, 1);
}
.paramsLeft {
  border-right: 1px solid rgb(0 0 0 / 10%);
}

.paramsRight {
  border-left: 1px solid rgb(0 0 0 / 10%);
  display: flex;
  align-items: center;
  justify-content: center;
  height: 32px;
  background-color: #f7f7f7;
}
/* 通用：去除 el-select 和 el-input 的外框 */
.paramsItem :deep(.el-input__wrapper) {
  box-shadow: none !important;
}
.paramsItem :deep(.el-select__wrapper) {
  box-shadow: none !important;
}

/* 专门针对 el-select：去除获得焦点时的蓝色外框 */
.paramsItem :deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: none !important;
}

/* 专门针对 el-input：去除获得焦点时的蓝色外框 */
.paramsItem :deep(.el-input .el-input__wrapper.is-focus) {
  box-shadow: none !important;
}
.customMiddle {
  border-left: 1px solid rgb(0 0 0 / 10%);
}
.errorParams {
  background-color: #f7f7f7;
  padding: 10px;
  border-radius: 5px;
  font-size: 14px;
  margin: 10px 0px;
  display: flex;
  align-items: center;
}
.addTxt {
  color: #576b95;
  font-size: 15px;
  display: flex;
  align-items: center;
  margin-top: 20px;
}
.speciesItem {
  background-color: #f7f7f7;
  padding: 10px 20px;
  margin: 15px 0px;
  border-radius: 5px;
}
.speciesTop {
  margin-top: 10px;
}
.imgSwitch {
  color: rgb(0 0 0 / 55%);
  font-size: 14px;
}
.speciesTop {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.speciesTopLeft {
  display: flex;
  /* align-items: center; */
}
.customizeInput {
  margin-left: 20px;
}
.customizeErrorMsg {
  margin-top: 5px;
  font-size: 14px;
  color: #fa5151;
}
.speciesTopRight {
  display: flex;
  align-items: center;
  justify-content: center;
  /* padding: 5px; */
  border-radius: 50%;
  border: 1px solid rgb(0 0 0 / 10%);
  width: 40px;
  height: 40px;
}
.speciesLeft {
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 32px;
}
.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
.speciesSelect {
  margin-bottom: 10px;
  display: flex;
}
.settingBox {
  display: flex;
}
.settingItem {
  width: 220px;
  margin-right: 20px;
}
.settingLeft {
  color: rgb(0 0 0 / 50%);
  font-size: 14px;
  text-align: center;
  width: 25%;
}
.settingRight {
  width: 80%;
}
.errMsg {
  color: #f56c6c;
  font-size: 12px;
}
.moreBox {
  margin-bottom: 20px;
}
.moreTitle {
  font-size: 17px;
  font-weight: 500;
}
.moreItem {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  color: rgb(0 0 0 / 90%);
  margin-top: 10px;
  font-size: 14px;
}
.moreLeft {
  width: 5%;
}
.categoryDialogFooter {
  margin-top: 50px;
}
.errorContent {
  height: 450px;
  overflow-y: scroll;
  /* overflow: hidden; */
}
.errorTitle {
  font-size: 13px;
  color: rgba(0, 0, 0, 50%);
}
.errorItem {
  padding: 10px;
  background-color: #f7f7f7;
  margin: 10px 0px;
  border-radius: 5px;
  width: 100%;
  font-size: 12px;
  display: flex;
  align-items: center;
}
</style>
