<template>
  <div class="mall-section-container">
    <div class="mall-content-section">
      <!-- <div class="mall-content-title">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '' }">
            <a href="/report/#/memberSummary">首页</a>
          </el-breadcrumb-item>
          <el-breadcrumb-item>积分商城</el-breadcrumb-item>
          <el-breadcrumb-item>商品</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/coupon' }">
            优惠券
          </el-breadcrumb-item>
          <el-breadcrumb-item>{{ typeVal }}优惠券</el-breadcrumb-item>
        </el-breadcrumb>
        <h3>
          <span>{{ typeVal }}优惠券</span>
        </h3>
      </div> -->
      <div class="section" v-loading="submitLoading">
        <el-form
          :model="couponForm"
          :rules="couponRules"
          ref="couponForm"
          label-width="100px"
          class="demo-ruleForm"
          label-position="right"
          @submit.native.prevent
        >
          <div class="section-content">
            <h3>选择卡券</h3>
            <el-form-item label="选择卡券" required v-show="mallProId === '-1'||isCopy">
              <el-button plain @click="showCard" :disabled="cardList.length >= addCardMax">
                添加卡券
              </el-button>
              <span style="font-size: 12px;color: rgb(144, 147, 153);margin-left:10px;">支持选择兑换券，最多支持添加{{ addCardMax }}张卡券</span>
            </el-form-item>
            <div class="alert-content" v-if="couponStatus">
              <el-alert title="原卡券已被删除，请及时下线卡券，否则用户将无法兑换" type="warning" />
            </div>
            <el-form-item label="选择卡券" required v-show="mallProId !== '-1'" />
            <el-table
              :data="cardList"
              style="width: 1000px;margin-left:135px;margin-bottom:22px;display:inline-block"
              v-show="cardList.length > 0"
              :style="{ marginTop: mallProId !== '-1' ? '-60px' : '' }"
            >
              <el-table-column label="卡券名称" prop="cardName" min-width="140">
                <template slot-scope="scope">
                  <p style="line-height:22px;">
                    {{ scope.row.cardName }}
                  </p>
                  <p class="fz13 gray" style="line-height:20px;color:#909399">
                    {{ scope.row.subName }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column
                :show-overflow-tooltip="false"
                width="165"
                align="left"
                prop="createTime"
                label="卡券模板投放期限"
              >
                <template slot-scope="scope">
                  <span v-if="scope.row.putEffectiveMode == 0"> 固定日期：{{ getTime2(scope.row.putBeginDate) }} 至 {{ getTime2(scope.row.putEndDate) }} </span>
                  <span v-else>长期有效</span>
                </template>
              </el-table-column>
              <el-table-column label="用户使用有效期" prop="limitDay" width="165">
                <template slot-scope="scope">
                  <div v-if="scope.row.cardEffectiveMode == 0">
                    固定日期：{{ getTime2(scope.row.beginDate) + '至' + getTime2(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-column label="操作">
                <template slot-scope="scope">
                  <dm-delete @confirm="deleteCard(scope.$index)" tips="确定删除该卡券吗?" v-if="mallProId === '-1' || isCopy">
                    <el-button type="text">
                      删除
                    </el-button>
                  </dm-delete>
                  <el-button type="text" v-else :disabled="true">
                    删除
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="卡券状态" v-if="mallProId !== '-1'">
                <template slot-scope="scope">
                  <div style="color:#f5222d">
                    {{ scope.row.status === 0 ? '已删除' : scope.row.status === 1 ? '正常' : scope.row.status === 2 ? '已过期' : scope.row.status === 3 ? '未开始' : '' }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-form-item label="券包名称" v-if="cardList.length > 1" prop="proName">
              <el-input
                v-model.trim="couponForm.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="数据对话">
              <dm-activity-select
                :repProjectName="projectName"
                width="300"
                :actId.sync="couponForm.dataDialogueId"
                :showAdd="false"
              />
            </el-form-item> -->
          </div>
          <div class="section-content">
            <h3>图文信息</h3>
            <el-form-item label="卡券主图">
              <span style="font-size: 12px;color: rgb(144, 147, 153);">小程序积分商城请升级至V3.0.5及以上版本方可支持</span>
              <div class="upload-list-box">
                <div style="display: inline-block;vertical-align: top;margin-right:5px">
                  <div v-for="(item, index) in couponForm.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 class="el-icon-arrow-right" @click="moveRight(index)" v-show="index + 1 !== couponForm.images.length" />
                    <i class="el-icon-delete" @click="deteletDialogImageUrl(index)" />
                    <i class="el-icon-zoom-in" @click="enlargeDialogImageUrl(index)" />
                    <div class="dialog-img" />
                  </div>
                  <el-upload
                    :action="uploadAction"
                    :headers="headersUpload"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess"
                    with-credentials
                    :show-file-list="false"
                    v-show="uploadStatus"
                    style="display: inline-block;vertical-align: top;"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                </div>
                <p style="font-size: 12px; color: rgb(144, 147, 153);line-height:18px;margin-top:10px">
                  图片宽度≥700px，≤1500px，图片宽高比1:1，单张图片大小不超过 2 MB。
                </p>
                <el-dialog :visible.sync="dialogVisibleImg">
                  <img width="100%" :src="dialogEnlargeImageUrl" alt="">
                </el-dialog>
              </div>
            </el-form-item>
            <el-form-item label="图文信息">
              <div class="tinymce-wrap">
                <tinymce-edit ref="tinymceWrap" :bodyHtml="couponForm.detailDescription" :projectName="projectName" />
              </div>
            </el-form-item>
          </div>
          <div class="section-content">
            <h3>销售信息</h3>
            <el-form-item label="卡券费用" v-if="cardCouponList.length > 1" required>
              <el-table :data="cardCouponList" style="width:900px">
                <el-table-column label="卡券名称" prop="proRefName" />
                <el-table-column label="积分费用">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.integralCost"
                      :precision="0"
                      :min="0"
                      controls-position="right"
                      @blur="handleIntegralCostTotal"
                      @change="handleIntegralCostTotal"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="现金费用">
                  <template slot-scope="scope">
                    <el-popover
                     popper-class="noClass"
                      v-if="jifenquanxian == true"
                      placement="bottom"
                      trigger="hover"
                      content="无积分购现金权限">
                      <el-input-number
                      slot="reference"
                      :disabled="jifenquanxian"
                        v-model="scope.row.cashCost"
                        :precision="2"
                        :min="0"
                        controls-position="right"
                        @blur="handleIntegralCostTotal"
                        @change="handleIntegralCostTotal"
                      />
                    </el-popover>
                    <el-input-number
                    v-else
                      v-model="scope.row.cashCost"
                      :precision="2"
                      :min="0"
                      controls-position="right"
                      @blur="handleIntegralCostTotal"
                      @change="handleIntegralCostTotal"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item label="积分费用" prop="integralCost">
              <el-input-number
                class="w-350"
                :disabled="cardCouponList.length > 1"
                :precision="0"
                :min="0"
                v-model="couponForm.integralCost"
              />
            </el-form-item>
            <el-form-item label="现金费用" prop="cashCost">
              <el-popover
              popper-class="noClass"
                v-if="jifenquanxian == true"
                placement="bottom"
                trigger="hover"
                content="无积分购现金权限">
              <el-input-number
                slot="reference"
                class="w-350"
                :disabled="jifenquanxian"
                :precision="2"
                :min="0"
                v-model="couponForm.cashCost"
              />
              </el-popover>
              <el-input-number
                v-else
                class="w-350"
                :disabled="cardCouponList.length > 1"
                :precision="2"
                :min="0"
                v-model="couponForm.cashCost"
              />
            </el-form-item>
            <el-form-item label="礼品成本" prop="cashCost">
              <el-input-number
                class="w-350"
                :precision="2"
                :min="0"
                v-model="costValue"
                :disabled="costValueStatus"
              />
            </el-form-item>
            <el-form-item label="库存" prop="virtualStock">
              <el-input
                class="w-350"
                :precision="0"
                :min="1"
                v-model="couponForm.virtualStock"
              />
              <span
                style="font-size: 12px;color: rgb(144, 147, 153);margin-left:10px;"
                v-show="cardList.length"
              >兑换限制不得大于此优惠券的库存：<i>{{ couponCardStock }}</i>张</span>
            </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))"
                >
                  查看当前商品历史配置数据
                </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="couponForm.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="couponForm.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="couponForm.ladder" @change="changeladder" style="display:inline-block">
                <el-checkbox label="1" :disabled="!couponForm.memberGrade.length">
                  设置阶梯价
                </el-checkbox>
              </el-checkbox-group>
              <el-popover
                placement="bottom"
                width="500"
                trigger="click"
                ref="popover"
                :disabled="!(cardCouponList.length && couponForm.memberGrade.length)"
              >
                <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"
                  >
                    <el-form v-if="list3.length">
                      <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"
                            :disabled="jifenquanxian"
                            size="small"
                            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="couponForm.limitTimesStatus" @change="refashData()">
                每个会员限制兑换
              </el-checkbox>
              <span v-if="couponForm.limitTimesStatus"><el-input-number
                controls-position="right"
                v-model="couponForm.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="couponForm.exchangeDateType" :label="1">
                全部日期
              </el-radio>
              <el-radio v-model="couponForm.exchangeDateType" :label="2">
                固定日期
              </el-radio>
              <el-radio v-model="couponForm.exchangeDateType" :label="3">
                每月
              </el-radio>
              <el-radio v-model="couponForm.exchangeDateType" :label="4">
                每周
              </el-radio>
              <el-radio v-model="couponForm.exchangeDateType" :label="6">
                生日当日
              </el-radio>
              <el-radio v-model="couponForm.exchangeDateType" :label="5">
                生日当月
              </el-radio>
            </el-form-item>
            <!-- 兑换日期 -->
            <!-- 固定日期 -->
            <el-form-item class="form-item-mt" v-if="couponForm.exchangeDateType === 2" prop="exchangeFixDate">
              <el-date-picker
                class="w300"
                v-model="couponForm.exchangeFixDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <!-- 每月 -->
            <el-form-item class="form-item-mt" v-if="couponForm.exchangeDateType === 3" prop="exchangeDateDayArr">
              <el-select
                size="small"
                v-model="couponForm.exchangeDateDayArr"
                multiple
                placeholder="请选择"
                class="w-350"
              >
                <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="couponForm.exchangeDateType === 4" prop="exchangeDateWeekArr">
              <el-select
                size="small"
                v-model="couponForm.exchangeDateWeekArr"
                multiple
                placeholder="请选择"
                class="w-350"
              >
                <el-option
                  v-for="item in weekOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="兑换时段" required>
              <el-radio v-model="couponForm.exchangeTimeType" :label="1">
                全部时段
              </el-radio>
              <el-radio v-model="couponForm.exchangeTimeType" :label="2">
                部分时段
              </el-radio>
            </el-form-item>
            <div v-if="couponForm.exchangeTimeType === 2">
              <el-form-item
                class="mt8"
                v-for="(v, i) in couponForm.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:130px;">
                请使用24小时制输入时间，格式如11:00至14:30
              </p>
              <p>
                <el-button type="text" style="margin:8px 0 10px 130px" @click="addTimeRange">
                  添加时间段
                </el-button>
              </p>
            </div>
          </div>
          <div class="section-content">
            <h3>售后服务</h3>
            <el-form-item label="支持退款" prop="refundType">
               <el-radio v-model="couponForm.refundType" :label="0" :disabled="$route.query.giftId != '-1'">
                否
              </el-radio>
              <el-radio v-model="couponForm.refundType" :label="1" :disabled="$route.query.giftId != '-1'">
                是
              </el-radio>
            </el-form-item>
            <el-form-item label="退款期限" prop="refundPeriod" v-if="couponForm.refundType">
              <el-input-number v-model="couponForm.refundPeriod"
                :disabled="$route.query.giftId != '-1'"
                controls-position="right"
                :min="1"
                :max="10"
                style="width:130px"
                :step="1"
                step-strictly></el-input-number> 月
            </el-form-item>
            <el-form-item label="退款方式" prop="refundWay" v-if="couponForm.refundType">
              <el-checkbox-group v-model="couponForm.refundWay" @change="checkBoxChange" :disabled="$route.query.giftId != '-1'">
                <el-checkbox label="1">主动退款</el-checkbox>
                <el-checkbox label="2" :disabled="cardList.length > 1">过期自动退款</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>

          <!-- <div class="confim-btn" :style="{ width: fixedWidth + 'px' }">
            <el-form-item class="fix-btn">
              <el-button
                type="primary"
                size="small"
                @click="submitForm('couponForm')"
                :disabled="isInfo"
              >
                保存
              </el-button>
              <el-button size="small" @click="goBack">
                返回
              </el-button>
            </el-form-item>
          </div> -->
        </el-form>
      </div>
    </div>
    <!-- 卡券选择弹框 -->
    <vue-gic-card
      :disabledList="disabledList"
      :featureModule="projectName"
      :projectName="projectName"
      :showCardDialog.sync="showCardDialog"
      :cardLimit="cardLimit"
      :cardType="cardType"
      @selectCard="selectCard"
      tableColumnType="checkbox"
      ref="dmcard"
    />
    <dm-form-bottom>
      <el-button
        type="primary"
        size="small"
        @click="submitForm('couponForm')"
        :disabled="isInfo"
      >
        保存
      </el-button>
      <el-button size="small" @click="goBack">
        返回
      </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 tinymceEdit from '../../../components/tinymce-edit';
import visibleSetting from '@/components/visible';
import historyData from '@/components/historyData';
export default {
  components: {
    tinymceEdit,
    visibleSetting,
    historyData,
  },
  data () {
    const validateTime = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入时间'));
      } else {
        callback();
      }
    };
    const stockValidator = (rule, value, callback) => {
      const reg = /^[1-9]+\d*$/;
      if (!reg.test(Number(value))) {
        return callback(new Error('库存必须为大于0整数'));
      } else {
        callback();
      }
    };
    return {
      jifenquanxian: '',
      addCardMax: 15, // 添加卡券的上限数量
      ladder: [],
      isDifferentialPricing: '',
      ladderPriceList: [],
      ladderMemberGrade: [],
      ladderSkuList: [],
      ladderHeader: [],
      gradeIdSku: [], // gradeId与SKU结合的数据
      // ladderPrice: false,
      submitLadderList: [],
      selectTab: 0,
      list3: [],
      combineListPre: [],
      combineList: [],
      isTable: true, // 判断有无sku
      integral: '',
      cash: '',
      list2: [],
      ladderMemberGradeChange: [],
      getTime: getInputVal.getTime,
      getTime2: getInputVal.getTime2,
      fixedWidth: document.documentElement.clientWidth - 200,
      // 卡券数据
      // 可传参数
      projectName: 'integral-mall', // 当前项目名
      showCardDialog: false,
      cardLimit: -1, // 卡券限制类型 1-限制领取1张的卡券 2- 限制领取 1~100的卡券 3-限制领取>=100 的卡券
      cardType: null, // 卡券类型集合（0：抵金券，1：折扣券，2：兑换券）null-为全部类型 逗号分隔
      disabledList: [],
      selectedData: {},
      cardList: [],
      cardCouponList: [],
      limitTimesNumArr: [],
      limitTimes: 0,
      limitTimesNum: 0,
      proReferId: '', // 卡券关联id
      couponForm: {
        cardType: '', // 卡券类型
        images: [],
        detailDescription: '', // 图文详情
        integralCost: '', // 积分费用
        cashCost: '',
        virtualStock: '',
        memberLabelType: 1,
        gradeType: 1,
        memberGrade: [], // 适用会员
        limitTimesStatus: false, // 限兑
        limitTimes: '', // 限兑次数
        exchangeDateType: 1, // 兑换日期
        exchangeTimeType: 1, // 兑换时段
        exchangeFixDate: [], // 固定日期
        exchangeDateDayArr: [],
        exchangeDateWeekArr: [],
        timeRangeList: [{ timeRange: '' }], // 部分时段数组
        timeZones: ['', ''],
        ladder: [],
        refundType: 0,
        refundPeriod: 10,
        refundWay: [],
      },
      uploadAction: getInputVal.uploadAction(),
      headersUpload: {
        sign: '',
      },
      uploadStatus: true, // 上传按钮
      dialogVisibleImg: false, // 上传图片
      refash: false,
      memberGradeList: [], // 会员等级
      cliqueStatus: true, // 是否有集团卡
      monthOptions: Array.from(Array(31), (v, k) => (k + 1).toString()),
      weekOptions: ['1', '2', '3', '4', '5', '6', '7'],
      couponRules: {
        integralCost: [{ required: true, message: '请输入积分费用', trigger: 'blur' }],
        cashCost: [{ required: true, message: '请输入现金费用', trigger: 'blur' }],
        virtualStock: [{ required: true, message: '请输入库存', trigger: 'blur' }, { validator: stockValidator, trigger: 'blur' }],
        gradeType: [{ required: true, message: '请选择适用会员', trigger: 'change' }],
        memberGrade: [{ required: true, message: '请选择适用会员', trigger: 'change' }],
        exchangeFixDate: [{ required: true, message: '请选择时间', trigger: 'change' }],
        exchangeDateDayArr: [{ required: true, message: '请选择时间', trigger: 'change' }],
        exchangeDateWeekArr: [{ required: true, message: '请选择时间', trigger: 'change' }],
        proName: [{ required: true, message: '请输入券包名称', trigger: 'blur' }],
        refundWay: [{ required: true, message: '请选择退款方式', trigger: 'blur' }],
      },
      validateTime,
      mallProId: '',
      coupCardId: '', // 卡券id
      costValue: '', // 礼品成本
      costValueArr: [],
      costValueStatus: true,
      couponCardStock: '', // 优惠券库存
      couponCardStockArr: [],
      couponStatus: false, // 卡券状态
      canEdit: true,
      submitLoading: false,
      groupIdDisableList: [],
      proNameLen: 0,
      // 新版门店卡券选择器
      memberGrade: '',
      isEdit: false,
      isCorrect: true, // 校验阶梯价的验证是否可以保存阶梯价
      enterpriseId: '', // 商户id
      specialOrder: false, // 是否定制
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 24 * 3600 * 1000;
        },
      },
      isInfo: this.$route.meta.type == 'info',
      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,
      }, // 可见配置的数据源
      isCopy: this.$route.meta.type == 'copy',
      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();
    window.onbeforeunload = function (e) {
      localStorage.removeItem('giftListObj');
    };

    this.mallProId = this.$route.query.giftId;
    this.coupCardId = this.$route.query.coupCardId;
    if (this.mallProId !== '-1') {
      this.getInfo();
      this.isEdit = true;
    } else {
      this.isNew = true;
      this.getMemberGradeList(); // 会员等级列表
    }
    document.documentElement.scrollTop = 0;
  },
  methods: {
    checkBoxChange (e) {
      // console.log(e);
    },
    clearHistoryData () {
      this.$confirm('是否确认清除【展示门店数据】？清除后，可进入升级后的编辑页面。', '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning',
      }).then(() => {
        this.jump(3);
        this.isNew = true;
      });
    },
    jump (index) {
      const jump = document.querySelectorAll('.section-content');
      const total = jump[index].offsetTop;
      let distance = document.documentElement.scrollTop || document.body.scrollTop;
      const step = total / 50;
      if (total > distance) {
        smoothDown();
      }
      function smoothDown () {
        if (distance < total) {
          distance += step;
          document.body.scrollTop = distance;
          document.documentElement.scrollTop = distance;
          setTimeout(smoothDown, 10);
        }
      }
    },
    // 阶梯价定制，判断达摩测试环境与地素环境
    // 达摩测试 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 () {
      if (!this.cardCouponList.length) {
        this.$message.error('请先添加卡券');
        return;
      }
      this.ladderMemberGrade = [];
      const lists = this.memberGradeList.filter(item => {
        return this.couponForm.memberGrade.join(',').indexOf(item.gradeId) != -1;
      });
      lists.forEach(item => {
        this.ladderMemberGrade.push({
          gradeId: item.gradeId,
          gradeName: item.gradeName,
        });
      });
      this.list2 = copy(this.ladderMemberGrade);
      this.ladderSkuList = copy(this.cardCouponList);
      this.ladderSkuList.forEach(item => {
        item.giftProSkuIntegral = '';
        item.giftProSkuCash = '';
      });
      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) {
              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 === '' || 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;
      }
    },
    refashData () {
      this.refash = !this.refash;
    },
    getOpenStatus () {
      request.post('/api-integral-mall/is-show-self ').then(res => {
        this.visibleData.openFlag = res.data.result.openFlag;
        if (this.openFlag) {
          this.visibleData.sendChildData.storeType = 1;
        }
      });
    },
    getDisGroupList (arr) {
      this.groupIdDisableList = arr;
      // if (this.mallProId !== '-1') {
      //   this.getInfo();
      // }
    },
    handleChange () {
      this.couponForm.memberGrade = [];
      this.getMemberGradeList();
    },
    // 获取会员等级
    async getMemberGradeList () {
      return request.post('/api-integral-mall/load-grade').then(res => {
        if (res.data.errorCode === 0) {
          this.cliqueStatus = !!res.data.result.cliqueGrade;
          if (this.couponForm.gradeType === 1) {
            // 品牌卡
            this.memberGradeList = res.data.result.enterpriseGrade || [];
          } else if (this.couponForm.gradeType === 2) {
            this.memberGradeList = res.data.result.cliqueGrade || [];
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 获取详情
    getInfo () {
      const params = {
        integralMallProId: this.mallProId,
      };
      this.submitLoading = true;
      request.post('/api-integral-mall/get-integral-mall-pro', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          this.submitLoading = false;
          this.coupCardId = res.data.result.proReferId;
          if (this.coupCardId !== '-1') {
            this.proReferId = this.coupCardId;
            this.getCardInfo();
          }
          this.couponForm.refundType = res.data.result.refundType ? res.data.result.refundType : 0;
          this.couponForm.refundPeriod = res.data.result.refundPeriod ? res.data.result.refundPeriod : 10;
          this.couponForm.refundWay = res.data.result.refundWay ? res.data.result.refundWay.split(',') : [];
          this.echoVisibleData(res.data.result);
          this.couponForm.proName = res.data.result.proName;
          this.proNameLen = getInputVal.getZhLen(this.couponForm.proName);
          this.couponForm.ladder = res.data.result.isDifferentialPricing ? ['1'] : []; // 是否设置阶梯价
          if (this.couponForm.ladder.length) {
            this.isDifferentialPricing = this.couponForm.ladder[0];
          }
          if (this.isDifferentialPricing && res.data.result.gradeProSkus && res.data.result.gradeProSkus.length > 0) {
            this.list3 = res.data.result.gradeProSkus; // 阶梯价详情
            this.submitLadderList = res.data.result.gradeProSkus;
          } else {
            this.list3 = [];
          }
          // 积分费用包
          if (res.data.result.cardCostList) {
            this.cardCouponList = res.data.result.cardCostList;
          } else {
            this.cardCouponList.push({
              proRefId: '',
              proRefName: '',
              integralCost: undefined,
              cashCost: undefined,
            });
          }
          // 积分费用
          this.couponForm.integralCost = res.data.result.integralCost;
          // 现金费用
          this.couponForm.cashCost = res.data.result.cashCost;
          // 库存
          this.couponForm.virtualStock = res.data.result.virtualStock;
          this.currentStock = res.data.result.virtualStock;
          this.couponForm.detailDescription = res.data.result.detailDescription; // 图文详情
          this.hasSearchData = res.data.result.searchParams;
          // 适用会员
          this.couponForm.gradeType = res.data.result.gradeType;
          this.getMemberGradeList()
            .then(() => {
              if (res.data.result.memberGrade) {
                this.memberGrade = res.data.result.memberGrade;
                this.couponForm.memberGrade = res.data.result.memberGrade.split(','); // 适用会员
              } else {
                this.memberGrade = '';
                this.couponForm.memberGrade = [];
              }
            })
            .finally(() => {
              if (this.$route.query.proReferId !== '-1') {
                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,
                  });
                });
              }
            }); // 会员等级列表
          if (res.data.result.images) {
            // 主图
            this.couponForm.images = [];
            for (const item of res.data.result.images) {
              this.couponForm.images.push({
                imageUrl: item.imageUrl,
                imageCode: item.imageFieldCode,
              });
            }
          }
          if (this.couponForm.images.length >= 1) {
            this.uploadStatus = false;
          } else {
            this.uploadStatus = true;
          }
          this.refash = !this.refash;
          // 限兑
          if (res.data.result.limitTimes === -1) {
            this.couponForm.limitTimesStatus = false;
          } else {
            this.couponForm.limitTimesStatus = true;
          }
          // 限兑
          this.couponForm.limitTimes = res.data.result.limitTimes;

          this.costValue = res.data.result.costValue; // 礼品陈本
          // 兑换日期
          this.couponForm.exchangeDateType = res.data.result.exchangeDateType;

          if (this.couponForm.exchangeDateType === 2) {
            this.couponForm.exchangeFixDate = [];
            this.couponForm.exchangeFixDate.push(res.data.result.exchangeFixDateBegin);
            this.couponForm.exchangeFixDate.push(res.data.result.exchangeFixDateEnd);
          } else if (this.couponForm.exchangeDateType === 3) {
            this.couponForm.exchangeDateDayArr = res.data.result.exchangeDateDay.split(',');
            this.couponForm.exchangeDateWeekArr = [];
          } else if (this.couponForm.exchangeDateType === 4) {
            this.couponForm.exchangeDateWeekArr = res.data.result.exchangeDateWeek.split(',');
            this.couponForm.exchangeDateDayArr = [];
          }

          // 兑换时段
          this.couponForm.exchangeTimeType = res.data.result.exchangeTimeType;
          // 部分时间段
          let timeDate;
          let timeRangeList;
          if (this.couponForm.exchangeTimeType === 2) {
            timeDate = res.data.result.timeZones.split('#');
            timeRangeList = [];
            for (const item of timeDate) {
              timeRangeList.push({
                timeRange: item.split('-'),
              });
            }
            this.couponForm.timeRangeList = timeRangeList;
          }
        } else {
          this.submitLoading = false;
          this.$message.error(res.data.message);
        }
      });
    },
    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);
    },
    // 礼品字数限制
    goodsLimit (value) {
      this.$nextTick(() => {
        this.couponForm.proName = getInputVal.getInputVal(value, 30);
        this.proNameLen = getInputVal.getZhLen(this.couponForm.proName);
      });
    },
    // 获取卡券详情
    getCardInfo () {
      const params = {
        coupCardId: this.coupCardId,
      };
      request.post('/api-integral-mall/get-card', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          // 退款方式
          if (res.data.result.refundWay) {
            this.couponForm.refundWay = res.data.result.refundWay.split(',');
          }
          this.cardList = [];
          this.cardList = res.data.result;
          if (this.cardList.length === 1) {
            this.cardCouponList[0].proRefName = this.cardList[0].cardName;
            this.cardCouponList[0].proRefId = this.cardList[0].coupCardId;
          }
          if (this.cardList) {
            this.couponForm.cardType = this.cardList[0].cardType;
            for (const item of this.cardList) {
              this.limitTimesNumArr.push(item.cardLimit);
              this.couponCardStockArr.push(item.couponStock);
              this.limitTimes = Math.min.apply(null, this.limitTimesNumArr);
              this.limitTimesNum = Math.min.apply(null, this.limitTimesNumArr);
              this.couponCardStock = Math.min.apply(null, this.couponCardStockArr);
            }
            const params = {
              coupCardId: this.cardList.map(item => item.coupCardId).join(','),
              proType: 1,
            };
            this.getCardCost(params);
          }
          this.couponStatus = this.cardList.some(item => {
            return item.status === 0;
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    limitTimeChange () {
      if (this.cardList.length) {
        if (Number(this.couponForm.limitTimes) > Number(this.limitTimes)) {
          this.$message.error('兑换限制不得大于此优惠券的领取次数');
          // this.couponForm.limitTimes = this.limitTimes;
          return false;
        }
      } else {
        this.limitTimesNum = this.couponForm.limitTimes;
      }
    },

    // 显示卡券弹窗
    showCard () {
      if (this.cardList.length >= this.addCardMax) return;
      this.showCardDialog = true;
    },
    // 子组件触发方法
    selectCard (arr) {
      // console.log(arr);
      // console.log(this.cardList);
      if (arr.length > 1) {
        const index = this.couponForm.refundWay.indexOf('2');
        if (index != -1) {
          this.couponForm.refundWay.splice(index, 1);
        }
      }

      if (arr.length + this.cardList.length > 15) {
        this.$message.error(`最多支持添加15张卡券,目前一共选择${arr.length + this.cardList.length}张卡券`);
        return;
      }
      this.showCardDialog = false;
      if (arr.length) {
        // 重复卡券去掉
        arr.forEach((val) => {
          if (
            !this.cardList.find(row => {
              return row.coupCardId === val.coupCardId;
            })
          ) {
            this.cardList.push(val);
            this.cardCouponList.push({
              proRefId: val.coupCardId,
              proRefName: val.cardName,
              integralCost: undefined,
              cashCost: undefined,
            });
            this.limitTimesNumArr.push(val.cardLimit);
            this.couponCardStockArr.push(val.couponStock);
            // console.log(this.couponCardStockArr);
            this.limitTimes = Math.min.apply(null, this.limitTimesNumArr);
            this.limitTimesNum = Math.min.apply(null, this.limitTimesNumArr);
            this.couponCardStock = Math.min.apply(null, this.couponCardStockArr);
            this.couponForm.limitTimesStatus = true;
          }
        });
        const params = {
          coupCardId: this.cardList.map(item => item.coupCardId).join(','),
          proType: 1,
        };
        this.getCardCost(params);
      }
      // console.log(this.limitTimesNumArr);
    },
    async getCardCost (params) {
      const res = await request.post('/api-integral-mall/get-integral-mall-CashCost', qs.stringify(params));
      if (res.data.errorCode === 0) {
        if (res.data.result.costValue) {
          this.costValueArr = [];
          const arr = res.data.result.costValue.split(',');
          arr.forEach(item => {
            this.costValueArr.push(Number(item));
          });
          const sum = this.costValueArr.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          this.costValue = sum;
        }
      } else {
        this.$message.error(res.data.message);
      }
    },
    deleteCard (index) {
      this.cardList.splice(index, 1);
      this.cardCouponList.splice(index, 1);
      this.costValueArr.splice(index, 1);
      this.couponCardStockArr.splice(index, 1);// 删除对应 卡券库存数组中的值
      this.limitTimesNumArr.splice(index, 1);// 删除对应 卡券领取限制数组中的值
      if (this.costValueArr.length) {
        const sum = this.costValueArr.reduce(function (prev, cur, index, array) {
          return prev + cur;
        });
        this.costValue = sum;
      } else {
        this.costValue = 0;
      }
      if (this.cardList.length > 0) {
        this.limitTimesNumArr = [];
        this.couponCardStockArr = [];
        for (const item of this.cardList) {
          this.limitTimesNumArr.push(item.cardLimit);
          this.couponCardStockArr.push(item.couponStock);
          this.limitTimes = Math.min.apply(null, this.limitTimesNumArr);
          this.limitTimesNum = Math.min.apply(null, this.limitTimesNumArr);
          this.couponCardStock = Math.min.apply(null, this.couponCardStockArr);
        }
      } else {
        this.limitTimes = '';
        this.limitTimesNum = '';
        this.couponCardStock = '';
        this.couponForm.limitTimesStatus = false;
      }
      // console.log(this.limitTimesNumArr);
      // console.log(this.cardList);
    },
    // 券包积分计算
    handleIntegralCostTotal () {
      let total = 0;
      let totalCash = 0;
      for (const item of this.cardCouponList) {
        if (item.integralCost) {
          total = total + Number(item.integralCost);
        } else {
          total = total + 0;
        }
        if (item.cashCost) {
          totalCash = totalCash + Number(item.cashCost);
        } else {
          totalCash = totalCash + 0;
        }
      }
      this.couponForm.integralCost = total;
      this.couponForm.cashCost = totalCash;
    },
    // 添加兑换时段
    addTimeRange () {
      if (this.couponForm.timeRangeList.length >= 5) {
        this.$message.error('最多五个时间段');
        return false;
      }
      this.couponForm.timeRangeList.push({ timeRange: '' });
    },
    // 删除兑换时段
    delTimeRange (index) {
      this.couponForm.timeRangeList.splice(index, 1);
    },

    // 图片上传
    // 上传图片前
    beforeUpload (file) {
      if (this.couponForm.images === null) {
        this.couponForm.images = [];
      }
      if (this.couponForm.images.length > 4) {
        this.$message.warning('最多上传5张商品主图');
        return false;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error('请上传小于2MB的图片');
        return false;
      }
      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 = '';
      }
      const that = this;
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (event) {
          const image = new Image();
          image.onload = function () {
            const width = this.width;
            const height = this.height;
            if (width < 700 || width > 1500 || width / height != 1) {
              that.$message.error('请上传正确的图片尺寸');
              reject();
            }
            resolve();
          };
          image.src = event.target.result;
        };
        reader.readAsDataURL(file);
      });
    },
    // 预览
    handlePictureCardPreview (file) {
      this.couponForm.images = file.url;
      this.dialogVisibleImg = true;
    },
    // 上传图片成功
    uploadSuccess (response, file, fileList) {
      if (response.errorCode === 0) {
        this.couponForm.images.push({
          imageUrl: response.result[0].qcloudImageUrl,
          imageCode: response.result[0].imageFiledCode,
        });
        this.$message.success('上传成功');
        if (this.couponForm.images.length === 1) {
          this.uploadStatus = false;
        } else {
          this.uploadStatus = true;
        }
      } else {
        this.$message.error(response.message);
      }
    },
    // 删除
    deteletDialogImageUrl (index) {
      this.uploadStatus = true;
      this.couponForm.images.splice(index, 1);
    },
    // 放大
    enlargeDialogImageUrl (index) {
      this.dialogEnlargeImageUrl = this.couponForm.images[index].imageUrl;
      this.dialogVisibleImg = true;
    },
    // 左移一位
    moveLeft (index) {
      this.swapArray(this.couponForm.images, index, index - 1);
    },
    // 右移一位
    moveRight (index) {
      this.swapArray(this.couponForm.images, index, index + 1);
    },
    // 两个数据条换位置
    swapArray (arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
    // 提交数据
    async submitForm (couponForm) {
      this.couponForm.detailDescription = this.$refs.tinymceWrap.tinymceHtml;
      const proReferIdArr = [];
      if (!this.cardList.length) {
        this.$message.error('请选择卡券');
        return false;
      } else if (this.isCopy && this.cardList.filter(item => item.status && item.status != 1).length) {
        this.$message.error('选择了无效卡券，无法保存');
        return false;
      } else {
        for (const item of this.cardList) {
          proReferIdArr.push(item.coupCardId);
        }
      }

      if (this.cardList.length) {
        if (Number(this.couponForm.limitTimes) > Number(this.limitTimes)) {
          this.$message.error('兑换限制不得大于此优惠券的领取次数');
          return false;
        }
      }
      if (this.cardCouponList.length > 1) {
        for (const item of this.cardCouponList) {
          if (item.integralCost === undefined) {
            this.$message.error('卡券积分不能为空');
            return false;
          }
          if (item.cashCost === undefined && !this.jifenquanxian) {
            this.$message.error('卡券积分或现金不能为空');
            return false;
          }
        }
      }
      if (Number(this.couponForm.virtualStock) > Number(this.couponCardStock)) {
        this.$message.error('礼品库存不能大于卡券库存 ');
        return false;
      }
      if (this.couponForm.limitTimesStatus) {
        if (Number(this.couponForm.limitTimes) === 0) {
          this.$message.error('限兑次数不能为0');
          return false;
        }
      }
      if (this.cardList.length > 1) {
        if (this.couponForm.images.length === 0) {
          this.$message.error('券包上传商品主图');
          return false;
        }
      } else {
        if (this.cardList[0].cardType === 2) {
          // 兑换券必须上传主图
          if (this.couponForm.images.length === 0) {
            this.$message.error('兑换券要上传商品主图');
            return false;
          }
        }
      }

      const giftImageUrls = [];
      const giftImageFiledCodes = [];
      for (const item of this.couponForm.images) {
        giftImageUrls.push(item.imageUrl);
        giftImageFiledCodes.push(item.imageCode);
      }
      const data = await this.$refs.visibleSetting.submit();
      if (!data) return false;
      this.$refs[couponForm].validate(valid => {
        if (valid) {
          let params = {
            proName: this.cardList.length > 1 ? this.couponForm.proName : this.cardList[0].cardName,
            integralMallProId: this.isCopy ? '' : (this.mallProId === '-1' ? '' : this.mallProId), // 礼品id
            proType: 1, // 优惠券
            proReferId: proReferIdArr.join(','), // 卡券id
            cardCostList: this.cardCouponList.length > 1 ? this.cardCouponList : null,
            detailDescription: this.couponForm.detailDescription, // 图文详情
            giftImageUrls: giftImageUrls.join(','), // 礼品主图
            giftImageFiledCodes: giftImageFiledCodes.join(','),
            cardType: this.cardList[0].cardType,
            integralCost: this.couponForm.integralCost, // 积分费用
            costValue: this.costValue, // 礼品成本
            cashCost: this.couponForm.cashCost, // 现金
            virtualStock: this.isCopy ? this.couponForm.virtualStock : (this.isEdit ? this.couponForm.virtualStock - (this.currentStock || 0) : this.couponForm.virtualStock), // 库存
            gradeType: this.couponForm.gradeType,
            memberGrade: this.couponForm.memberGrade.join(','), // 适用会员
            limitTimes: this.couponForm.limitTimesStatus ? this.couponForm.limitTimes : '-1', // 限兑
            exchangeDateType: this.couponForm.exchangeDateType, // 兑换日期
            exchangeFixDateBegin: this.couponForm.exchangeDateType === 2 ? this.getTime(this.couponForm.exchangeFixDate[0]) : '', // 固定日期
            exchangeFixDateEnd: this.couponForm.exchangeDateType === 2 ? this.getTime(this.couponForm.exchangeFixDate[1]) : '',
            exchangeDateDay: this.couponForm.exchangeDateType === 3 ? this.couponForm.exchangeDateDayArr.join(',') : '', // 兑换日期月
            exchangeDateWeek: this.couponForm.exchangeDateType === 4 ? this.couponForm.exchangeDateWeekArr.join(',') : '', // 兑换日期周
            exchangeTimeType: this.couponForm.exchangeTimeType, // 兑换时段
            isDifferentialPricing: this.isDifferentialPricing,
            differentialPricingJson: JSON.stringify(this.submitLadderList),
            refundType: this.couponForm.refundType,
            refundPeriod: this.couponForm.refundPeriod,
            refundWay: this.couponForm.refundWay.toString(),
          };
          // 可见配置参数组装
          params = { ...params, ...data };
          // 部分时段时间转换
          const timeLink = [];
          if (this.couponForm.exchangeTimeType === 2) {
            for (const item of this.couponForm.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);
        console.log('保存');
      });
    },
    saveDeatail (params) {
      request.post('/api-integral-mall/create-integral-pro', params).then(res => {
        if (res.data.errorCode === 0) {
          this.$message.success('保存成功');
          this.$router.push({
            name: 'coupon',
          });
        } else {
          this.$message.error(res.data.message);
        }
      }).finally(() => {
        this.submitLoading = false;
      });
    },
    goBack () {
      this.$router.push({
        name: 'coupon',
      });
    },
  },
};
</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-content .el-form-item {
  margin-left: 32px;
}
.w-350 {
  width: 350px;
}

.form-item-mt {
  margin-top: -12px;
}
/* 固定按钮 */
.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;
}
.mb8 {
  margin-bottom: 8px;
}
/* 主图 */
.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;
}
.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;
}
.alert-content {
  width: 500px;
  margin: 22px 0 22px 133px;
}
.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>
.select-shop__right {
  line-height: 28px !important;
}

.upload-list-box .el-upload--picture-card {
  width: 104px;
  height: 104px;
  line-height: 104px;
}
.upload-list-box .el-upload--picture-card {
  width: 104px;
  height: 104px;
  line-height: 104px;
}
.select-shop__right {
  line-height: 28px !important;
}
.section-tip-content .el-form-item__label {
  text-align: left !important;
}
/* 人群筛选器
.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>
