<template>
  <div class="mall-section-container">
    <div class="mall-content-section">
      <div class="mall-content-title">
        <!-- <h3>
          <span>{{ typeVal }}{{ giftType === 1 ? '实物' : '虚拟' }}礼品</span>
        </h3> -->
      </div>
      <div class="section" v-loading="submitLoading">
        <el-form
          :model="giftForm"
          :rules="giftRules"
          ref="giftForm"
          label-width="150px"
          class="demo-ruleForm"
          @submit.native.prevent
          label-position="right"
        >
          <div class="section-content">
            <h3>基础信息</h3>
            <el-form-item label="礼品名称" prop="proName">
              <el-input
                v-model.trim="giftForm.proName"
                class="w-600"
                type="text"
                placeholder="请输入礼品名称"
                @input="value => goodsLimit(value)"
              >
                <span slot="suffix">{{ proNameLen }}/30</span>
              </el-input>
            </el-form-item>
            <el-form-item label="礼品主图" required>
              <div class="upload-list-box">
                <div class="drag-box-wrap">
                  <draggable
                    :list="giftForm.images"
                    class="list-group"
                    ghost-class="ghost"
                    @start="dragging = true"
                    @end="dragging = false"
                  >
                    <div v-for="(item, index) in giftForm.images" :key="index" class="img-box">
                      <img width="100%" :src="item.imageUrl" alt>
                      <!-- <i class="el-icon-arrow-left" @click="moveLeft(index)" v-show="index !== 0"></i>
                      <i class="el-icon-arrow-right" @click="moveRight(index)" v-show="index + 1 !== giftForm.images.length"></i> -->
                      <i class="el-icon-delete" @click="deteletDialogImageUrl(index)" />
                      <i class="el-icon-zoom-in" @click="enlargeDialogImageUrl(index)" />
                      <div class="dialog-img" />
                    </div>
                  </draggable>
                  <el-upload
                    ref="giftFormUpload"
                    :limit="5"
                    :on-remove="handleRemove"
                    multiple
                    :file-list="giftFormFileList"
                    :action="uploadAction"
                    :headers="headersUpload"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-exceed="handlePictrueExceed"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess"
                    with-credentials
                    :show-file-list="false"
                    v-show="uploadStatus"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                </div>
                <p style="font-size: 12px; color: rgb(144, 147, 153);line-height:18px;margin-top:10px;">
                  图片建议尺寸 800*800px，格式 jpg/png，大小 1M 以内，你可以拖拽图片调整顺序，最多上传 5 张。
                </p>
                <el-dialog :visible.sync="dialogVisibleImg">
                  <img width="100%" :src="dialogEnlargeImageUrl" alt>
                </el-dialog>
              </div>
            </el-form-item>
            <el-form-item label="礼品分类" prop="proCategoryId">
              <el-select v-model="giftForm.proCategoryId" placeholder="请选择" class="w-300 delete-select">
                <el-option
                  v-for="(v, i) in categoryOptions"
                  :key="i"
                  :label="v.categoryName"
                  :value="v.integralMallCategoryId"
                >
                  <span class="fl">{{ v.categoryName }}</span>
                  <el-button
                    class="fr delete-icon"
                    type="text"
                    @click.stop="deleteCategory(v.integralMallCategoryId)"
                    style="line-height:34px"
                  >
                    <i class="el-icon-error el-icon--right" />
                  </el-button>
                </el-option>
              </el-select>
              <el-button type="text" @click="createCategory">
                新建分类
              </el-button>
            </el-form-item>
            <!-- <el-form-item label="数据对话">
              <dm-activity-select
                :repProjectName="projectName"
                width="300"
                :actId.sync="giftForm.dataDialogueId"
                :showAdd="false"
              />
            </el-form-item> -->
          </div>
          <div class="section-content">
            <h3>销售信息</h3>
            <el-form-item label="礼品规格" v-if="giftType === 1 || submitSkuJson.length">
              <addSku
                :giftId="giftId"
                :skuJson="giftProStandardJson"
                :giftType="giftType"
                @getSpuStock="getSpuStock"
                @getStandradList="getStandradList"
                @getSkuList="getSkuList"
                @IsAgreeUpload="IsAgreeUpload"
                :isStdImg="isStdImg"
                :skuList="skuList"
                @changeMinIntegral="changeMinIntegral"
              />
            </el-form-item>
            <el-form-item label="礼品编码">
              <table class="spu-table">
                <thead>
                  <tr>
                    <th>礼品编码</th>
                    <th style="width:80px">
                      <span class="red-color">*</span>积分
                    </th>
                    <th style="width:80px">
                      <span class="red-color">*</span>现金（元）
                    </th>
                    <th style="width:120px">
                      <span class="red-color">*</span>库存
                    </th>
                    <th style="width:120px">
                      礼品条形码
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td style="width:120px">
                      <!-- 礼品编码 -->
                      <el-input
                        size="small"
                        v-model.trim="giftForm.proCode"
                        placeholder="请输入内容"
                        @input="limitProCode"
                        @blur="limitProCodeType"
                      />
                    </td>
                    <td style="width:120px">
                      <!-- 积分 -->
                      <el-input
                        size="small"
                        v-model.trim="giftForm.integralCost"
                        placeholder="请输入内容"
                        @blur="limitCostType"
                      />
                    </td>
                    <td style="width:120px">
                      <!-- 现金 -->
                      <el-popover
                        popper-class="noClass"
                          v-if="jifenquanxian == true"
                          placement="bottom"
                          trigger="hover"
                          content="无积分购现金权限">
                          <el-input
                          slot="reference"
                            :disabled="jifenquanxian"
                            size="small"
                            v-model.trim="giftForm.cashCost"
                            placeholder="请输入内容"
                            @blur="limitCash"
                          />
                      </el-popover>
                      <el-input
                        v-else
                        size="small"
                        v-model.trim="giftForm.cashCost"
                        placeholder="请输入内容"
                        @blur="limitCash"
                      />
                    </td>
                    <td style="width:120px">
                      <!-- 库存 -->
                      <el-input
                        size="small"
                        v-model.trim="giftForm.virtualStock"
                        placeholder="请输入内容"
                        :disabled="stockDisabled"
                        @blur="limitStock"
                      />
                    </td>
                    <td style="width:120px">
                      <!-- 礼品条形码 -->
                      <el-input
                        size="small"
                        v-model.trim="giftForm.proCodeQuery"
                        placeholder="请输入内容"
                        @input="limintProCodeQuery"
                        @blur="limitproCodeQueryType"
                      />
                    </td>
                  </tr>
                </tbody>
              </table>
            </el-form-item>
            <el-form-item label="礼品成本" prop="costValue">
              <el-input-number
                class="w-350"
                :precision="2"
                :min="0"
                v-model="giftForm.costValue"
                :disabled="costValueStatus"
              />
            </el-form-item>
            <el-form-item label="市场价">
              <el-input-number
                class="w-350"
                :precision="2"
                :min="0"
                :max="9999999"
                v-model="giftForm.marketPrice"
              />
              <el-popover placement="top-start" width="347" trigger="hover">
                <img src="../../../../static/img/eg.png" alt>
                <el-button slot="reference" type="text" style="margin-left:15px;">
                  查看示例
                </el-button>
              </el-popover>
            </el-form-item>
          </div>
          <div class="section-content">
            <h3>图文信息</h3>
            <el-form-item label>
              <div class="tinymce-wrap">
                <tinymce-edit ref="tinymceWrap" :bodyHtml="giftForm.detailDescription" :projectName="projectName" />
              </div>
            </el-form-item>
          </div>

          <div class="section-content">
            <h3>
              可见配置<span class="sub_title">该配置决定客户是否可见</span>
              <el-popover
                placement="right"
                width="670"
                trigger="click"
              >
                <historyData ref="historyData" :form="visibleData" />
                <el-button
                  slot="reference"
                  type="text"
                  style="position: absolute;right: 5%;"
                  v-show="isNew&&(visibleData.useNewStoreWidget==0 || (visibleData.uuid && visibleData.useNewStoreWidget == 1))&&!isCopy"
                >
                  查看当前商品历史配置数据
                </el-button>
              </el-popover>
            </h3>
            <visible-setting
              ref="visibleSetting"
              :form="visibleData"
              @update="isNew = true"
              :isNew="isNew"
            />
          </div>
          <div class="section-content">
            <h3>可兑换配置<span class="sub_title">该配置决定客户是否可以兑换</span></h3>
            <el-form-item label="适用会员" prop="gradeType" v-if="cliqueStatus">
              <el-radio-group v-model="giftForm.gradeType" @change="handleChange">
                <el-radio :label="1">
                  品牌卡
                </el-radio>
                <el-radio :label="2">
                  集团卡
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="memberGrade" :label="cliqueStatus ? '' : '适用会员'">
              <el-select
                v-model="giftForm.memberGrade"
                multiple
                placeholder="请选择"
                size="small"
                class="w-600"
                @change="memberChange"
              >
                <el-option
                  v-for="item in memberGradeList"
                  :key="item.gradeId"
                  :label="item.gradeName"
                  :value="item.gradeId"
                />
              </el-select>
              <span  style="font-size: 12px;color: rgb(144, 147, 153);margin-left:10px;">注意，该字段的配置也会影响到可见配置，请谨慎</span>
            </el-form-item>
            <el-form-item prop="ladder" v-if="specialOrder">
              <el-checkbox-group v-model="giftForm.ladder" @change="changeladder" style="display:inline-block">
                <el-checkbox label="1" :disabled="!giftForm.memberGrade.length">
                  设置阶梯价
                </el-checkbox>
              </el-checkbox-group>
              <el-popover
                placement="bottom"
                width="500"
                trigger="click"
                ref="popover"
              >
                <div style="margin-top:10px;margin-bottom:10px">
                  <span style="color:#303133;font-size:16px">设置阶梯价</span>
                  <span style="color:#606266;font-size:12px;margin-left:20px">*若未设置阶梯价则以原价进行兑换，请勿随意填入0积分/现金；</span>
                </div>
                <el-tabs :value="selectTab" type="border-card" class="card-style">
                  <el-tab-pane
                    :name="index"
                    v-for="(item, index) in ladderMemberGrade"
                    :key="index"
                    :label="item.gradeName"
                    :value="item.gradeId"
                  >
                    <div class="fr" style="margin-bottom:20px" v-if="list3.length && isTable">
                      <el-input
                        class="w-100"
                        placeholder="请输入积分"
                        v-model="integral"
                        size="small"
                      />
                      <el-popover
                        popper-class="noClass"
                          v-if="jifenquanxian == true"
                          placement="bottom"
                          trigger="hover"
                          content="无积分购现金权限">
                          <el-input
                          slot="reference"
                            :disabled="jifenquanxian"
                            class="w-100"
                            placeholder="请输入金额"
                            v-model="cash"
                            size="small"
                          />
                      </el-popover>
                      <el-input
                        v-else
                        class="w-100"
                        placeholder="请输入金额"
                        v-model="cash"
                        size="small"
                      />
                      <el-button type="primary" size="small" @click="handleLadder(list3[index].skuList)">
                        批量填充
                      </el-button>
                    </div>
                    <!-- <el-table v-if="list3.length && isTable" :data="list3.length && isTable ? list3[index].skuList : []"> -->
                    <el-table v-if="isTable" :data="isTable && list3.length ? list3[index].skuList : []">
                      <el-table-column v-for="(it, i) in ladderHeader" :key="i" :label="it.proName">
                        <template slot-scope="{ row }">
                          {{ row.giftPropValues[i].valueName }}
                        </template>
                      </el-table-column>
                      <el-table-column label="积分">
                        <template slot-scope="{ row }">
                          <el-input size="small" v-model.trim="row.giftProSkuIntegral" />
                        </template>
                      </el-table-column>
                      <el-table-column label="现金(元)">
                        <template slot-scope="{ row }">
                          <el-popover
                        popper-class="noClass"
                          v-if="jifenquanxian == true"
                          placement="bottom"
                          trigger="hover"
                          content="无积分购现金权限">
                          <el-input slot="reference"
                            size="small"
                            v-model.trim="row.giftProSkuCash"
                            :disabled="jifenquanxian"/>
                      </el-popover>
                      <el-input size="small" v-model.trim="row.giftProSkuCash" v-else/>
                        </template>
                      </el-table-column>
                    </el-table>
                    <!-- <el-form v-if="list3.length && !isTable"> -->
                    <el-form v-if="!isTable">
                      <el-form-item label="积分">
                        <el-input size="small" v-model.trim="list3[index].skuList[0].giftProSkuIntegral" style="width:180px" />
                      </el-form-item>
                      <el-form-item label="现金">
                        <el-popover
                        popper-class="noClass"
                          v-if="jifenquanxian == true"
                          placement="bottom"
                          trigger="hover"
                          content="无积分购现金权限">
                          <el-input slot="reference"
                          size="small"
                          :disabled="jifenquanxian"
                          v-model.trim="list3[index].skuList[0].giftProSkuCash"
                          style="width:180px" />
                      </el-popover>
                        <el-input v-else
                          size="small"
                          v-model.trim="list3[index].skuList[0].giftProSkuCash"
                          style="width:180px" />&nbsp;&nbsp;元
                      </el-form-item>
                    </el-form>
                  </el-tab-pane>
                </el-tabs>
                <div style="margin-top:10px;text-align:right">
                  <el-button type="default" @click="$refs.popover.showPopper = false">
                    取消
                  </el-button>
                  <el-button type="primary" @click="saveLadderDetail">
                    保存
                  </el-button>
                </div>
                <el-button
                  slot="reference"
                  type="text"
                  v-show="isDifferentialPricing"
                  class="set-ladder"
                  @click="setLadder"
                >
                  点击设置
                </el-button>
              </el-popover>
            </el-form-item>
            <el-form-item label="限兑">
              <el-checkbox v-model="giftForm.limitTimesStatus" @change="refashData()">
                每个会员限制兑换
              </el-checkbox>
              <span v-if="giftForm.limitTimesStatus"> <el-input-number
                controls-position="right"
                v-model="giftForm.limitTimes"
                :precision="0"
                :min="0"
                @change="limitTimeChange"
              />次 </span>
              <span v-show="cardList.length" style="font-size: 12px;color: rgb(144, 147, 153);margin-left:10px;">
                兑换限制不得大于此兑换券的领取次数：
                <i>{{ limitTimesNum }}</i>次
              </span>
            </el-form-item>
            <el-form-item label="兑换日期" required>
              <el-radio v-model="giftForm.exchangeDateType" :label="1">
                全部日期
              </el-radio>
              <el-radio v-model="giftForm.exchangeDateType" :label="2">
                固定日期
              </el-radio>
              <el-radio v-model="giftForm.exchangeDateType" :label="3">
                每月
              </el-radio>
              <el-radio v-model="giftForm.exchangeDateType" :label="4">
                每周
              </el-radio>
              <el-radio v-model="giftForm.exchangeDateType" :label="6">
                生日当日
              </el-radio>
              <el-radio v-model="giftForm.exchangeDateType" :label="5">
                生日当月
              </el-radio>
            </el-form-item>
            <!-- 兑换日期 -->
            <!-- 固定日期 -->

            <el-form-item class="form-item-mt" v-if="giftForm.exchangeDateType === 2" prop="exchangeFixDate">
              <el-date-picker
                class="w-300"
                v-model="giftForm.exchangeFixDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <!-- 每月 -->
            <el-form-item class="form-item-mt" v-if="giftForm.exchangeDateType === 3" prop="exchangeDateDayArr">
              <el-select
                size="small"
                v-model="giftForm.exchangeDateDayArr"
                multiple
                placeholder="请选择"
                class="w-300"
              >
                <el-option
                  v-for="item in monthOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <!-- 每周 -->
            <el-form-item class="form-item-mt" v-if="giftForm.exchangeDateType === 4" prop="exchangeDateWeekArr">
              <el-select
                size="small"
                v-model="giftForm.exchangeDateWeekArr"
                multiple
                placeholder="请选择"
                class="w-300"
              >
                <el-option
                  v-for="item in weekOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <!-- 兑换时段 -->
            <el-form-item label="兑换时段" prop="exchangeTimeType">
              <el-radio v-model="giftForm.exchangeTimeType" :label="1">
                全部时段
              </el-radio>
              <el-radio v-model="giftForm.exchangeTimeType" :label="2">
                部分时段
              </el-radio>
            </el-form-item>
            <div v-if="giftForm.exchangeTimeType === 2">
              <el-form-item
                class="mt8"
                v-for="(v, i) in giftForm.timeRangeList"
                :key="i"
                :prop="'timeRangeList.' + i + '.timeRange'"
                :rules="[{ validator: validateTime, trigger: 'change' }]"
              >
                <el-time-picker
                  is-range
                  v-model="v.timeRange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="HH:mm"
                  format="HH:mm"
                  placeholder="选择时间范围"
                />
                <el-button v-if="i" type="text" @click="delTimeRange(i)">
                  删除
                </el-button>
              </el-form-item>
              <p style="font-size:12px;color:#909399;line-height:12px;margin-left:180px;">
                请使用24小时制输入时间，格式如11:00至14:30
              </p>
              <p>
                <el-button type="text" style="margin:8px 0 10px 180px" @click="addTimeRange">
                  添加时间段
                </el-button>
              </p>
            </div>
            <!-- 实物礼品 -->
            <el-form-item
              label="配送方式"
              required
              v-if="giftType === 1"
              prop="changeTypeList"
            >
              <el-checkbox-group v-model="giftForm.changeTypeList" :disabled="editChangeTypeStatus">
                <el-checkbox label="2">
                  快递发货
                </el-checkbox>
                <el-checkbox v-if="giftForm.changeType === 1" label="1">
                  微信兑换券
                </el-checkbox>
                <el-checkbox
                  v-if="giftForm.changeType !== 1"
                  label="4"
                  @change="handleStatus"
                  @click="selfRaising"
                >
                  门店自提
                </el-checkbox>
                <span class="tips">公众号积分商城不支持此功能，小程序积分商城请升级至V3.5.8及以上版本</span>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="自提点" v-if="giftForm.changeTypeList.indexOf('4') != -1">
              <pickUp-store
                :isAdd="isAdd"
                :pickUpPointType="pickUpPointType"
                :selectData="selectedStoreData"
                @getArr="getArr"
              />
            </el-form-item>
            <el-form-item label="配送方式" v-if="giftType !== 1" prop="changeType">
              <el-radio-group v-model="giftForm.changeType" @change="changeDeliver" :disabled="editChangeTypeStatus">
                <el-radio :label="3">
                  在线发货
                  <el-tooltip effect="dark" content="上架虚拟商品时，若选择在线发货，则买家下单后，商户需及时在后台点击发货" placement="top-start">
                    <i class="iconfont icon-xinxixianshi" />
                  </el-tooltip>
                </el-radio>
                <el-radio :label="1" v-if="giftForm.changeType === 1">
                  微信兑换券
                </el-radio>
                <el-radio :label="5" v-if="giftForm.changeType !== 1" @change="textCode">
                  文本券码
                  <el-tooltip effect="dark" content="上架虚拟商品时，若选择文本券码，则可预先上传券码等信息，买家下单后，系统会自动将券码发给买家并完成交易，无需商户在后台点击发货。" placement="top-start">
                    <i class="iconfont icon-xinxixianshi" />
                  </el-tooltip>
                </el-radio>
              </el-radio-group>
              <el-button
                type="primary"
                size="mini"
                v-if="giftForm.changeType === 5"
                style="margin-left:20px;"
                @click="handleImportCoupon"
              >
                批量导入
              </el-button>
              <span v-if="giftForm.changeType === 5" style="font-size: 12px;color: rgb(144, 147, 153);margin-left:10px;">小程序积分商城请升级至V3.0.5及以上版本方可支持</span>
            </el-form-item>
            <div class="section-content1" v-show="giftForm.changeType === 1">
              <h3>选择卡券</h3>
              <el-form-item
                label="选择卡券"
                required
                v-show="giftId === '-1'"
                style="margin-bottom:66px;"
              >
                <el-button plain @click="showCard">
                  添加卡券
                </el-button>
              </el-form-item>
              <el-form-item label="选择卡券" required v-show="giftId !== '-1'" />
              <el-table :data="cardList" style="width: 900px;margin-left:170px;margin-top:-44px;" v-show="cardList.length > 0">
                <el-table-column label="卡券名称" prop="cardName" />
                <el-table-column label="有效期" prop="limitDay">
                  <template slot-scope="scope">
                    <div v-if="scope.row.cardEffectiveMode == 0">
                      固定日期：{{ scope.row.beginDate + '至' + scope.row.endDate }}
                    </div>
                    <div v-if="scope.row.cardEffectiveMode == 1">
                      领取后{{ (scope.row.startDay === 0 ? '当' : scope.row.startDay) + '天，有效天数' + scope.row.limitDay }}天
                    </div>
                    <div v-if="scope.row.cardEffectiveMode == 2">
                      投放后当月
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="领取限制">
                  <template slot-scope="scope">
                    {{ scope.row.cardLimit }}张/人
                  </template>
                </el-table-column>
                <el-table-column label="适用门店">
                  <template slot-scope="scope">
                    {{ scope.row.storeMode === 0 ? '所有门店' : scope.row.storeMode === 1 ? '部分分组' : '部分门店' }}
                  </template>
                </el-table-column>
                <el-table-column label="库存" prop="couponStock" />
              </el-table>
            </div>
          </div>
          <div class="section-content section-tip-content">
            <h3>售后服务</h3>
            <el-form-item label="支持买家申请退款" prop="refundType"  >
              <el-tooltip
                class="tip-content"
                effect="dark"
                content="若商品不支持买家退款，则在下单时系统会提醒买家此商品不支持退款或退货。"
                placement="top-start"
              >
                <i class="iconfont icon-xinxixianshi" />
              </el-tooltip>
              <el-radio-group v-model="giftForm.refundType" :disabled="!giftType || refundTypeStatus">
                <el-radio :label="1" @change="afterSale">
                  是
                </el-radio>
                <el-radio :label="0">
                  否
                </el-radio>
              </el-radio-group>
              <span style="font-size: 12px;color: rgb(144, 147, 153);margin-left:10px;">公众号积分商城不支持此功能，小程序积分商城请升级至V3.0.0及以上版本</span>
            </el-form-item>
          </div>
          <!-- <div class="confim-btn" :style="{ width: fixedWidth + 'px' }">
            <el-form-item class="fix-btn">
              <el-button
                type="primary"
                @click="submitGoodsForm('giftForm')"
                size="small"
                :disabled="$route.meta.type=='info'"
              >
                保存
              </el-button>
              <el-button @click="cancelGoodsForm" size="small">
                返回
              </el-button>
            </el-form-item>
          </div> -->
        </el-form>
      </div>
      <div class="anchor-link">
        <div class="link-item" :class="linkIndex === 0 ? 'link-item-active' : ''" @click="jump(0)">
          基础信息
        </div>
        <div class="link-item" :class="linkIndex === 1 ? 'link-item-active' : ''" @click="jump(1)">
          销售信息
        </div>
        <div class="link-item" :class="linkIndex === 2 ? 'link-item-active' : ''" @click="jump(2)">
          图文信息
        </div>
        <div class="link-item" :class="linkIndex === 3 ? 'link-item-active' : ''" @click="jump(3)">
          兑换信息
        </div>
        <div class="link-item" :class="linkIndex === 4 ? 'link-item-active' : ''" @click="jump(4)">
          售后服务
        </div>
      </div>
    </div>
    <!-- 新建分类弹框 -->
    <addCate :addCateModal="addCateModal" @getCategoryOptions="getCategoryOptions" />
    <!-- 卡券选择弹框 -->
    <vue-gic-card
      :disabledList="disabledList"
      :featureModule="projectName"
      :projectName="projectName"
      :showCardDialog="showCardDialog"
      :cardLimit="cardLimit"
      :cardType="cardType"
      @selectCard="selectCard"
      ref="dmcard"
    />
    <!-- 跳转链接 -->
    <el-dialog title="提示" :visible.sync="dialogVisibleLink" width="400px">
      <p style="margin-bottom:22px;">
        需先开启门店自提服务后方可生效，请先
        <el-button type="text" @click="goDeliverSet">
          前往设置
        </el-button>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleLink = false">取 消</el-button>
        <el-button type="primary" @click="goDeliverSet">确 定</el-button>
      </span>
    </el-dialog>
    <importCoupon :couponModal="importCouponModal" @getSuceessNum="getSuceessNum" />
    <dm-form-bottom>
      <el-button
        type="primary"
        @click="submitGoodsForm('giftForm')"
        size="small"
        :disabled="$route.meta.type=='info'"
      >
        保存
      </el-button>
      <el-button @click="cancelGoodsForm" size="small">
        返回
      </el-button>
    </dm-form-bottom>
  </div>
