<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>{{ mallProId === '-1' ? '新建' : '编辑' }}优惠券</el-breadcrumb-item>
        </el-breadcrumb>
        <h3>
          <span>{{ mallProId === '-1' ? '新建' : '编辑' }}优惠券</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"
        >
          <div class="section-content">
            <h3>选择卡券</h3>
            <el-form-item label="选择卡券" required v-show="mallProId === '-1'">
              <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="操作" v-if="mallProId === '-1'">
                <template slot-scope="scope">
                  <dm-delete @confirm="deleteCard(scope.$index)" tips="确定删除该卡券吗?">
                    <el-button type="text">
                      删除
                    </el-button>
                  </dm-delete>
                </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>
            <!-- <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>
                    <i class="el-icon-arrow-right" @click="moveRight(index)" v-show="index + 1 !== couponForm.images.length"></i>
                    <i class="el-icon-delete" @click="deteletDialogImageUrl(index)"></i>
                    <i class="el-icon-zoom-in" @click="enlargeDialogImageUrl(index)"></i>
                    <div class="dialog-img"></div>
                  </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"></i>
                  </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> -->
          </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-input-number
                      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-input-number
                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></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 class="tips">不符合此处会员等级卡的客户在小程序积分商城中不可见该礼品</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-input 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="会员筛选">
              <div style="margin-right:24px;">
                <vue-gic-people :projectName="projectName" :useId="useId" :hasSearchData="hasSearchData" :sceneValue="sceneValue" ref="peopleFilter" :isAdd="operateType" @findFilter="findFilter" @getBackData="getBackData" @editHide="editHide" @editShow="editShow" @hideBtn="hideBtn"> </vue-gic-people>
                <div class="gic-people--button" v-show="toggleTag">
                  <el-button size="small" type="primary" @click="getData">确 定</el-button>
                  <el-button size="small" @click="cancelFilter">取 消</el-button>
                </div>
              </div>
            </el-form-item> -->
            <!-- <el-form-item label="展现门店" required style="position:relative">
              <vue-gic-store-linkage :disabled="isInfo" :msg="sendChildData" @getDisGroupList="getDisGroupList" :openFlag="openFlag" ref="selectTree" @sendSelectGroupData="getSelectGroupData"></vue-gic-store-linkage>
              <span v-if="sendChildData.storeType === 1" class="store-tip">若选中的门店分组下有新增的门店，系统不会默认选中此新增门店，请重新确认选择并保存礼品</span>
            </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>可见配置<span class="sub_title">该配置决定客户是否可见</span></h3>
            <el-form-item label="上架时间" required>
              <el-radio v-model="couponForm.releaseType" :label="1">
                立即上架
              </el-radio>
              <el-radio v-model="couponForm.releaseType" :label="2">
                自定义上架时间段
              </el-radio>
            </el-form-item>
            <!-- 定时上架 -->
            <el-form-item class="form-item-mt" v-if="couponForm.releaseType === 2" prop="limitTimeBegin">
              <el-date-picker
                v-model="couponForm.limitTimeBegin"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item label="显示状态" required>
              <el-radio-group v-model="couponForm.proShowStatus">
                <el-radio :label="1">
                  上架状态就显示
                </el-radio>
                <el-radio :label="2">
                  兑换状态下显示
                </el-radio>
              </el-radio-group>
              <div v-if="couponForm.proShowStatus == 1" style="margin-left:20px;">
                <el-checkbox v-model="couponForm.isNewGuestVisible" :true-label="1" :false-label="0">
                  非会员可见
                </el-checkbox>
                <span class="tips">开启后，未开卡客户在积分商城也可见该礼品（前提是该礼品的“适用会员”包含最低会员卡等级）</span>
              </div>
            </el-form-item>
            <el-form-item
              label="展现门店"
              required
              style="position:relative"
              v-if="useNewStoreWidget === 0"
            >
              <el-tooltip
                class="tips-content"
                popper-class="store-tips"
                effect="dark"
                placement="top-start"
              >
                <div slot="content" style="line-height:18px">
                  会员的门店(常规设置)满足展示门店设置，则在礼品/优惠券列表可见
                </div>
                <i class="iconfont icon-xinxixianshi" style="color:#1890ff" />
              </el-tooltip>
              <vue-gic-store-linkage
                style="margin-left:10px"
                v-if="(mallProId && creatorId) || mallProId == -1"
                :creatorId="creatorId"
                :disabled="isInfo"
                @getDisGroupList="getDisGroupList"
                :msg="sendChildData"
                :openFlag="openFlag"
                ref="selectTree"
                @sendSelectGroupData="getSelectGroupData"
              />
              <span v-if="sendChildData.storeType === 1" class="store-tip">若选中的父分组下有新增的门店分组，系统不会默认选中此新增门店分组，请重新确认选择并保存礼品</span>
            </el-form-item>
            <el-form-item label="展现门店" v-if="useNewStoreWidget === 1" class="store-card">
              <el-tooltip
                class="tips-content"
                popper-class="store-tips"
                effect="dark"
                placement="top-start"
              >
                <div slot="content" style="line-height:18px">
                  会员的门店(常规设置)满足展示门店设置，则在礼品/优惠券列表可见
                </div>
                <i class="iconfont icon-xinxixianshi" style="color:#1890ff" />
              </el-tooltip>
              <vue-gic-store-card
                style="margin-left:10px"
                class="pt10"
                ref="storeCard"
                :uuid.sync="uuid"
                scenes=""
              />
            </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="!canEdit" :loading="submitLoading">保存</el-button> -->
              <el-button
                type="primary"
                size="small"
                @click="submitForm('couponForm')"
                :disabled="!canEdit"
              >
                保存
              </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"
      ref="dmcard"
    />
  </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';
export default {
  components: {
    tinymceEdit,
  },
  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 {
      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: [],
      getTimeAll: getInputVal.formatDate,
      getTime: getInputVal.getTime,
      getTime2: getInputVal.getTime2,
      getHours: getInputVal.getHours,
      fixedWidth: document.documentElement.clientWidth - 200,
      // 卡券数据
      // 可传参数
      projectName: 'integral-mall', // 当前项目名
      showCardDialog: false,
      // cardLimit: 3, //卡券限制类型 1-限制领取1张的卡券 2- 限制领取 1~100的卡券 3-限制领取&=100 的卡券
      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: '', // 限兑次数
        releaseType: 1, // 上架时间
        proShowStatus: 1, // 显示状态
        exchangeDateType: 1, // 兑换日期
        exchangeTimeType: 1, // 兑换时段
        exchangeFixDate: [], // 固定日期
        exchangeDateDayArr: [],
        exchangeDateWeekArr: [],
        timeRangeList: [{ timeRange: '' }], // 部分时段数组
        limitTimeBegin: [],
        timeZones: ['', ''],
        isNewGuestVisible: 0, // 0：新客不可见、1：新客可见
        dataDialogueId: '', // 数据对话id
        ladder: [],
      },
      uploadAction: window.location.origin + '/api-plug/upload-img?requestProject=integral-mall',
      // uploadAction: 'http://gicdev.demogic.com/api-plug/upload-img?requestProject=integral-mall',
      headersUpload: {
        sign: '',
      },
      uploadStatus: true, // 上传按钮
      dialogVisibleImg: false, // 上传图片
      refash: false,
      memberGradeList: [], // 会员等级
      // 门店控件
      sendChildData: {
        storeType: 1,
        storeGroupIds: '',
        storeIds: [],
      },
      cliqueStatus: true, // 是否有集团卡
      openFlag: false,
      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' }],
        limitTimeBegin: [{ required: true, message: '请选择时间', trigger: 'change' }],
        proName: [{ required: true, message: '请输入券包名称', trigger: 'blur' }],
      },
      validateTime,
      mallProId: '',
      coupCardId: '', // 卡券id
      costValue: '', // 礼品成本
      costValueArr: [],
      costValueStatus: true,
      couponCardStock: '', // 优惠券库存
      couponCardStockArr: [],
      couponStatus: false, // 卡券状态
      canEdit: true,
      submitLoading: false,
      groupIdDisableList: [],
      proNameLen: 0,
      creatorId: '',
      useNewStoreWidget: 1, // 1新的卡券门店组件 ，0老的门店组件
      // 新版门店卡券选择器
      uuid: '',
      isAdd: true,
      // 人群筛选器
      // // 可传参数
      // // projectName: 'integral-mall', // 当前项目名
      // getSaveData: '',
      // sceneValue: 'member', // 场景值
      // useId: '', // 模板id
      // hasSearchData: '', // 当前页回显的数据(接口返回)
      // operateType: true, // 编辑的时候是false 新增是true 例如列表筛选是开始true 编辑改成false
      // toggleTag: false, // 控制(确认取消)按钮显示的参数,仅供参考,可自行修改
      // saveTag: false, // 控制(保存)按钮显示的参数,仅供参考,可自行修改
      // searchParams: {}, //查询数据数据
      // responseParams: [] //回显的数据
      memberGrade: '',
      isEdit: false,
      isCorrect: true, // 校验阶梯价的验证是否可以保存阶梯价
      enterpriseId: '', // 商户id
      specialOrder: false, // 是否定制
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 24 * 3600 * 1000;
        },
      },
    };
  },
  mounted () {
    this.getOpenStatus();
    this.getUserId();
    window.onbeforeunload = function (e) {
      localStorage.removeItem('giftListObj');
    };
    const val = {
      storeType: 0,
      storeGroupIds: '',
      storeIds: [],
    };
    this.getSelectGroupData(val);
    this.mallProId = this.$route.query.giftId;
    this.canEdit = Boolean(this.$route.query.canEdit);
    this.coupCardId = this.$route.query.coupCardId;

    // if (this.mallProId !== '-1') {
    //   this.getInfo();
    //   this.getDisGroupList();
    // }

    if (this.mallProId !== '-1') {
      this.getInfo();
      this.isAdd = false;
      this.isEdit = true;
    } else {
      this.getMemberGradeList(); // 会员等级列表
    }
  },
  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 () {
      // this.ladderMemberGradeChange = [];
      // let lists = this.memberGradeList.filter(item => {
      //   return this.couponForm.memberGrade.join(',').indexOf(item.gradeId) != -1;
      // });
      // lists.forEach(item => {
      //   this.ladderMemberGradeChange.push({
      //     gradeId: item.gradeId,
      //     gradeName: item.gradeName
      //   });
      // });
      // console.log(this.ladderMemberGradeChange);
      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) {
              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 => {
        if (res.data.errorCode === 0) {
          this.openFlag = res.data.result.openFlag;
          if (this.openFlag) {
            this.sendChildData.storeType = 1;
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    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.couponForm = res.data.result;
          this.coupCardId = res.data.result.proReferId;
          if (this.coupCardId !== '-1') {
            this.proReferId = this.coupCardId;
            this.getCardInfo();
          }
          this.couponForm.proName = res.data.result.proName;
          this.proNameLen = getInputVal.getZhLen(this.couponForm.proName);
          this.couponForm.isNewGuestVisible = res.data.result.isNewGuestVisible || 0; // 新客是否可见
          // this.list3 = res.data.result.gradeProSkus && res.data.result.gradeProSkus.length ? res.data.result.gradeProSkus : []; // 阶梯价详情
          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 = [];
          }
          // console.log(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; // 图文详情
          // if (res.data.result.searchParams) {
          //   this.searchParams = res.data.result.searchParams; //会员筛选
          // } else {
          //   this.searchParams = {};
          // }

          // if (res.data.result.responseParams) {
          //   this.responseParams = res.data.result.responseParams;
          // } else {
          //   this.responseParams = [];
          // }

          // this.useId = res.data.result.integralMallProId;
          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.memberGrade) {
          //   this.couponForm.memberGrade = res.data.result.memberGrade.split(',');
          // } else {
          //   this.couponForm.memberGrade = [];
          // }
          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.creatorId = res.data.result.creatorId;
          this.refash = !this.refash;
          this.useNewStoreWidget = res.data.result.useNewStoreWidget;
          if (this.useNewStoreWidget === 0) {
            this.sendChildData.storeType = Number(res.data.result.showStore);

            if (this.sendChildData.storeType === 1) {
              const arr = res.data.result.storeGroupIds.split(',');
              for (let i = 0; i < arr.length; i++) {
                if (this.groupIdDisableList.indexOf(arr[i]) !== -1) {
                  // 存在
                  // console.log('不可删除的');
                  arr.splice(i, 1);
                  i--;
                }
              }
              this.sendChildData.storeGroupIds = arr.join(',');
              // this.sendChildData.storeGroupIds = res.data.result.storeGroupIds || '';
            } else if (this.sendChildData.storeType === 2) {
              const list = [];
              if (res.data.result.storeInfo) {
                res.data.result.storeInfo.forEach(v => {
                  list.push(v);
                });
              }
              this.sendChildData.storeIds = list;
            }
            this.getSelectGroupData(this.sendChildData);
          } else if (this.useNewStoreWidget === 1) {
            this.uuid = res.data.result.storeWidgetId;
            this.$nextTick(_ => {
              // console.log(this.$refs.storeCard);
              this.$refs.storeCard.init();
            });
          }
          // 限兑
          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;
          }

          // 显示状态
          this.couponForm.proShowStatus = res.data.result.proShowStatus;
          // 上架时间
          this.couponForm.releaseType = res.data.result.releaseType;
          if (this.couponForm.releaseType === 2) {
            this.couponForm.limitTimeBegin[0] = res.data.result.limitTimeBegin || '';
            this.couponForm.limitTimeBegin[1] = res.data.result.limitTimeEnd || '';
          } else {
            this.couponForm.limitTimeBegin = [];
          }
          // 数据对话id
          this.couponForm.dataDialogueId = res.data.result.dataDialogueId;
        } else {
          this.submitLoading = false;
          this.$message.error(res.data.message);
        }
      });
    },
    // 礼品字数限制
    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) {
          this.cardList = [];
          this.cardList = res.data.result;
          if (this.cardList.length === 1) {
            this.cardCouponList[0].proName = 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) {
              // item.beginDate = this.getTime2(item.beginDate);
              // item.endDate = this.getTime2(item.endDate);
              // item.putBeginDate = this.getTime2(item.putBeginDate);
              // item.putEndDate = this.getTime2(item.putEndDate);
              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);
            }
          }
          this.couponStatus = this.cardList.some(item => {
            return item.status === 0;
          });
          // if (res.data.result.status) {
          //   this.couponStatus = true;
          // } else {
          //   this.couponStatus = false;
          // }
          // this.limitTimes = Number(res.data.result.cardLimit);
          // this.limitTimesNum = res.data.result.cardLimit;
          // this.couponCardStock = res.data.result.couponStock;
          // this.couponForm.virtualStock = this.couponCardStock;
          // this.couponForm.proName = res.data.result.cardName;
        } 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;
      }
    },
    // 门店分类回执方法
    getSelectGroupData (val) {
      this.sendChildData = {
        storeType: val.storeType || 0,
        storeGroupIds: val.storeGroupIds || '',
        storeIds: val.storeIds || [],
      };
    },
    // 显示卡券弹窗
    showCard () {
      if (this.cardList.length >= this.addCardMax) return;
      this.showCardDialog = true;
    },
    // 子组件触发方法
    selectCard (val) {
      this.showCardDialog = false;
      // this.cardList = [];

      if (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);
        } else {
          this.$message.error('重复的卡券不允许');
          return;
        }
        // this.limitTimes = val.cardLimit;
        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.limitTimesNum = val.cardLimit;
        // this.proReferId = val.coupCardId;
        // this.couponForm.cardType = val.cardType;
        // this.couponCardStock = val.couponStock;

        // this.couponForm.virtualStock = this.couponCardStock;
        // this.couponForm.proName = val.cardName;
        this.couponForm.limitTimesStatus = true;
        const params = {
          coupCardId: val.coupCardId,
          proType: 1,
        };
        request.post('/api-integral-mall/get-integral-mall-CashCost', qs.stringify(params)).then(res => {
          if (res.data.errorCode === 0) {
            this.costValueArr.push(res.data.result.costValue);
            // 计算数组的总和
            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);
      const sum = this.costValueArr.reduce(function (prev, cur, index, array) {
        return prev + cur;
      });
      this.costValue = sum;
      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;
      }
    },
    // 券包积分计算
    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;
    },
    // 校验datePricker
    vaidataDataPicker () {
      const endTime = this.couponForm.limitTimeBegin[1];
      const startTime = this.couponForm.limitTimeBegin[0];
      const currentTime = new Date().getTime();
      return endTime > currentTime && endTime > startTime;
    },
    // 提交数据
    async submitForm (couponForm) {
      this.couponForm.detailDescription = this.$refs.tinymceWrap.tinymceHtml;
      const proReferIdArr = [];
      if (this.cardList.length === 0) {
        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.cashCost === undefined || item.integralCost === undefined) {
            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.useNewStoreWidget === 1) {
        const data = await this.$refs.storeCard.getRightList();
        if (!data.length) {
          this.$message.error('请选择展示门店');
          return;
        }
      }
      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);
      }
      this.$refs[couponForm].validate(valid => {
        if (valid) {
          const params = {
            proName: this.cardList.length > 1 ? this.couponForm.proName : this.cardList[0].cardName,
            integralMallProId: this.mallProId === '-1' ? '' : this.mallProId, // 礼品id
            proType: 1, // 优惠券
            proReferId: proReferIdArr.join(','), // 卡券id
            dataDialogueId: this.couponForm.dataDialogueId, // 数据对话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.isEdit ? this.couponForm.virtualStock - (this.currentStock || 0) : this.couponForm.virtualStock, // 库存
            gradeType: this.couponForm.gradeType,
            memberGrade: this.couponForm.memberGrade.join(','), // 适用会员
            showStore: this.sendChildData.storeType, // 显示门店 0所有 1部分分类 2部分门店
            storeIds: '', // 展现门店id
            storeWidgetId: '',
            useNewStoreWidget: this.useNewStoreWidget,
            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, // 兑换时段
            proShowStatus: this.couponForm.proShowStatus, // 显示状态
            releaseType: this.couponForm.releaseType, // 上架状态
            limitTimeBegin: this.couponForm.releaseType === 2 ? this.getTimeAll(this.couponForm.limitTimeBegin[0]) : '', // 定时上架开始时间
            limitTimeEnd: this.couponForm.releaseType === 2 ? this.getTimeAll(this.couponForm.limitTimeBegin[1]) : '', // 定时上架结束时间
            isNewGuestVisible: this.couponForm.proShowStatus == 1 ? this.couponForm.isNewGuestVisible : 0, // 新客是否可见 0：新客不可见、1：新客可见'
            isDifferentialPricing: this.isDifferentialPricing,
            differentialPricingJson: JSON.stringify(this.submitLadderList),
          };
          // 校验定时上架时间
          if (this.couponForm.releaseType == 2 && !this.vaidataDataPicker()) return this.$message.error('定时上架结束时间必须大于当前时间和开始时间');
          // 门店分类
          if (this.useNewStoreWidget === 0) {
            if (this.sendChildData.storeType === 1) {
              if (this.sendChildData.storeGroupIds) {
                params.storeGroupIds = this.sendChildData.storeGroupIds || '';
              } else {
                this.$message.error('门店分类不能为空');
                return;
              }
            } else if (this.sendChildData.storeType === 2) {
              if (this.sendChildData.storeIds.length) {
                params.storeIds = this.sendChildData.storeIds.map(v => v.storeId).join(',');
              } else {
                params.storeIds = '';
                this.$message.error('部分门店不能为空');
                return;
              }
            }
          } else if (this.useNewStoreWidget === 1) {
            params.storeWidgetId = this.uuid;
          }

          // 部分时段时间转换
          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('#');
          // this.submitLoading = true;
          // if (this.cardCouponList.length === this.ladderSkuList.length) {
          //   let num2 = 0;
          //   this.cardCouponList.map(v1 => {
          //     this.ladderSkuList.forEach(v2 => {
          //       if (v1.proRefId !== v2.proRefId) {
          //         num2++;
          //       }
          //     });
          //   });
          //   let num = 0;
          //   if (this.ladderMemberGradeChange.length) {
          //     this.ladderMemberGradeChange.map(v1 => {
          //       this.list2.forEach(v2 => {
          //         if (v1.gradeId !== v2.gradeId) {
          //           num++;
          //         }
          //       });
          //     });
          //   }
          //   if (!num && !num2) {
          //     this.saveDeatail(params);
          //   } else {
          //     this.confirmDetail(params);
          //   }
          // } else {
          //   this.confirmDetail(params);
          // }
          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',
          });
          this.submitLoading = false;
        } else {
          this.$message.error(res.data.message);
          this.submitLoading = false;
        }
      });
    },
    goBack () {
      this.$router.push({
        name: 'coupon',
      });
    },
    // //人群筛选器使用的方法
    // // 父组件调用子组件方法,触发父组件事件
    // getData() {
    //   var that = this;
    //   that.$refs.peopleFilter.confirmSet();
    //   // that.usePeopleFilter = true;
    // },
    // // 子组件触发父组件事件,返回过滤条件数据
    // findFilter(value) {
    //   // var that = this;
    //   this.searchParams = value;
    // },
    // // 取消
    // cancelFilter() {
    //   var that = this;
    //   that.$refs.peopleFilter.cancelSet();
    // },
    // // 获取需要回显的数据, 供保存时候使用
    // getBackData(val) {
    //   this.responseParams = val;
    //   this.getSaveData = val;
    // },
    // // 显示编辑,保存按钮隐藏,确认按钮显示 (子组件会调用)
    // editShow() {
    //   var that = this;
    //   that.toggleTag = true;
    //   that.saveTag = false;
    // },
    // // 显示保存按钮,隐藏确认按钮显示  (子组件会调用)
    // editHide() {
    //   var that = this;
    //   that.toggleTag = false;
    //   that.saveTag = true;
    // },
    // // 隐藏保存按钮和确认按钮  (子组件会调用)
    // // 传个参数给父组件 来查数据
    // hideBtn(refresh) {
    //   if (refresh === 0) {
    //     this.memberSearchStr = -1;
    //     this.toggleTag = false;
    //     // 查数据的方法
    //     // this.getList();
    //   }
    // }
  },
};
</script>
<style scoped>
.w-100 {
  width: 100px;
}
.section {
  background: #fff;
  margin: 24px;
  padding-bottom: 24px;
  margin-bottom: 80px;
  /* padding: 24px; */
}

.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;
}
.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 #1890ff;
  margin-left: 15px;
  display: inline-block;
  position: absolute;
  top: 12px;
}
</style>
<style>
.select-shop__right {
  line-height: 28px !important;
}
.section-content .pagination {
  float: none !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;
}
.store-tip {
  font-size: 13px;
  color: #909399;
  position: absolute;
  left: 430px;
  top: 0px;
}
.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;
} */
.store-tips {
  width: 200px;
  position: absolute;
  left: -10px;
}
.card-style.el-tabs--border-card {
  box-shadow: none !important;
}
.sub_title {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}
</style>