</template>

<script>
import qs from 'qs';
import request from '../../../service/request.js';
import copy from '../../../utils/clone.js';
import getInputVal from '../../../utils/common.js';
import addCate from '../../../components/addGiftCate';
import tinymceEdit from '../../../components/tinymce-edit';
import importCoupon from './importCoupon';
import addSku from './addSku';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import pickUpStore from '../../../components/store/store';
import draggable from 'vuedraggable';
import visibleSetting from '@/components/visible';
import historyData from '@/components/historyData';
export default {
  data () {
    const validateTime = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入时间'));
      } else {
        callback();
      }
    };
    const proNameValidator = (rule, value, callback) => {
      if (!value.trim()) {
        return callback(new Error('请输入礼品名称'));
      } else {
        callback();
      }
    };
    return {
      jifenquanxian: '',
      ladder: [],
      isDifferentialPricing: '',
      ladderPriceList: [],
      ladderMemberGrade: [],
      ladderSkuList: [],
      ladderHeader: [],
      gradeIdSku: [], // gradeId与SKU结合的数据
      // ladderPrice: false,
      submitLadderList: [],
      selectTab: 0,
      list3: [],
      combineListPre: [],
      combineList: [],
      isTable: true, // 判断有无sku
      integral: '',
      cash: 0.00,
      list2: [],
      ladderMemberGradeChange: [],
      getTime: getInputVal.getTime,
      getTime2: getInputVal.getTime2,
      // fixedWidth: document.documentElement.clientWidth - 200,
      projectName: 'integral-mall',
      giftType: '', // 礼品类型 实物是1虚拟是0
      mallProId: '', // 礼品id
      giftId: '', // 礼品Id
      linkIndex: 0,
      giftForm: {
        proReferId: '', // 礼品关联id
        proName: '',
        proCategoryId: '', // 分类id
        images: [],
        gradeType: 1,
        memberGrade: [], // 适用会员
        limitTimesStatus: false,
        limitTimes: '', // 限制兑换的次数
        exchangeDateType: 1, // 兑换日期
        exchangeFixDate: [], // 固定日期
        exchangeDateDayArr: [],
        exchangeDateWeekArr: [],
        exchangeTimeType: 1, // 兑换时段
        timeRangeList: [{ timeRange: '' }], // 部分时段数组
        detailDescription: '', // 图文性情
        changeType: 3, // 配送方式T
        pickUpPointType: 1,
        pickUpPoint: [],
        changeTypeList: [], // 配东方式
        refundType: 0, // 是否允许退款
        costValue: '', // 礼品成本
        marketPrice: '', // 市场价
        proCode: '', // 编码
        integralCost: '', // 积分
        cashCost: 0.00, // 现金
        virtualStock: '', // 库存
        proCodeQuery: '', // 条形码
        ladder: [],
      },
      limitTimes: 0,
      limitTimesNum: 0,
      validateTime,
      cliqueStatus: true, // 是否有集团卡
      memberGradeList: [], // 会员等级列表
      submitLoading: false, // 按钮加载中
      giftRules: {
        proName: [{ validator: proNameValidator, trigger: 'blur' }],
        costValue: [{ required: true, message: '请输入礼品成本', trigger: 'blur' }],
        gradeType: [{ required: true, message: '请选择适用会员', trigger: 'change' }],
        memberGrade: [{ required: true, message: '请选择适用会员', trigger: 'change' }],
        proCategoryId: [{ required: true, message: '请选择礼品分类', trigger: 'blur' }],
        exchangeFixDate: [{ required: true, message: '请选择时间', trigger: 'change' }],
        exchangeDateDayArr: [{ required: true, message: '请选择时间', trigger: 'change' }],
        exchangeDateWeekArr: [{ required: true, message: '请选择时间', trigger: 'change' }],
        changeTypeList: [{ type: 'array', required: true, message: '请至少选择一个配送方式', trigger: 'change' }],
        changeType: [{ required: true, message: '请选择一个配送方式', trigger: 'change' }],
        exchangeTimeType: [{ required: true, message: '请选择兑换时段', trigger: 'change' }],
        pickUpPoint: [{ required: true, message: '请选择自提点', trigger: 'change' }],
        refundType: [{ required: true, message: '请选择售后方式', trigger: 'change' }],
      },
      refundTypeStatus: false,
      uploadAction: getInputVal.uploadAction(),
      headersUpload: {
        sign: '',
      },
      proNameLen: 0,
      uploadStatus: true, // 上传按钮
      dialogVisibleImg: false, // 上传图片
      categoryOptions: [], // 礼品分类
      addCateModal: {
        dialogVisible: false,
      },
      monthOptions: Array.from(Array(31), (v, k) => (k + 1).toString()),
      weekOptions: ['1', '2', '3', '4', '5', '6', '7'],
      stockDisabled: false, // spu库存是否可输入
      refash: false,
      giftProStandardJson: [], // 规格列表
      isStdImg: false, // 图片上传的状态
      skuList: [], // sku列表
      submitSkuJson: [],
      skuHeaderList: [],
      IsAgreeUploadStatus: false, // 是否允许上传
      // projectName: 'intergral-mall', //当前项目名
      showCardDialog: false,
      cardLimit: 3, // 卡券限制类型 1-限制领取1张的卡券 2- 限制领取 1~100的卡券 3-限制领取&=100 的卡券
      cardType: 2, // 卡券类型集合（0：抵金券，1：折扣券，2：兑换券）null-为全部类型 逗号分隔
      disabledList: [],
      selectedData: {},
      cardList: [],
      editChangeTypeStatus: false,

      couponCostValue: 0, // 兑换券成本
      couponCardStock: 0, // 兑换券库存
      costValueStatus: false,
      dialogVisibleLink: false,
      importCouponModal: {
        // 文本券码导入
        dialogVisible: false,
        integralMallProId: '',
      },
      textStock: 0, // 文本券码库存数
      creatorId: '', // 权限id
      getSaveData: '',
      sceneValue: 'member', // 场景值
      useId: '', // 模板id
      hasSearchData: '', // 当前页回显的数据(接口返回)
      operateType: true, // 编辑的时候是false 新增是true 例如列表筛选是开始true 编辑改成false
      toggleTag: false, // 控制(确认取消)按钮显示的参数,仅供参考,可自行修改
      searchParams: {}, // 查询数据数据
      pickUpPointList: [], // 门店自提列表
      // 新版门店卡券选择器
      uuid: '',
      // 门店自提数据
      pickUpPointType: 0,
      selectedStoreData: [],
      pickUpPointStr: '',
      warnStatus: {
        way: false, // 配送方式提示
        refund: false, // 退款提示
        textCode: false, // 文本券码
      },
      memberGrade: '',
      isEdit: this.$route.meta.type == 'edit',
      isAdd: this.$route.meta.type == 'add',
      isCopy: this.$route.meta.type == 'copy',
      isInfo: this.$route.meta.type == 'info',
      isCorrect: true, // 校验阶梯价的验证是否可以保存阶梯价
      enterpriseId: '', // 商户id
      specialOrder: false, // 是否定制
      dragging: false,
      giftFormFileList: [],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 24 * 3600 * 1000;
        },
      },
      visibleData: { // 可见配置的数据源
        releaseType: 1, // 上架时间
        limitTimeBegin: [], // 上架时间具体
        proShowStatus: 1, // 显示状态
        isNewGuestVisible: 0, // 0：新客不可见、1：新客可见
        // 可见配置的公共组件的配置
        useNewStoreWidget: 1,
        openFlag: false,
        creatorId: '',
        sendChildData: {
          storeType: 1,
          storeGroupIds: '',
          storeIds: [],
        },
        uuid: '',
        showFlag: 1,
        shareFlag: 0,
      },
      isNew: true, // 编辑旧商品时，是否确认转换为新数据格式
    };
  },
  computed: {
    typeVal () {
      const obj = { add: '新建', copy: '复制', edit: '编辑', info: '查看' };
      return obj[this.$route.meta.type];
    },
  },
  mounted () {
    this.jifenquanxian = localStorage.getItem('limitCodeType') == 'true';
    this.getOpenStatus();
    this.getUserId();
    this.getErpGoodsFlag();
    window.onbeforeunload = function (e) {
      localStorage.removeItem('giftListObj');
    };
    this.giftType = Number(this.$route.query.type); // 列表上实物是1虚拟是0
    this.giftId = this.$route.query.giftId;
    this.mallProId = this.$route.query.giftId;

    if (this.isEdit || this.isInfo) {
      this.giftForm.proReferId = this.$route.query.proReferId;
      this.getInfo();
      this.editChangeTypeStatus = true;
    } else {
      this.getMemberGradeList(); // 会员等级列表
      this.isNew = true;
      if (this.giftType === 1) {
      // 实物
        this.giftForm.changeType = 2;
      } else if (this.giftType === 0) {
        // 虚拟
        this.getGiftId();
      }
    }
    if (this.isCopy) {
      this.giftForm.proReferId = this.$route.query.proReferId;
      this.getInfo();
      this.editChangeTypeStatus = false;
      if (this.giftType === 0) {
        this.getGiftId();
      }
    }

    this.getCategoryOptions(); // 分类数据
    this.$nextTick(function () {
      window.addEventListener('scroll', this.onScroll, true);
    });
    const mainSection = document.querySelector('.dm-layout-page');
    mainSection.scrollTop = 0;
    console.log(mainSection.scrollTop);
    // const pageWidth = this.$refs.dmLayoutPage.offsetWidth;
    // const formBottom = getFormButton(this, 'DmFormBottom');
    // console.log(getFormButton);
    // formBottom.pageWidth = pageWidth;
    // function getFormButton (vm, compName) {
    //   let result = {};
    //   vm.$children.some(el => {
    //     if (el.$options && el.$options.name == compName) {
    //       result = el;
    //     } else if (Array.isArray(el.$children)) {
    //       result = getFormButton(el, compName);
    //     }
    //     return result.$options && result.$options.name == compName;
    //   });
    //   return result;
    // }
  },
  methods: {
    // 阶梯价定制，判断达摩测试环境与地素环境
    // 达摩测试 ff8080815dacd3a2015dacd3ef5c0000
    // 达摩生产 ff8080816a36326c016a53380d8b5f52
    // 地素 ff80808163218c030163429b47110635
    // 地素测试 ff8080816f12b5c0016f1d5896820147
    getUserId () {
      request.get('/api-integral-mall/can-differential-pricing').then(res => {
        if (res.data.errorCode === 0) {
          this.specialOrder = res.data.result == 1;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    memberChange () {
      if (this.isDifferentialPricing) {
        this.setLadder();
        this.submitLadderList = copy(this.list3);
      }
    },
    changeladder (value) {
      if (value.length) {
        this.isDifferentialPricing = 1;
        // 勾选了阶梯价，先设置默认数据
        this.memberChange();
      } else {
        this.isDifferentialPricing = 0;
      }
    },
    setLadder () {
      const submitSkuJsonTwo = []; // 未选sku时使用
      this.ladderMemberGrade = [];
      const lists = [];
      // 解决会员等级排序以及阶梯价等级的排序问题
      this.giftForm.memberGrade.forEach(item => {
        this.memberGradeList.forEach(itt => {
          if (item === itt.gradeId) {
            lists.push(itt);
          }
        });
      });
      lists.forEach(item => {
        this.ladderMemberGrade.push({
          gradeId: item.gradeId,
          gradeName: item.gradeName,
        });
      });
      // }
      this.list2 = copy(this.ladderMemberGrade);
      this.ladderHeader = copy(this.skuHeaderList);
      if (this.submitSkuJson.length) {
        this.ladderSkuList = copy(this.submitSkuJson);
        this.isTable = true;
      } else {
        submitSkuJsonTwo.push({
          giftProSkuId: '',
          giftProSkuIntegral: '', // 积分
          giftProSkuCash: 0.00, // 现金
          stock: '', // 库存
          giftProSkuStandCode: '', // 规格编码
          giftProGiftCode: '', // 条形码
          giftPropValues: '',
        });
        this.isTable = false;
        this.ladderSkuList = copy(submitSkuJsonTwo);
      }
      // 目前
      this.ladderSkuList.forEach(item => {
        item.giftProSkuIntegral = '';
        item.giftProSkuCash = 0.00;
      });
      for (let i = 0; i < this.list2.length; i++) {
        this.list2[i].skuList = this.ladderSkuList;
      }
      this.list3 = copy(this.list2);
      // 多次设置阶梯价，回显之前保存的值
      if (this.submitLadderList.length) {
        this.submitLadderList.forEach(item => {
          this.list3.forEach(itt => {
            if (item.gradeId === itt.gradeId) {
              item.skuList.forEach(item2 => {
                const id = [];
                if (item2.giftPropValues && item2.giftPropValues.length) {
                  item2.giftPropValues.forEach(item3 => {
                    id.push(item3.valueId);
                  });
                  itt.skuList.forEach(itt2 => {
                    const id2 = [];
                    if (itt2.giftPropValues.length) {
                      itt2.giftPropValues.forEach(itt3 => {
                        id2.push(itt3.valueId);
                      });
                      if (id.length && id2.length && id.join('_') === id2.join('_')) {
                        itt2.giftProSkuCash = item2.giftProSkuCash;
                        itt2.giftProSkuIntegral = item2.giftProSkuIntegral;
                      }
                    }
                  });
                } else {
                  // itt.skuList.forEach(itt3 => {
                  // if (!itt3.giftPropValues.length) {
                  itt.skuList[0].giftProSkuCash = item.skuList[0].giftProSkuCash;
                  itt.skuList[0].giftProSkuIntegral = item.skuList[0].giftProSkuIntegral;
                  // }
                  // });
                }
              });
            }
          });
        });
      }
    },
    saveLadderDetail () {
      this.isCorrect = true;
      for (let i = 0; i < this.list3.length; i++) {
        const skuList = this.list3[i].skuList;
        if (this.isCorrect) {
          for (let j = 0; j < skuList.length; j++) {
            if (skuList[j].giftProSkuCash && (skuList[j].giftProSkuIntegral === 0 || skuList[j].giftProSkuIntegral === null)) {
              this.isCorrect = false;
              this.$message.error('已填入现金，则必填积分');
              break;
            }
            if ((skuList[j].giftProSkuCash === '' || skuList[j].giftProSkuCash === null) && skuList[j].giftProSkuIntegral) {
              if (this.jifenquanxian) {
                skuList[j].giftProSkuCash = 0.00;
                return;
              }
              this.isCorrect = false;
              this.$message.error('已填入积分，则必填现金');
              break;
            }
            if (skuList[j].giftProSkuCash && skuList[j].giftProSkuIntegral) {
              const itemPlus = Number(skuList[j].giftProSkuCash) + Number(skuList[j].giftProSkuIntegral);
              if (!itemPlus) {
                this.isCorrect = false;
                this.$message.error('积分和现金相加不可为0');
                break;
              }
            }
          }
        } else {
          break;
        }
      }
      if (this.isCorrect) {
        this.submitLadderList = copy(this.list3);
        this.$message.success('保存成功');
        this.$refs.popover.showPopper = false;
      }
    },
    handleLadder (value) {
      value.forEach(item => {
        item.giftProSkuIntegral = this.integral;
        item.giftProSkuCash = this.cash;
      });
      this.integral = '';
      this.cash = 0.00;
    },
    getOpenStatus () {
      request.post('/api-integral-mall/is-show-self').then(res => {
        this.visibleData.openFlag = res.data.result.openFlag;
        if (this.visibleData.openFlag) {
          this.visibleData.sendChildData.storeType = 1;
        } else {
          this.visibleData.sendChildData.storeType = 0;
        }
        this.visibleData = Object.assign({}, this.visibleData);
      });
    },

    // 获取卡券详情
    getCardInfo () {
      const params = {
        coupCardId: this.giftForm.proReferId,
      };
      request.post('/api-integral-mall/get-card', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          this.cardList = [];
          this.cardList.push(res.data.result);
          if (this.cardList) {
            for (const item of this.cardList) {
              item.beginDate = this.getTime2(item.beginDate);
              item.endDate = this.getTime2(item.endDate);
            }
          }
          this.couponCardStock = res.data.result.couponStock; // 兑换券库存
          this.limitTimes = Number(res.data.result.cardLimit);
          this.limitTimesNum = res.data.result.cardLimit;
          const params = {
            couponCardId: res.data.result.coupCardId,
            proType: 1,
          };
          request.post('/api-integral-mall/get-integral-mall-CashCost', qs.stringify(params)).then(res => {
            if (res.data.errorCode === 0 && res.data.result.costValue) {
              this.couponCostValue = Number(res.data.result.costValue);
            } else {
              this.$message.error(res.data.message);
            }
          });
          // this.limitStock = Number(res.data.result.couponStock);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    limitTimeChange () {
      if (this.cardList.length) {
        // 选择了卡圈
        if (Number(this.giftForm.limitTimes) > Number(this.limitTimes)) {
          this.$message.error('兑换限制不得大于此优惠券的领取次数');
          // this.couponForm.limitTimes = this.limitStock;
          return false;
        }
      } else {
        // 未选择了卡圈
        this.limitTimesNum = this.giftForm.limitTimes;
      }
    },
    refashData () {
      this.refash = !this.refash;
    },
    onScroll () {
      const mainSection = document.querySelector('.dm-layout-page');
      if (mainSection) {
        const scroll = mainSection.scrollTop;
        const jump = mainSection.querySelectorAll('.section-content');
        jump.forEach((item, index) => {
          if (scroll >= item.offsetTop) {
          // 滚动到对应的锚记改变样式
            this.linkIndex = index;
          }
        });
      }
    },
    jump (num) {
      const mainSection = document.querySelector('.dm-layout-page');
      const index = Number(num);
      this.linkIndex = index;
      // 用 class="d_jump" 添加锚点
      const jump = mainSection.querySelectorAll('.section-content');
      const total = jump[index].offsetTop;
      let distance = mainSection.scrollTop;
      // let distance = 200;
      // 平滑滚动，时长500ms，每10ms一跳，共50跳

      let step = total / 50;

      if (total > distance) {
        smoothDown();
      } else {
        const newTotal = distance - total;
        step = newTotal / 50;
        smoothUp();
      }
      function smoothDown () {
        if (distance < total) {
          distance += step;
          mainSection.scrollTop = distance;
          // mainSection.scrollTop = distance;
          setTimeout(smoothDown, 10);
        } else {
          mainSection.scrollTop = total;
          // mainSection.scrollTop = total;
        }
      }
      function smoothUp () {
        if (distance > total) {
          distance -= step;
          mainSection.scrollTop = distance;
          // document.documentElement.scrollTop = distance;
          setTimeout(smoothUp, 10);
        } else {
          mainSection.scrollTop = total;
          // document.documentElement.scrollTop = total;
        }
      }
    },
    // 获取详情
    async getInfo () {
      const params = {
        integralMallProId: this.giftId,
      };
      this.submitLoading = true;
      request.post('/api-integral-mall/get-integral-mall-pro', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          const data = res.data.result;
          this.echoVisibleData(data);
          this.giftForm.proName = data.proName; // 名称
          this.proNameLen = getInputVal.getZhLen(this.giftForm.proName);
          this.giftForm.proCategoryId = data.proCategoryId; // 分类
          this.giftForm.proCode = data.proCode; // 编码
          this.giftForm.integralCost = data.integralCost; // 积分
          this.giftForm.cashCost = data.cashCost; // 现金
          this.giftForm.virtualStock = data.virtualStock; // 库存
          this.currentStock = data.virtualStock;
          if (this.isCopy && data.giftType == 0 && data.changeType == 5) {
            this.giftForm.virtualStock = ''; // 清空虚拟礼品库存
            this.currentStock = '';
          }
          this.giftForm.proCodeQuery = data.proCodeQuery; // 条形码
          this.giftForm.costValue = data.costValue; // 礼品成本
          this.giftForm.marketPrice = data.marketPrice; // 市场价
          this.giftForm.detailDescription = data.detailDescription; // 图文详情

          this.giftForm.ladder = data.isDifferentialPricing ? ['1'] : []; // 是否设置阶梯价
          if (this.giftForm.ladder.length) {
            this.isDifferentialPricing = this.giftForm.ladder[0];
          }
          if (this.isDifferentialPricing && data.gradeProSkus && data.gradeProSkus.length > 0) {
            if (this.isCopy) { // 复制时重置阶梯价 giftProSkuId
              data.gradeProSkus.forEach(item => {
                if (item.skuList && item.skuList.length) {
                  item.skuList.forEach(it => {
                    it.giftProSkuId = '';
                  });
                }
              });
            }
            this.list3 = data.gradeProSkus; // 阶梯价详情
            this.submitLadderList = data.gradeProSkus;
          } else {
            this.list3 = [];
          }
          this.list3.forEach(item => {
            if (item.skuList && item.skuList.length) {
              item.skuList.forEach(it => {
                it.giftPropValues = JSON.parse(it.giftPropValuesJson);
              });
            }
          });

          this.hasSearchData = data.searchParams;
          this.giftForm.gradeType = data.gradeType;
          this.getMemberGradeList()
            .then(() => {
              if (data.memberGrade) {
                this.memberGrade = data.memberGrade;
                this.giftForm.memberGrade = data.memberGrade.split(','); // 适用会员
              } else {
                this.memberGrade = '';
                this.giftForm.memberGrade = [];
              }
            })
            .finally(() => {
              if (this.isEdit || this.isInfo) {
                const list = this.memberGradeList.filter(item => {
                  return this.memberGrade.indexOf(item.gradeId) != -1;
                });
                list.forEach(item => {
                  this.ladderMemberGrade.push({
                    gradeId: item.gradeId,
                    gradeName: item.gradeName,
                  });
                });
              }
            });
          this.giftForm.proReferId = this.isEdit || this.isInfo ? data.proReferId : '';
          this.refash = !this.refash;
          const giftFormFileList = [];
          this.giftForm.images = [];
          if (data.images) {
            // 主图
            for (const item of data.images) {
              giftFormFileList.push({
                imageUrl: item.imageUrl,
                imageCode: item.imageFieldCode,
              });
            }
          }
          this.giftForm.images = [].concat(giftFormFileList);
          this.giftFormFileList = [].concat(giftFormFileList);
          if (this.giftForm.images.length >= 5) {
            this.uploadStatus = false;
          } else {
            this.uploadStatus = true;
          }
          // 限兑
          if (data.limitTimes === -1) {
            this.giftForm.limitTimesStatus = false;
          } else {
            this.giftForm.limitTimesStatus = true;
          }
          this.giftForm.limitTimes = data.limitTimes;
          // 兑换日期
          this.giftForm.exchangeDateType = data.exchangeDateType;

          if (this.giftForm.exchangeDateType === 2) {
            this.giftForm.exchangeFixDate = [];
            this.giftForm.exchangeFixDate.push(data.exchangeFixDateBegin);
            this.giftForm.exchangeFixDate.push(data.exchangeFixDateEnd);
          } else if (this.giftForm.exchangeDateType === 3) {
            this.giftForm.exchangeDateDayArr = data.exchangeDateDay.split(',');
            this.giftForm.exchangeDateWeekArr = [];
          } else if (this.giftForm.exchangeDateType === 4) {
            this.giftForm.exchangeDateWeekArr = data.exchangeDateWeek.split(',');
            this.giftForm.exchangeDateDayArr = [];
          }
          // 兑换时段
          this.giftForm.exchangeTimeType = data.exchangeTimeType;
          // 部分时间段
          let timeDate;
          let timeRangeList;
          if (this.giftForm.exchangeTimeType === 2) {
            timeDate = data.timeZones.split('#');
            timeRangeList = [];
            for (const item of timeDate) {
              timeRangeList.push({
                timeRange: item.split('-'),
              });
            }
            this.giftForm.timeRangeList = timeRangeList;
          }
          // 配送方式
          if (data.giftType === 1) {
            // 实物礼品
            this.giftForm.changeType = Number(data.changeType);
            this.giftForm.changeTypeList = data.changeType.split(',');

            if (this.giftForm.changeTypeList.indexOf('4') != -1) {
              this.pickUpPointType = data.pickUpPointType;
              this.selectedStoreData = JSON.parse(data.pickUpPointExtra) || [];
              if (this.pickUpPointType === 4) {
                this.pickUpPointStr = data.pickUpPoint || '';
              }
            }
          } else if (data.giftType === 0) {
            // 虚拟礼品
            this.giftForm.changeType = Number(data.changeType);
          }
          if (this.giftForm.changeType === 1 || this.giftForm.changeType === 5) {
            this.refundTypeStatus = true;
          } else {
            this.refundTypeStatus = false;
          }

          this.giftForm.refundType = data.refundType;
          if (this.giftForm.changeType === 1) {
            // 微信兑换券
            this.getCardInfo();
          }
          // 规格列表
          if (data.giftProStandardJson) {
            this.giftProStandardJson = JSON.parse(data.giftProStandardJson);
          } else {
            this.giftProStandardJson = [];
          }

          if (this.giftProStandardJson.length) {
            if (this.giftProStandardJson[0].standardimg === 2) {
              this.isStdImg = true;
            } else {
              this.isStdImg = false;
            }
          }
          if (data.skuJsonList) {
            if (this.isCopy) { // 复制时重置规格 giftProSkuId
              data.skuJsonList.forEach(item => {
                item.giftProSkuId = '';
              });
            }
            this.submitSkuJson = data.skuJsonList;
          } else {
            this.submitSkuJson = [];
          }

          // 获取头部
          this.skuHeaderList = [];

          if (data.skuJsonList) {
            for (const item of JSON.parse(data.skuJsonList[0].giftPropValues)) {
              this.skuHeaderList.push({
                proName: item.proName,
                proId: item.proId,
              });
            }
          }

          // sku列表skuList
          if (data.skuJsonList) {
            this.skuList = [];
            for (const i in data.skuJsonList) {
              const tem = JSON.parse(data.skuJsonList[i].giftPropValues);
              tem.push({
                valueName: data.skuJsonList[i].giftProSkuIntegral, // 积分
              });
              tem.push({
                valueName: data.skuJsonList[i].giftProSkuCash, // 现金
              });
              tem.push({
                valueName: data.skuJsonList[i].stock, // 库存
                currentStock: data.skuJsonList[i].stock,
              });
              tem.push({
                valueName: data.skuJsonList[i].giftProSkuStandCode, // 规格编码
              });
              tem.push({
                valueName: data.skuJsonList[i].giftProGiftCode, // 条形码
              });
              tem.push({
                valueName: data.skuJsonList[i].giftProSkuId, // skuId
              });
              this.skuList.push(tem);
            }
            this.handleSku();
          }
          if (data.giftType === 1) {
            // 实物礼品
            if (this.giftProStandardJson.length > 0) {
              if (this.skuList.length > 0) {
                // spu库存是否可输入
                this.stockDisabled = true;
              } else {
                this.stockDisabled = false;
              }
            } else {
              this.stockDisabled = false;
            }
          } else if (data.giftType === 0) {
            // 虚拟
            if (this.giftForm.changeType === 5) {
              // 文本券码
              this.stockDisabled = true;
            } else {
              // 在线发货
              if (this.giftProStandardJson.length > 0) {
                if (this.skuList.length > 0) {
                  // 有sku(主要是处理老数据)
                  // spu库存是否可输入
                  this.stockDisabled = true;
                } else {
                  // 无sku的数据
                  this.stockDisabled = false;
                }
              } else {
                this.stockDisabled = false;
              }
            }
          }
          console.log(this.giftForm.virtualStock);
        }
      }).finally(() => {
        this.submitLoading = false;
      });
    },
    // 处理 可见配置回显
    echoVisibleData (data) {
      const { releaseType, limitTimeBegin, limitTimeEnd, proShowStatus, isNewGuestVisible, useNewStoreWidget, creatorId, storeWidgetId, showStore, storeGroupIds, storeInfo, ruleTitle, integralMallProRuleId, newRuleFlag, showFlag, shareFlag } = data;
      // 上架类型,自定义开始时间，自定义结束时间，显示状态，新客是否可见，使用新版卡券门店选择器，创建人id,新版卡券门店选择器id, 老的门店控件类型，门店分组id,部分门店id,规则标题，规则id,商品是否关联新规则,是否在积分商城显示,是否支持分享
      this.visibleData = { ...this.visibleData, releaseType, proShowStatus, isNewGuestVisible: isNewGuestVisible || 0, useNewStoreWidget, creatorId, showFlag, shareFlag };
      if (releaseType === 1) { // 1立即上架 2自定义上架时间段
        this.visibleData.limitTimeBegin = [];
      } else if (releaseType == 2) {
        this.visibleData.limitTimeBegin[0] = limitTimeBegin || '';
        this.visibleData.limitTimeBegin[1] = limitTimeEnd || '';
      }
      if (newRuleFlag == 1) {
        this.visibleData.ruleTitle = ruleTitle;
        this.visibleData.integralMallProRuleId = integralMallProRuleId;
        this.isNew = true;
      } else {
        this.isNew = false;
      }
      if (useNewStoreWidget == 0) { // 使用老的门店控件 (兼容老数据)
        const type = Number(showStore);
        this.visibleData.sendChildData.storeType = type; // ：0所有 1门店分组 2部分门店
        if (type == 1) {
          const arr = storeGroupIds && storeGroupIds.split(',');
          this.visibleData.sendChildData.storeGroupIds = arr && arr.join(',');
        } else if (type == 2) {
          this.visibleData.sendChildData.storeIds = storeInfo;
        }
      } else if (useNewStoreWidget == 1) { // 使用卡券门店选择器
        this.visibleData.uuid = storeWidgetId;
      }
      if (this.isCopy) { // 老数据复制时 使用上架规则那套新模式
        this.isNew = true;
        this.visibleData.uuid = '';
        this.visibleData.useNewStoreWidget = 1;
      }
      console.log(this.visibleData);
      this.visibleData = Object.assign({}, this.visibleData);
    },
    getSpuStock (val) {
      this.giftForm.virtualStock = val;
    },

    // 礼品字数限制
    goodsLimit (value) {
      this.$nextTick(() => {
        this.giftForm.proName = getInputVal.getInputVal(value, 30);
        this.proNameLen = getInputVal.getZhLen(this.giftForm.proName);
      });
    },
    // spu信息限制
    limitProCode (value) {
      this.$nextTick(() => {
        this.giftForm.proCode = getInputVal.getInputVal(value, 16);
      });
    },
    limitProCodeType () {
      const reg = /^[0-9a-zA-Z\-]+?$/;
      if (!reg.test(this.giftForm.proCode)) {
        this.$message.error('请输入数字或者字母或-');
        this.giftForm.proCode = '';
      } else {
        // 校验是否重复给出提示
        const params = {
          proCode: this.giftForm.proCode,
          integralMallProId: this.giftId === '-1' ? '' : this.giftId,
        };
        request.get('/api-integral-mall/check-pro-code-exsits', { params }).then(res => {
          if (res.data.errorCode === 0) {
            if (res.data.result) {
              this.$message.warning('当前编码已存在，不影响保存');
            }
          } else {
            this.$message.error(res.data.message);
          }
        });
      }
    },
    limitCostType () {
      // 积分
      if (Number(this.giftForm.integralCost) < 0) {
        this.$message.error('请输入大于0的数字');
        this.giftForm.integralCost = '';
      } else if (Number(this.giftForm.integralCost) === 0) {
        return false;
      } else if (!Number(this.giftForm.integralCost)) {
        this.$message.error('请输入数字类型');
        this.giftForm.integralCost = '';
      } else if (Number(this.giftForm.integralCost) > 10000000) {
        this.$message.error('积分最大10000000');
        this.giftForm.integralCost = '';
      } else {
        this.giftForm.integralCost = Number(this.giftForm.integralCost).toFixed(0);
      }
    },
    limitCash () {
      if (this.jifenquanxian) return;
      // 现金
      if (Number(this.giftForm.cashCost) < 0) {
        this.$message.error('请输入大于等于0的数字');
        this.giftForm.cashCost = 0.00;
      // } else if (Number(this.giftForm.cashCost) === 0) {
        // return false;
      } else if (!Number(this.giftForm.cashCost)) {
        this.$message.error('请输入数字类型');
        this.giftForm.cashCost = 0.00;
      } else if (Number(this.giftForm.cashCost) > 9999999) {
        this.$message.error('现金最大9999999');
        this.giftForm.cashCost = 0.00;
      } else {
        this.giftForm.cashCost = Number(this.giftForm.cashCost).toFixed(2);
      }
    },
    limitStock () {
      // 库存
      if (Number(this.giftForm.virtualStock) <= 0) {
        this.$message.error('请输入大于0的数字');
        this.giftForm.virtualStock = '';
      } else if (!Number(this.giftForm.virtualStock)) {
        this.$message.error('请输入数字类型');
        this.giftForm.virtualStock = '';
      } else if (Number(this.giftForm.virtualStock) > 1000000) {
        this.$message.error('库存最大1000000');
        this.giftForm.virtualStock = '';
      } else {
        this.giftForm.virtualStock = Number(this.giftForm.virtualStock).toFixed(0);
      }
    },
    limintProCodeQuery (value) {
      this.$nextTick(() => {
        this.giftForm.proCodeQuery = getInputVal.getInputVal(value, 16);
      });
    },
    limitproCodeQueryType () {
      const reg = /^[0-9a-zA-Z]+?$/;
      if (!reg.test(this.giftForm.proCodeQuery)) {
        this.$message.error('请输入数字或者字母');
        this.giftForm.proCodeQuery = '';
      }
    },
    // 获取礼品分类数据
    getCategoryOptions () {
      request.post('/api-integral-mall/load-category').then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result) {
            this.categoryOptions = res.data.result;
          } else {
            this.categoryOptions = [];
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 删除分类
    deleteCategory (id) {
      const params = {
        integralMallCategoryId: id,
      };
      request.post('/api-integral-mall/del-gift-category', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          this.$message.success('删除分类成功');
          this.getCategoryOptions();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 新增分类
    createCategory () {
      this.addCateModal.dialogVisible = true;
    },
    handleChange () {
      this.giftForm.memberGrade = [];
      this.getMemberGradeList();
    },
    // 获取会员等级
    async getMemberGradeList () {
      return request.post('/api-integral-mall/load-grade').then(res => {
        if (res.data.errorCode === 0) {
          if (res.data.result) {
            this.cliqueStatus = !!res.data.result.cliqueGrade;
            if (this.giftForm.gradeType === 1) {
              // 品牌卡
              this.memberGradeList = res.data.result.enterpriseGrade || [];
            } else if (this.giftForm.gradeType === 2) {
              this.memberGradeList = res.data.result.cliqueGrade || [];
            }
          } else {
            this.memberGradeList = [];
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 图片上传超出数量限制
    handlePictrueExceed (files, fileList) {
      if (5 - this.giftForm.images.length - files.length < 0) {
        this.$message.warning('最多上传5张商品主图');
        this.$refs.giftFormUpload.abort();
      }
    },
    // 上传图片前
    beforeUpload (file) {
      if (this.giftForm.images === null) {
        this.giftForm.images = [];
      }
      if (this.giftForm.images.length > 4) {
        this.$message.warning('最多上传5张商品主图');
        return false;
      }
      if (file.size > 1024 * 1024) {
        this.$message.error('请上传小于1MB的图片');
        return false;
      }
      /*eslint-disable*/
      if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg') {
        this.$message.error('请上传jpg，png格式的图片');
        return false;
      }
      if (localStorage.getItem('sign')) {
        this.headersUpload.sign = localStorage.getItem('sign');
      } else {
        this.headersUpload.sign = '';
      }
      var that = this;
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        reader.onload = function(event) {
          let image = new Image();
          image.onload = function() {
            resolve();
          };
          image.src = event.target.result;
        };
        reader.readAsDataURL(file);
      });
    },
    // 预览
    handlePictureCardPreview(file) {
      this.giftForm.images = file.url;
      this.dialogVisibleImg = true;
    },
    // 上传图片成功
    uploadSuccess(response, file, fileList) {
      if (response.errorCode === 0) {
        this.giftForm.images.push({
          imageUrl: response.result[0].qcloudImageUrl,
          imageCode: response.result[0].imageFiledCode
        });
        this.$message.success('上传成功');
        if (this.giftForm.images.length >= 5) {
          this.uploadStatus = false;
        } else {
          this.uploadStatus = true;
        }
      } else {
        this.$message.error(response.message);
      }
    },
    // 删除
    deteletDialogImageUrl(index) {
      this.uploadStatus = true;
      this.giftForm.images.splice(index, 1);
      this.$refs['giftFormUpload'].handleRemove();
    },
    handleRemove(file, fileList) {
      this.giftFormFileList = [].concat(fileList);
    },
    // 放大
    enlargeDialogImageUrl(index) {
      this.dialogEnlargeImageUrl = this.giftForm.images[index].imageUrl;
      this.dialogVisibleImg = true;
    },
    //两个数据条换位置
    swapArray(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
    // 添加兑换时段
    addTimeRange() {
      if (this.giftForm.timeRangeList.length >= 5) {
        this.$message.error('最多五个时间段');
        return false;
      }
      this.giftForm.timeRangeList.push({ timeRange: '' });
    },
    // 删除兑换时段
    delTimeRange(index) {
      this.giftForm.timeRangeList.splice(index, 1);
    },
    changeDeliver() {
      if (this.giftForm.changeType === 1 || this.giftForm.changeType === 5) {
        //微信兑换券
        this.refundTypeStatus = true;
        this.giftForm.refundType = 0;
      } else {
        this.refundTypeStatus = false;
        this.cardList = [];
      }
      if (this.giftForm.changeType === 3) {
        //在线发货
        this.giftForm.virtualStock = 0;
      } else if (this.giftForm.changeType === 5) {
        //文本卡券
        this.giftForm.virtualStock = this.textStock;
      }
      this.stockDisabled = this.giftForm.changeType === 5 ? true : false;
    },
    //获取商品的id
    getGiftId() {
      request.post('/api-integral-mall/get-gift-id').then(res => {
        if (res.data.errorCode === 0) {
          this.mallProId = res.data.result;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 导入文本券码
    handleImportCoupon() {
      this.importCouponModal.dialogVisible = true;
      this.importCouponModal.integralMallProId = this.mallProId;
    },
    // 获取文本券码成功的数据
    getSuceessNum(val) {
      this.textStock = val;
      this.giftForm.virtualStock = this.textStock;
    },
    // 勾选自提点
    handleStatus(val) {
      if (val) {
        this.getPickUpPointList();
        request.get('/api-integral-mall/pick-up-point-switch-status').then(res => {
          if (res.data.errorCode === 0) {
            if (res.data.result.status === 0) {
              //0关闭1开启
              this.dialogVisibleLink = true;
              for (let i = 0; i < this.giftForm.changeTypeList.length; i++) {
                if (this.giftForm.changeTypeList[i] === '4') {
                  this.giftForm.changeTypeList.splice(i, 1);
                }
              }
            }
          } else {
            this.$message.error(res.data.message);
          }
        });
      } else {
        this.giftForm.pickUpPointType = 1;
      }
      if (val && !this.warnStatus.way) {
        let code = 'pick-up-point';
        request.get(`/api-integral-mall/check-function-version?code=${code}`).then(res => {
          if (res.data.errorCode === 0) {
            if (!res.data.result.ok) {
              if (res.data.result.now !== '') {
                // this.$message.error('公众号积分商城不支持此功能，小程序积分商城请升级至V3.5.8及以上版本');
                this.$confirm('您当前小程序版本低于功能适用版本，设置在小程序无法正常生效，请进行版本升级', '提示', {
                  confirmButtonText: '确定',
                  showCancelButton: false,
                  type: 'warning'
                });
                this.warnStatus.way = true;
              } else {
                this.$message.error('该商户未开通小程序功能');
              }
            }
          }
        });
      }
    },
    textCode() {
      if (this.warnStatus.textCode) return;
      let code = 'text-code';
      request.get(`/api-integral-mall/check-function-version?code=${code}`).then(res => {
        if (res.data.errorCode === 0) {
          if (!res.data.result.ok) {
            if (res.data.result.now !== '') {
              // this.$message.error('公众号积分商城不支持此功能，小程序积分商城请升级至V3.5.8及以上版本');
              this.$confirm('您当前小程序版本低于功能适用版本，设置在小程序无法正常生效，请进行版本升级', '提示', {
                confirmButtonText: '确定',
                showCancelButton: false,
                type: 'warning'
              });
              this.warnStatus.textCode = true;
            } else {
              this.$message.error('该商户未开通小程序功能');
            }
          }
        }
      });
    },
    afterSale() {
      if (this.warnStatus.refund) return;
      let code = 'integral-refund';
      request.get(`/api-integral-mall/check-function-version?code=${code}`).then(res => {
        if (res.data.errorCode === 0) {
          if (!res.data.result.ok) {
            if (res.data.result.now !== '') {
              // this.$message.error('公众号积分商城不支持此功能，小程序积分商城请升级至V3.5.8及以上版本');
              this.$confirm('您当前小程序版本低于功能适用版本，设置在小程序无法正常生效，请进行版本升级', '提示', {
                confirmButtonText: '确定',
                showCancelButton: false,
                type: 'warning'
              });
              this.warnStatus.refund = true;
            } else {
              this.$message.error('该商户未开通小程序功能');
            }
          }
        }
      });
    },
    remoteMethod(value) {
      this.getPickUpPointList(value);
    },
    // 跳转到设置自提点
    goDeliverSet() {
      this.$router.push({ name: 'deliverSet' });
    },
    // 获取规格列表
    getStandradList(val) {
      this.giftProStandardJson = val;
      if (this.giftProStandardJson.length) {
        for (let i in this.giftProStandardJson) {
          if (Number(i) === 0) {
            this.giftProStandardJson[i].standardimg = this.IsAgreeUploadStatus ? 2 : 1;
          } else {
            this.giftProStandardJson[i].standardimg = 1;
          }
        }
        this.skuHeaderList = [];
        for (let item of this.giftProStandardJson) {
          this.skuHeaderList.push({
            proName: item.standardName,
            proId: item.standardId
          });
        }
        if (this.giftProStandardJson.length <= 0) {
          this.stockDisabled = false;
          this.giftForm.virtualStock = 0;
        }
      }
      console.log( this.giftProStandardJson )
    },
    async getSkuList(val) {
      console.log(val);
      if (val.length === 1 && val[0].length === 0) {
        this.submitSkuJson = [];
        this.stockDisabled = false;
        this.currentStock = 0;
        return false;
      }
      this.skuList = val;

      this.handleSku();
      if (this.isDifferentialPricing) {
        this.setLadder();
      }
      this.submitLadderList = copy(this.list3);
      await this.$nextTick();
      if (this.giftProStandardJson.length > 0) {
        if (this.skuList.length > 0) {
          //spu库存是否可输入
          this.stockDisabled = true;
        } else {
          this.stockDisabled = false;
          this.currentStock = 0;
        }
      } else {
        this.stockDisabled = false;
        this.giftForm.virtualStock = 0;
        this.currentStock = 0;
      }
    },
    IsAgreeUpload(val) {
      this.isStdImg = val;
      this.IsAgreeUploadStatus = val;
    },
    changeMinIntegral(val) {
      this.giftForm.integralCost = val.integralCost || '';
      this.giftForm.cashCost = val.cashCost || 0.00;
    },
    //处理sku
    handleSku() {
      let skuArr = copy(this.skuList);
      let outArr;
      let outArr1;
      let skuPrice = [];
      let skuSta = [];
      if (skuArr[0]) {
        // console.log('skuSta1', skuSta);
        for (let i in skuArr) {
          // console.log(777, skuArr[0]);
          //先获取sku价格条码这些
          outArr = copy(skuArr[i]); //得到固定的数据
          // console.log(333, outArr);
          outArr1 = outArr.splice(outArr.length - 6, 6);
          for (let k in outArr) {
            outArr[k].proName = this.skuHeaderList[k].proName;
            outArr[k].proId = this.skuHeaderList[k].proId;
            // outArr[k].proName = skuArr[0][k].proName;
            // outArr[k].proId = skuArr[0][k].proId;
          }

          skuSta.push(outArr);
          // console.log('skuSta2', skuSta);
          skuPrice.push(outArr1);
        }
        // console.log()
      }
      // return false;
      this.submitSkuJson = [];
      if (skuArr[0]) {
        for (let j in skuArr) {
          //数据的个数
          this.submitSkuJson.push({
            giftProSkuId: skuPrice[j][5] ? skuPrice[j][5].valueName : '',
            giftProSkuIntegral: skuPrice[j][0] ? skuPrice[j][0].valueName : '', //积分
            giftProSkuCash: skuPrice[j][1] ? skuPrice[j][1].valueName : 0.00, //现金
            stock: this.isEdit ? (skuPrice[j][2] ? skuPrice[j][2].valueName - (skuPrice[j][2].currentStock || 0) : '') : skuPrice[j][2] ? skuPrice[j][2].valueName : '', //库存
            giftProSkuStandCode: skuPrice[j][3] ? skuPrice[j][3].valueName : '', //规格编码
            giftProGiftCode: skuPrice[j][4] ? skuPrice[j][4].valueName : '', //条形码
            giftPropValues: skuSta[j]
          });
        }
      }
    },
    combine(arr) {
      arr.reverse();
      let r = [];

      (function f(t, a, n) {
        if (n == 0) return r.push(t);
        for (let i = 0; i < a[n - 1].length; i++) {
          f(t.concat(a[n - 1][i]), a, n - 1);
        }
      })([], arr, arr.length);
      // var t = r;
      return r; // r是排列组合后的数据与
    },
    // 显示卡券弹窗
    showCard() {
      this.showCardDialog = true;
    },
    // 子组件触发方法
    selectCard(val) {
      this.showCardDialog = false;
      this.cardList = [];
      if (val) {
        this.cardList.push(val);
        this.costValueStatus = true;
        this.limitTimes = val.cardLimit;
        this.limitTimesNum = val.cardLimit;
        // this.limitStock = val.couponStock;
        this.giftForm.proReferId = val.coupCardId;
        this.giftForm.cardType = val.cardType;
        this.couponCardStock = val.couponStock; //兑换券库存
        this.giftForm.limitTimesStatus = true;
        let params = {
          couponCardId: val.coupCardId,
          proType: 1
        };
        request.post('/api-integral-mall/get-integral-mall-CashCost', qs.stringify(params)).then(res => {
          if (res.data.errorCode === 0) {
            this.couponCostValue = res.data.result.costValue;
            this.giftForm.costValue = res.data.result.costValue;
          } else {
            this.$message.error(res.data.message);
          }
        });
      }
    },
    // 门店自提列表
    getPickUpPointList(value) {
      let params = {
        search: value
      };
      request.post('/api-integral-mall/list-pick-up-points', qs.stringify(params)).then(res => {
          this.pickUpPointList = res.data.result || [];
      
      });
    },
    getArr(arr, type) {
      if (type === 4) {
        let selectedStoreData = {};
        selectedStoreData = {
          downloadUrl: arr.downloadUrl,
          fileId: arr.fileId,
          correctNumber: arr.correctNumber
        };
        this.selectedStoreData = selectedStoreData;
        this.pickUpPointStr = arr.pickUpPointStr;
      } else {
        this.selectedStoreData = arr;
      }
      this.pickUpPointType = type;
    },

    // 保存
    async submitGoodsForm(form) {
      this.giftForm.detailDescription = this.$refs.tinymceWrap.tinymceHtml;
      let giftImageUrls = [];
      let giftImageFiledCodes = [];
      if (this.giftForm.images.length === 0) {
        this.$message.error('请上传商品主图');
        return false;
      } else {
        for (let item of this.giftForm.images) {
          giftImageUrls.push(item.imageUrl);
          giftImageFiledCodes.push(item.imageCode);
        }
      }
      //校验规格明细
      if(this.giftType == 1 && this.$store.state.product.erpGoodsFlag && !this.giftProStandardJson.length) {
        this.$message.error('您已开启商品兑换库存同步接口，商品sku必填');
        return false;
      }
      if (this.giftProStandardJson) {
        for (let item of this.giftProStandardJson) {
          if (item.standardId === '') {
            this.$message.error('请填写完整的规格');
            return false;
          } else if (item.valueList.length === 0) {
            this.$message.error('请填写完整的规格');
            return false;
          }
          for (let item1 of item.valueList) {
            if (item1.valueName === '' || item1.valueId === '') {
              this.$message.error('请填写完整的规格');
              return false;
            }
          }
        }
      }
      //校验规格明细
      if (this.submitSkuJson.length) {
        for (let item of this.submitSkuJson) {
          if (item.giftPropValues.length) {
            for (let i of item.giftPropValues) {
              if (i.proId === '' || i.proName === '' || i.valueId === '' || i.valueName === '') {
                this.$message.error('请填写完整的sku数据');
                return false;
              }
            }
          }

          if (!item.stock && item.stock !== 0) {
            this.$message.error('请填写库存');
            return false;
          }
          if ((item.giftProSkuCash == '0.00' || item.giftProSkuCash === 0) && !this.jifenquanxian) {
            this.$message.error('请填写现金');
            return false;
          }
          if(this.giftType == 1 && this.$store.state.product.erpGoodsFlag && !item.giftProSkuStandCode) {
            this.$message.error('您已开启商品兑换库存同步接口,规格编码必填');
            return false;
          }
          if (item.giftProSkuIntegral === '') {
            this.$message.error('请填写积分');
            return false;
          }
        }
      }
      // 检验规格图片
      if (this.IsAgreeUploadStatus && this.giftProStandardJson.length) {
        if (this.giftProStandardJson[0].valueList) {
          for (let item of this.giftProStandardJson[0].valueList) {
            if (!item.propImg) {
              this.$message.error('请上传规格图片');
              return false;
            }
          }
        }
      }
      if (this.giftForm.integralCost === '') {
        this.$message.error('请填写礼品积分');
        return false;
      } else if (this.giftForm.cashCost === '') {
        if(this.jifenquanxian) {
          return this.giftForm.cashCost = '0.00';
        }
        this.$message.error('请填写礼品现金');
        return false;
      } else if (this.giftForm.virtualStock === '') {
        this.$message.error('请填写礼品库存');
        return false;
      }
      if (Number(this.giftForm.virtualStock) === 0) {
        this.$message.error('库存为0的礼品不允许保存');
        return false;
      }
      if (this.giftForm.changeType === 1) {
        if (this.cardList.length === 0) {
          this.$message.error('请选择卡券');
          return false;
        }
      }
      //库存不能大于兑换券库存
      if (this.giftForm.changeType === 1) {
        if (Number(this.giftForm.virtualStock) > Number(this.couponCardStock)) {
          this.$message.error('礼品库存不能大于兑换券的库存');
          return false;
        }
      }
      if (this.cardList.length) {
        if (Number(this.giftForm.limitTimes) > Number(this.limitTimes)) {
          this.$message.error('兑换限制不得大于此优惠券的领取次数');
          return false;
        }
      }
      if (this.giftForm.limitTimesStatus) {
        if (Number(this.giftForm.limitTimes) === 0) {
          this.$message.error('限兑次数不能为0');
          return false;
        }
      }
 
    
      if (this.giftForm.changeTypeList.indexOf('4') != -1) {
        //配送方式选择了门店自提
        if (this.pickUpPointType === 1 || this.pickUpPointType === 2 || this.pickUpPointType === 3) {
          if (this.selectedStoreData.length < 1) {
            this.$message.error('请选择自提点数据');
            return false;
          }
        } else if (this.pickUpPointType === 4) {
          if (!this.selectedStoreData.correctNumber > 0) {
            this.$message.error('请至少成功导入一个自提点');
            return false;
          }
        }
      }
      let hasWay = this.giftType ? this.giftForm.changeTypeList.length : this.giftForm.changeType;
      if (!hasWay) {
        this.$message.error('请选择配送方式');
        return false;
      }

      const data  = await  this.$refs.visibleSetting.submit()
      if(!data) return false;
      this.$refs[form].validate(valid => {
        if (valid) {
          if(this.submitLadderList.skuList) {
            this.submitLadderList.skuList.map(item=>{
              item.giftProSkuCash == 0 ? '0.00' : item.giftProSkuCash
            })
          }
          if(this.submitSkuJson) {
            this.submitSkuJson.map(item=>{
              console.log(item.giftProSkuCash, 'giftProSkuCash');
              if(item.giftProSkuCash){
                console.log(item.giftProSkuCash, 'iiii');
              }else{
                console.log(item.giftProSkuCash, 'ooo');
                item.giftProSkuCash = '0.00'
              }
            })
          }
          console.log(this.submitSkuJson, 'dfsdfd');
          let params = {
            integralMallProId: this.isCopy? (this.giftType == 1? '' : this.mallProId):this.mallProId === '-1' ? '' : this.mallProId, //礼品id 复制时 虚拟礼品拿到新id 实物礼品不传id
            proType: this.giftForm.changeType === 1 ? 2 : 3, //发货方式是微信兑换券传2其他传3
            giftType: this.giftType === 0 ? 0 : 1, //0、虚拟 1、实物
            proName: this.giftForm.proName.trim(), //礼品名称
            giftImageUrls: giftImageUrls.join(','), //礼品主图
            giftImageFiledCodes: giftImageFiledCodes.join(','),
            proReferId: this.giftForm.proReferId, //关联id
            cardType: this.giftForm.changeType === 1 ? this.giftForm.cardType : '', //卡券类型
            proCategoryId: this.giftForm.proCategoryId, //礼品分类
            detailDescription: this.giftForm.detailDescription, //图文详情
            gradeType: this.giftForm.gradeType,
            memberGrade: this.giftForm.memberGrade.join(','), //适用会员
            showStore: this.visibleData.sendChildData.storeType, // 显示门店 0所有 1部分分类 2部分门店
            storeIds: '', //展现门店id
            storeWidgetId: '',
            limitTimes: this.giftForm.limitTimesStatus ? this.giftForm.limitTimes : '-1', //限兑
            exchangeDateType: this.giftForm.exchangeDateType, //兑换日期
            exchangeFixDateBegin: this.giftForm.exchangeDateType === 2 ? this.getTime(this.giftForm.exchangeFixDate[0]) : '', //固定日期
            exchangeFixDateEnd: this.giftForm.exchangeDateType === 2 ? this.getTime(this.giftForm.exchangeFixDate[1]) : '',
            exchangeDateDay: this.giftForm.exchangeDateType === 3 ? this.giftForm.exchangeDateDayArr.join(',') : '', //兑换日期月
            exchangeDateWeek: this.giftForm.exchangeDateType === 4 ? this.giftForm.exchangeDateWeekArr.join(',') : '', //兑换日期周
            exchangeTimeType: this.giftForm.exchangeTimeType, //兑换时段
            integralCost: this.giftForm.integralCost, //积分
            cashCost: this.giftForm.cashCost, //现金
            proCode: this.giftForm.proCode, //编码
            proCodeQuery: this.giftForm.proCodeQuery, //条形码
            costValue: this.giftForm.changeType === 1 ? this.couponCostValue : this.giftForm.costValue, //卡券礼品成本
            marketPrice: this.giftForm.marketPrice, //市场价
            virtualStock: this.isEdit ? this.giftForm.virtualStock - (this.currentStock || 0) : this.giftForm.virtualStock, //库存
            timeZones: '', //部分时段
            changeType: this.giftType === 0 ? String(this.giftForm.changeType) : this.giftForm.changeTypeList.join(','), //配送方式
            refundType: this.giftForm.refundType, //售后
            giftProStandardJson: this.giftProStandardJson ? JSON.stringify(this.giftProStandardJson) : '', //规格列表
            skuJson: this.submitSkuJson.length ? JSON.stringify(this.submitSkuJson) : '', //sku数据
            pickUpPointType: this.giftForm.changeTypeList.indexOf('4') != -1 ? this.pickUpPointType : '', //门店自提数据
            pickUpPointExtra: this.giftForm.changeTypeList.indexOf('4') != -1 ? JSON.stringify(this.selectedStoreData) : '', //门店自提数据
            isDifferentialPricing: this.isDifferentialPricing,
            differentialPricingJson: JSON.stringify(this.submitLadderList)
          };
          // 可见配置参数组装
          params = {...params,...data};
          if (this.pickUpPointType === 4) {
            params.pickUpPoint = this.pickUpPointStr;
          }
          // 部分时段时间转换
          let timeLink = [];
          if (this.giftForm.exchangeTimeType === 2) {
            for (let item of this.giftForm.timeRangeList) {
              timeLink.push(item.timeRange[0] + '-' + item.timeRange[1]);
            }
          }
          params.timeZones = timeLink.join('#');

          if (this.isDifferentialPricing) {
            this.confirmDetail(params);
          } else {
            this.submitLoading = true;
            this.saveDeatail(params);
          }
        } else {
          return false;
        }
      });
    },
    confirmDetail(params) {
      this.$confirm('<div>如更改规格或适用会员后，请先去设置阶梯价并保存，否则会使用原阶梯价，是否继续操作?</div>', '提示', {
        closeOnClickModal: false,
        showClose: false,
        type: 'warning',
        customClass: 'show-title',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '保存'
      }).then(() => {
        this.submitLoading = true;
        this.saveDeatail(params);
      });
    },
    saveDeatail(params) {
      request.post('/api-integral-mall/create-integral-pro', params).then(res => {
          this.$message.success('保存成功');
          this.$router.push({
            name: 'gift'
          });
      }).finally(()=>{
          this.submitLoading = false;
      })
    },
    // 返回
    cancelGoodsForm() {
      this.$router.push({
        name: 'gift'
      });
    },
   // 检测是否开启 erp商品兑换接口
    getErpGoodsFlag() {
      request.get('/api-integral-mall/get-config').then(res => {
        if (res.data.errorCode === 0) {
          const result = res.data.result || {};
          this.$store.commit('mutations_erpGoodsFlag', result.goodsStockSync || 0);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    //人群筛选器使用的方法
    // 父组件调用子组件方法,触发父组件事件
    getData() {
      this.$refs.peopleFilter.confirmSet();
    },
    // 子组件触发父组件事件,返回过滤条件数据
    findFilter(value) {
      console.log(value)
      this.searchParams = value;
    },
    // 取消
    cancelFilter() {
      this.$refs.peopleFilter.cancelSet();
    },
    // 获取需要回显的数据, 供保存时候使用
    getBackData(val) {
      this.getSaveData = val;
    },
    // 显示编辑,保存按钮隐藏,确认按钮显示 (子组件会调用)
    editShow() {
      this.toggleTag = true; 
    },
    // 显示保存按钮,隐藏确认按钮显示  (子组件会调用)
    editHide() {
      this.toggleTag = false; 
    },
    // 隐藏保存按钮和确认按钮  (子组件会调用)
    // 传个参数给父组件 来查数据
    hideBtn(refresh) {
      if (refresh === 0) {
        this.toggleTag = false;
      }
    }
  },
  components: {
    Treeselect,
    addCate,
    tinymceEdit,
    addSku,
    importCoupon,
    pickUpStore,
    draggable,
    visibleSetting,
    historyData
  }
};
</script>
<style scoped>
.w-100 {
  width: 100px;
}
.section-content h3 {
  height: 55px;
  line-height: 55px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  margin-bottom: 25px;
  padding-left: 32px;
  font-size: 16px;
   display: flex;
  align-items: center;
}
.section-content1 h3 {
  height: 55px;
  line-height: 55px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  margin-bottom: 25px;
  padding-left: 32px;
  font-size: 16px;
 
}
.section-content .el-form-item {
  margin-left: 32px;
}
.section-content1 .el-form-item {
  margin-left: 32px;
}
.w-376 {
  width: 376px;
}
/* 礼品主图 */
.img-box {
  width: 104px;
  height: 104px;
  border-radius: 4px;
  display: inline-block;
  margin-right: 8px;
  position: relative;
}
.img-box img {
  border-radius: 4px;
}

.dialog-img {
  width: 104px;
  height: 104px;
  position: absolute;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.5);
  display: none;
  cursor: pointer;
  border-radius: 6px;
}
.img-box:hover .dialog-img {
  display: block;
}

.upload-list-box .el-icon-delete {
  position: absolute;
  left: 56px;
  top: 50%;
  transform: translateY(-50%);
  display: none;
  font-size: 20px;
  color: #fff;
  z-index: 2;
}
.drag-box-wrap {
  display: flex;
  text-align: center;
}
.el-icon-zoom-in {
  position: absolute;
  left: 30px;
  top: 50%;
  transform: translateY(-50%);
  display: none;
  font-size: 20px;
  color: #fff;
  z-index: 2;
}
.el-icon-arrow-left {
  position: absolute;
  left: 5px;
  top: 50%;
  transform: translateY(-50%);
  display: none;
  font-size: 20px;
  color: #fff;
  z-index: 2;
}
.el-icon-arrow-right {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  display: none;
  font-size: 20px;
  color: #fff;
  z-index: 2;
}
.img-box:hover i {
  display: block;
  cursor: pointer;
}
.img-box:first-child .el-icon-arrow-left {
  display: none;
}
.img-box:last-child .el-icon-arrow-right {
  display: none;
}
/*.img-box:hover img{
    opacity:0.6;
    cursor: pointer;
  }*/
.img-box img {
  width: 104px;
  height: 104px;
}
.w-300 {
  width: 300px;
}
.w-600 {
  width: 600px;
}
.mall-content-section {
  position: relative;
}

/* 锚记 */
.anchor-link {
  width: 120px;
  position: fixed;
  right: 24px;
  bottom: 110px;
  background: #fff;
}
.link-item {
  height: 28px;
  line-height: 28px;
  color: #606266;
  font-size: 14px;
  border-left: 2px solid #ebeef5;
  padding-left: 18px;
  cursor: pointer;
}
.link-item-active {
  border-left: 2px solid #2F54EB;
  color: #2F54EB;
}
/* 固定按钮 */
.confim-btn {
  height: 32px;
  padding: 12px 0;
  position: fixed;
  bottom: 0px;
  left: 200px;
  background: #fff;
  z-index: 2;
  text-align: center;
  border-top: 1px solid #dcdfe6;
}
.fix-btn {
  margin-left: -100px;
}
/* 带删除的下拉框 */
.delete-select .delete-icon {
  display: none;
}
.delete-icon {
  color: #dcdfe6;
}
.delete-icon:focus {
  color: #dcdfe6;
}
.delete-icon:hover {
  color: #f5222d;
}
.curson-pointer tbody tr {
  cursor: pointer;
}
.form-item-mt {
  margin-top: -18px;
}
.mb8 {
  margin-bottom: 8px;
}
.red-color {
  color: #f5222d;
}
/* 表格 */
.spu-table {
  width: 900px;
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  border: 1px solid #ebeef5;
}
.spu-table thead tr {
  height: 48px;
  line-height: 48px;
  background: #f1f3f7;
  text-align: left;
}
.spu-table thead th {
  padding: 0 15px;
}
.spu-table tbody tr {
  border-bottom: 1px solid #ebeef5;
}
.spu-table tbody td {
  padding: 20px 15px;
  vertical-align: middle;
}
.tip-content {
  position: absolute;
  left: -25px;
}
.store-card {
  position: relative;
}
.tips-content {
  position: absolute;
  left: -10px;
}
.set-ladder {
  border-bottom: 1px solid #2F54EB;
  margin-left: 15px;
  display: inline-block;
  position: absolute;
  top: 12px;
}
</style>
<style>
.upload-list-box .el-upload--picture-card {
  width: 104px;
  height: 104px;
  line-height: 104px;
}
.select-shop__right {
  line-height: 28px !important;
}
.section-tip-content {
  padding-bottom: 30px;
}
.section-tip-content .el-form-item__label {
  text-align: left !important;
}
 
.tips {
  font-size: 12px;
  color: rgb(144, 147, 153);
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
  line-height: 32px;
}
/* 人群筛选器 */
/* .gic-people--button {
  background: #f2f3f4;
  padding: 0 0 20px 124px;
} */
 
.card-style.el-tabs--border-card {
  box-shadow: none !important;
}
.sub_title {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}
</style>
