<template>
  <div class="subPage flex-h">
    <div class="img">
      <img v-if="templateList.length" :src="templateList[templateActiveIndex].TplImg" width="100%" alt="">
    </div>
    <div class="flex-item">
      <div style="text-align:right;margin-bottom:20px;">
        <el-button
          :disabled="isread"
          size="mini"
          type="success"
          @click="submitLuckdrawData">保存</el-button>
        <el-button
          size="mini"
          type="warning"
          @click="rebackList">取消</el-button>
      </div>
      <nav class="flex-h">
        <a class="flex-item" :class="{'active': activeIndex === 0}" @click="activeIndex = 0">基础信息</a>
        <a class="flex-item" :class="{'active': activeIndex === 1}" @click="activeIndex = 1">奖品信息</a>
        <a class="flex-item" :class="{'active': activeIndex === 2}" @click="activeIndex = 2">活动设置</a>
      </nav>
      <div class="cutBody">
        <form class="mainForm">
          <div :hidden="activeIndex !== 0">
            <ul>
              <li class="flex-h">
                <span>案场：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-select :disabled="!editAll || isread" v-model="CaseId" @change="selectCase" placeholder="请选择案场">
                      <el-option
                        v-for="item in cases"
                        :key="item.CaseId"
                        :label="item.CaseName"
                        :value="item.CaseId">
                      </el-option>
                    </el-select>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动标题：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-input
                      :disabled="isread"
                      placeholder="请输入活动标题"
                      v-model="postData.Name"
                      clearable>
                    </el-input>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动主图：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <el-upload
                      class="avatar-uploader"
                      action='string'
                      :before-upload="toolClass.beforeUpload"
                      :http-request="toolClass.upload"
                      :show-file-list="false"
                      :on-success="handleMainImgSuccess">
                      <img v-if="postData.ActivityMainImg" :src="postData.ActivityMainImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动时间：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <el-date-picker
                      :disabled="!editAll || isread"
                      value-format="yyyy-MM-ddT00:00:00+08:00"
                      v-model="postData.BeginDate"
                      type="date"
                      placeholder="选择开始日期">
                    </el-date-picker>
                    <span>至</span>
                    <el-date-picker
                      :disabled="!editAll || isread"
                      value-format="yyyy-MM-ddT23:59:59+08:00"
                      v-model="postData.EndDate"
                      type="date"
                      placeholder="选择截止日期">
                    </el-date-picker>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动模板：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <div class="drawTemplateItem" v-for="(item,index) in templateList" :key="index">
                      <a :class="{'active': templateActiveIndex === index}" @click="cutTemplate(index)">
                        <input type="file" :ref="'templateImg' + index" hidden @change="templateImgChange(item, $event)">
                        <img :src="item.MiniPic" style="width:100%;height:100%;object-fit: contain;">
                      </a>
                      <!-- <span style="width:100%;display:block;text-align:center;font-size:11px;color:#ccc;margin-bottom:5px;">（双击更换背景图）</span> -->
                      <!-- <el-button
                        v-if="item.currentImg !== ''"
                        size="mini"
                        @click="resetCurrentImg(item, index)"
                        type="success">重置</el-button> -->
                    </div>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>模板背景图：</span>
                <div class="flex-item">
                  <div style="width:300px;text-align:center" v-for="(item,index) in templateList" :key="index" v-if="index === templateActiveIndex">
                    <div :style="{height: item.currentImg ? '300px' : '40px'}">
                      <img v-if="item.currentImg" class="contain currentImg" :src="item.currentImg" alt="" @dblclick="dbTemplateClick(index)">
                      <!-- <span v-else style="width:100%;line-height:40px;font-size:11px;color:#ccc;text-align:left;display:block;">默认背景图</span> -->
                      <el-button
                        v-else
                        style="float:left;margin-top:5px;"
                        size="mini"
                        @click="dbTemplateClick(index)"
                        type="success">更换背景图</el-button>
                    </div>
                    <span v-if="item.currentImg" style="width:100%;display:block;text-align:center;font-size:11px;color:#ccc;margin-bottom:5px;">（双击更换背景图）</span>
                    <el-button
                      v-if="item.currentImg"
                      size="mini"
                      @click="resetCurrentImg(item, index)"
                      type="success">重置</el-button>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>活动规则说明：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <quill-editor
                      :disabled="isread"
                      v-model="postData.LuckdrawRule"
                      ref="myQuillEditor"
                      :options="editorOption">
                    </quill-editor>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>分享标题：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-input
                      :disabled="isread"
                      placeholder="请输入分享标题"
                      v-model="postData.ActivityTitle"
                      clearable>
                    </el-input>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>分享图片：<em>*</em></span>
                <div class="flex-item">
                  <div>
                    <el-upload
                      class="avatar-uploader"
                      action='string'
                      :before-upload="toolClass.beforeUpload"
                      :http-request="toolClass.upload"
                      :show-file-list="false"
                      :on-success="handleShareImgSuccess">
                      <img v-if="postData.ShareImg" :src="postData.ShareImg" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>分享文案：<em>*</em></span>
                <div class="flex-item">
                  <div style="width:50%">
                    <el-input
                      :disabled="isread"
                      placeholder="请输入分享文案"
                      v-model="postData.ShareContent"
                      clearable>
                    </el-input>
                  </div>
                </div>
              </li>
            </ul>
          </div>
          <div :hidden="activeIndex !== 1">
            <el-table
              :data="postData.Prizes"
              style="width: 100%">
              <el-table-column
                prop="PrizeImg"
                label="奖品图片"
                width="180">
                <template slot-scope="scope">
                  <img :src="scope.row.PrizeImg" width="100" alt="">
                </template>
              </el-table-column>
              <el-table-column
                prop="PrizeName"
                label="奖品名称">
              </el-table-column>
              <el-table-column
                prop="Stock"
                label="奖品数量">
              </el-table-column>
              <el-table-column
                prop="Probability"
                label="中奖概率">
                <template slot-scope="scope">
                  <span>{{scope.row.Probability}}%</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="address"
                label="操作"
                width="200">
                <template slot-scope="scope">
                  <el-button
                    :disabled="isread"
                    size="mini"
                    type="success"
                    @click="editPrizeItem(scope.row, scope.$index)">编辑</el-button>
                  <el-button
                    :disabled="!editAll || isread"
                    size="mini"
                    type="warning"
                    @click="deletePrizeItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="text-align:center;margin-top:20px;">
              <el-button
                :disabled="!editAll || isread"
                size="mini"
                type="primary"
                @click="addPrize">新增奖品</el-button>
            </div>
          </div>
          <div :hidden="activeIndex !== 2">
            <ul>
              <li class="flex-h">
                <span>参与类型：</span>
                <div class="flex-item flex-h">
                  <el-switch
                    :disabled="!editAll || isread"
                    v-model="postData.JoinType"
                    active-value="newuser"
                    inactive-value="no"
                    :active-text="postData.JoinType === 'newuser' ? '新用户' : '不限'">
                  </el-switch>
                </div>
              </li>
              <li class="flex-h">
                <span>抽奖次数：</span>
                <div class="flex-item flex-h">
                  <el-switch
                    :disabled="!editAll || isread"
                    v-model="postData.NumType"
                    active-value="repeat"
                    inactive-value="noRepeat"
                    :active-text="postData.NumType === 'noRepeat' ? '固定次数' : '周期次数'">
                  </el-switch>
                  <div :hidden="postData.NumType !== 'noRepeat'">
                    <span>每个账号</span>
                    <div style="width:100px;">
                      <el-input
                        :disabled="!editAll || isread"
                        placeholder=""
                        v-model="postData.LuckdrawNum"
                        clearable>
                      </el-input>
                    </div>
                    <span>次</span>
                  </div>
                  <div :hidden="postData.NumType !== 'repeat'">
                    <span>每</span>
                    <div style="width:100px;">
                      <el-select :disabled="!editAll || isread" v-model="postData.NumInterval" placeholder="请选择">
                        <el-option
                          v-for="item in lotteryTimeUnitOptions"
                          :key="item.id"
                          :label="item.value"
                          :value="item.id">
                        </el-option>
                      </el-select>
                    </div>
                    <div style="width:100px;">
                      <el-input
                        :disabled="!editAll || isread"
                        placeholder=""
                        v-model="postData.LuckdrawNum"
                        clearable>
                      </el-input>
                    </div>
                    <span>次</span>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>分享设置：</span>
                <div class="flex-item flex-h">
                  <el-switch
                    :disabled="!editAll || isread"
                    v-model="postData.ShareType"
                    active-value="newuser"
                    inactive-value="no"
                    :active-text="postData.ShareType === 'newuser' ? '分享新用户' : '不限'">
                  </el-switch>
                  <div :hidden="postData.ShareType !== 'newuser'">
                    <span>新增</span>
                    <div style="width:100px;">
                      <el-input
                        :disabled="!editAll || isread"
                        placeholder=""
                        v-model="postData.ShareAddNum"
                        clearable>
                      </el-input>
                    </div>
                    <span>次抽奖</span>
                  </div>
                </div>
              </li>
              <li class="flex-h">
                <span>系统用户抽奖：</span>
                <div class="flex-item flex-h">
                  <el-switch
                    :disabled="!editAll || isread"
                    v-model="postData.IsSysLuckdraw"
                    :active-value="1"
                    :inactive-value="0"
                    :active-text="postData.IsSysLuckdraw ? '开启' : '关闭'">
                  </el-switch>
                </div>
              </li>
              <li class="flex-h">
                <span>奖品内定设置：</span>
                <div class="flex-item flex-h">
                  <el-switch
                    :disabled="!editAll || isread"
                    v-model="postData.IsInternalDefault"
                    :active-value="1"
                    :inactive-value="0"
                    :active-text="postData.IsInternalDefault ? '开启' : '关闭'">
                  </el-switch>
                </div>
              </li>
            </ul>
            <el-table
              :hidden="!postData.IsInternalDefault"
              :data="postData.Prizes"
              style="width: 100%">
              <el-table-column
                prop="PrizeImg"
                label="奖品图片"
                width="180">
                <template slot-scope="scope">
                  <img :src="scope.row.PrizeImg" width="100" alt="">
                </template>
              </el-table-column>
              <el-table-column
                prop="PrizeName"
                label="奖品名称">
              </el-table-column>
              <el-table-column
                prop="address"
                label="操作"
                width="200">
                <template slot-scope="scope">
                  <el-button
                    :disabled="!editAll || isread"
                    size="mini"
                    type="success"
                    @click="addPrizeItemPhone(scope.$index)">内定设置</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </form>
      </div>
    </div>
    <el-dialog
      :title="editPrizeOff ? '编辑奖品' : '新增奖品'"
      :visible.sync="centerDialogVisible"
      width="800px"
      @closed="prizeTypeChange();editPrizeOff = false"
      center>
      <form class="mainForm addPrizeForm">
        <ul>
          <li class="flex-h" style="width:50%;float:left;">
            <span>奖品类型：<em>*</em></span>
            <div class="flex-item">
              <el-select :disabled="!editAll || isread" v-model="addPrizeInfo.PrizeType" @change="prizeTypeChange" placeholder="请选择">
                <el-option
                  v-for="item in prizeOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </li>
          <li class="flex-h" style="width:50%;float:left;" v-if="addPrizeInfo.PrizeType === 'third'">
            <span>是否实物：<em>*</em></span>
            <div class="flex-item">
              <el-switch
                :disabled="!editAll || isread"
                v-model="addPrizeInfo.IsReality"
                :active-value="1"
                :inactive-value="0"
                @change="checkIsReality"
                :active-text="addPrizeInfo.IsReality ? '是' : '否'">
              </el-switch>
              <span style="line-height:40px;font-size:11px;color:#ccc;">（选择“否”即为“谢谢参与”奖项）</span>
            </div>
          </li>
          <li class="flex-h" style="width:50%;float:left;" v-if="addPrizeInfo.PrizeType === 'third'">
            <span>奖品名称：<em>*</em></span>
            <div class="flex-item">
              <div style="width: 200px;">
                <el-input
                  :disabled="!editAll || isread"
                  placeholder=""
                  v-model="addPrizeInfo.PrizeName"
                  clearable>
                </el-input>
              </div>
            </div>
          </li>
          <li class="flex-h" style="width:50%;float:left;" v-if="addPrizeInfo.PrizeType === 'couponcard'">
            <span>卡券类型：<em>*</em></span>
            <div class="flex-item">
              <el-select :disabled="!editAll || isread" v-model="addPrizeInfo.CouponCardType" @change="cardCouponChange" placeholder="请选择">
                <el-option
                  v-for="item in cardOrCouponOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </li>
          <li class="flex-h" v-if="addPrizeInfo.PrizeType === 'couponcard'">
            <span>选择卡券：<em>*</em></span>
            <div class="flex-item">
              <el-select :disabled="!editAll || isread" v-if="addPrizeInfo.CouponCardType === 'card'" @change="cardChange" v-model="addPrizeInfo.CouponCardId" placeholder="请选择">
                <el-option
                  :disabled="!item.select"
                  v-for="item in cardList"
                  :key="item.CardId"
                  :label="item.CardName"
                  :value="item.CardId">
                </el-option>
              </el-select>
              <el-select :disabled="!editAll || isread" v-if="addPrizeInfo.CouponCardType === 'coupon'" @change="couponChange" v-model="addPrizeInfo.CouponCardId" placeholder="请选择">
                <el-option
                  :disabled="!item.select"
                  v-for="item in couponList"
                  :key="item.CouponId"
                  :label="item.CouponName"
                  :value="item.CouponId">
                </el-option>
              </el-select>
            </div>
          </li>
          <li class="flex-h" style="width:50%;float:left;">
            <span>中奖概率：<em>*</em></span>
            <div class="flex-item">
              <div style="width: 200px;display:inline-block;">
                <el-input
                  :disabled="!editAll || isread"
                  placeholder=""
                  v-model="addPrizeInfo.Probability"
                  clearable>
                </el-input>
              </div>
              <span style="line-height:40px;">%</span>
            </div>
          </li>
          <li class="flex-h" style="width:50%;float:left;" v-if="!(addPrizeInfo.PrizeType === 'third' && addPrizeInfo.IsReality !== 1)">
            <span>奖品数量：<em>*</em></span>
            <div class="flex-item">
              <div style="width: 200px;">
                <el-input
                  :disabled="!editAll || isread || addPrizeInfo.PrizeType === 'couponcard'"
                  placeholder=""
                  v-model="addPrizeInfo.Stock"
                  clearable>
                </el-input>
              </div>
            </div>
          </li>
          <li class="flex-h" v-if="addPrizeInfo.PrizeType === 'third' && addPrizeInfo.IsReality === 1">
            <span>核销时间：<em>*</em></span>
            <div class="flex-item">
              <div class="flex-h" style="width: 100%;align-item: center;">
                <el-radio :disabled="!editAll || isread" v-model="verificationType" :label="1" style="margin-right: 5px;"><em style="color: transparent;display:none;">1</em></el-radio>
                <span>领取后</span>
                <div style="width: 100px;display: inline-block;">
                  <el-input
                    :disabled="!editAll || isread"
                    placeholder=""
                    v-model="addPrizeInfo.ValidDays"
                    clearable>
                  </el-input>
                </div>
                <span>天内有效</span>
              </div>
              <div class="flex-h" style="width: 100%;align-item: center;margin-top: 10px;">
                <el-radio :disabled="!editAll || isread" v-model="verificationType" :label="2" style="margin-right: 5px;"><em style="color: transparent;display:none;">2</em></el-radio>
                <span>有效期</span>
                <div style="display: inline-block;">
                  <el-date-picker
                    :disabled="!editAll || isread"
                    value-format="yyyy-MM-ddT00:00:00+08:00"
                    v-model="addPrizeInfo.VerificationStart"
                    type="date"
                    placeholder="选择起始日期">
                  </el-date-picker>
                </div>
                <span>至</span>
                <div style="display: inline-block;">
                  <el-date-picker
                    :disabled="!editAll || isread"
                    value-format="yyyy-MM-ddT23:59:59+08:00"
                    v-model="addPrizeInfo.VerificationEnd"
                    type="date"
                    placeholder="选择截止日期">
                  </el-date-picker>
                </div>
              </div>
            </div>
          </li>
          <li class="flex-h" style="width:50%;float:left;">
            <span>奖品图片：<em>*</em></span>
            <div class="flex-item">
              <el-upload
                :disabled="!editAll || isread"
                class="avatar-uploader"
                action='string'
                :http-request="toolClass.upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess">
                <img v-if="addPrizeInfo.PrizeImg" :src="addPrizeInfo.PrizeImg" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </li>
          <li class="flex-h" v-if="addPrizeInfo.PrizeType === 'third'">
            <span>兑换说明：</span>
            <div class="flex-item">
              <div>
                <quill-editor
                  :disabled="isread"
                  v-model="addPrizeInfo.PrizeDesc"
                  ref="myQuillEditor"
                  :options="editorOption">
                </quill-editor>
              </div>
            </div>
          </li>
        </ul>
      </form>
      <div style="text-align:center;margin:20px 0 0;padding-bottom:20px;">
        <el-button
          :disabled="isread"
          size="mini"
          type="primary"
          @click="savePrizeItem">保存</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="closeAddPrize">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="添加手机号"
      :visible.sync="showAddPhone"
      width="600px"
      @closed="addPhoneNum = ''"
      center>
      <div style="text-align:center;font-size:0;">
        <div style="width:300px;display:inline-block;margin-right:20px;">
          <el-input
            :disabled="isread"
            placeholder="请输入正确手机号"
            v-model="addPhoneNum"
            clearable>
          </el-input>
        </div>
        <el-button
          :disabled="isread"
          type="primary"
          @click="addPhoneInPrize">确定</el-button>
      </div>
      <div style="border:1px solid #eee;border-bottom:none;margin:20px 0 0;">
        <el-table
          :data="addPhoneTableData"
          style="width: 100%">
          <el-table-column
            prop="Tel"
            label="手机号">
          </el-table-column>
          <el-table-column
            prop="address"
            label="操作">
            <template slot-scope="scope">
              <el-button
                :disabled="isread"
                size="mini"
                type="warning"
                @click="deletePrizeItemPhone(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="text-align:center;padding-bottom:20px;">
      </div>
    </el-dialog>
    <div id="hiddenRule" style="display:none;"></div>
  </div>
</template>
<script>
import { mapState, createNamespacedHelpers } from 'vuex'
import { quillEditor } from 'vue-quill-editor'
import uploadImage from 'quill-plugin-image'
const { mapState: mapActivityLuckDrawState, mapActions: mapActivityLuckDrawActions } = createNamespacedHelpers('activityLuckDraw')
const { mapActions: mapCardActions } = createNamespacedHelpers('card')
const { mapActions: mapCouponActions } = createNamespacedHelpers('coupon')

export default {
  data () {
    return {
      submitOff: true,
      editPrizeOff: false,
      isread: false, // 是否预览模式
      editAll: true, // 是否全部能编辑
      editPrizePhoneIndex: '', // 编辑奖品内定手机号索引值
      addPhoneTableData: [], // 添加手机号数据
      addPhoneNum: '', // 添加手机号
      showAddPhone: false,
      prizeOptions: [{
        value: '城的空间内部券',
        id: 'couponcard'
      }, {
        value: '第三方奖品',
        id: 'third'
      }],
      cardOrCouponOptions: [{
        value: '体验卡',
        id: 'card'
      }, {
        value: '优惠券',
        id: 'coupon'
      }],
      cardOrCouponList: [],
      addPrizeInfo: {
        PrizeType: 'couponcard', // 奖品类型
        CouponCardType: '', // 卡券类型
        CouponCardId: '', // 卡券id
        Stock: '', // 奖品数量
        PrizeImg: '', // 奖品图片
        PrizeName: '', // 奖品名称
        ValidDays: '', // 领取后有效天数
        VerificationStart: '', // 有效期起始时间
        VerificationEnd: '', // 有效期截止时间
        PrizeDesc: '', // 兑换说明
        Probability: '', // 中奖概率
        IsReality: 1, // 是否实物
      },
      verificationType: 1, // 核销类型
      centerDialogVisible: false,
      activeIndex: 0,
      lotteryTimeUnitOptions: [{
        value: '天',
        id: 'day'
      }, {
        value: '周',
        id: 'week'
      }, {
        value: '月',
        id: 'month'
      }],
      postData: {
        CaseId: '', // 案场id
        TplId: '', // 模板id
        Name: '', // 活动标题
        BeginDate: '', // 开始日期
        EndDate: '', // 截止日期
        LuckdrawRule: '', // 编辑内容
        JoinType: 'no', // 参与类型
        NumType: 'repeat', // 抽奖次数类型
        NumInterval: 'day', // 抽奖周期单位
        LuckdrawNum: '', // 抽奖次数
        ShareType: 'newuser', // 分享设置
        ShareAddNum: '', // 新增抽奖次数
        IsSysLuckdraw: 1, // 系统用户抽奖
        IsInternalDefault: 1, // 奖品内定
        Prizes: [], // 奖品内定表格数据
        Imgs: [], // 活动模板背景图

        ActivityMainImg: '',
        ShareImg: '',
        ActivityTitle: '',
        ShareContent: '',
      },
      templateList: [], // 抽奖活动模板
      templateActiveIndex: 0, // 活动模板选中索引值
      editorOption: {},
      cardList: [], // 卡列表
      couponList: [], // 券列表
    }
  },
  computed: {
    ...mapState({
      cases: x => x.app.cases.list,
      defaultCaseId: x => x.app.cases.default
    }),
    ...mapActivityLuckDrawState({
      luckDrawList: x => x.luckDrawList.list,
    }),
    CaseId: {
      get () {
        return this.postData.CaseId || this.defaultCaseId
      },
      set (val) {
        this.postData.CaseId = val
      }
    }
  },
  components: {
    quillEditor,
  },
  mounted () {
    uploadImage(this.$refs.myQuillEditor.quill, file => {
      return this.toolClass.upload({ file }).then(data => {
        const url = data.result.url
        return { src: url, alt: '' }
      })
    })
  },
  created () {
    if (this.$route.query.isread) {
      this.isread = true
    }
    this.GetCardList({ // 获取卡列表
      page: 1,
      pagesize: 100000,
      sendtype: 'system',
      usetype: 'luckdraw',
      usedid: this.$route.query.id || '',
      caseid: this.CaseId,
    }).then((res) => {
      res.list = res.list || []
      for (var n = 0; n < res.list.length; n++) {
        res.list[n].select = true
      }
      this.cardList = res.list
    })
    this.GetCouponList({ // 获取券列表
      page: 1,
      pagesize: 100000,
      sendtype: 'system',
      usetype: 'luckdraw',
      usedid: this.$route.query.id || '',
      caseid: this.CaseId,
    }).then((res) => {
      res.list = res.list || []
      for (var n = 0; n < res.list.length; n++) {
        res.list[n].select = true
      }
      this.couponList = res.list
    })
    this.getDrawTemplateList().then((res) => { // 获取活动模板列表
      for (var n = 0; n < res.length; n++) {
        res[n].currentImg = ''
      }
      this.templateList = res
      this.postData.TplId = this.templateList[0].TplId
      if (this.$route.query.id) {
        this.getLuckdrawById(this.$route.query.id).then((resr) => { // 编辑模式下获取活动信息
          resr.Imgs = resr.Imgs || []
          this.postData = resr
          if (resr.JoinedNum > 0) { // 已有人参与抽奖则信息部分不可编辑
            this.editAll = false
          }
          for (var n = 0; n < this.templateList.length; n++) {
            if (this.templateList[n].TplId === resr.TplId) {
              if (resr.Imgs.length) {
                this.templateList[n].currentImg = resr.Imgs[0].ImgUrl
              }
              this.templateActiveIndex = n
            }
          }
          for (var a = 0; a < this.postData.Prizes.length; a++) {
            if (this.postData.Prizes[a].VerificationStart === '0001-01-01T00:00:00Z') {
              this.postData.Prizes[a].VerificationStart = ''
              this.postData.Prizes[a].VerificationEnd = ''
            }
            if (this.postData.Prizes[a].ValidDays === 0) {
              this.postData.Prizes[a].ValidDays = ''
            }
            this.postData.Prizes[a].Defaults = this.postData.Prizes[a].Defaults || []
          }
        })
      }
    })
  },
  methods: {
    ...mapActivityLuckDrawActions([
      'getDrawTemplateList',
      'addLuckdraw',
      'getLuckdrawById',
      'editLuckdraw',
    ]),
    ...mapCardActions([
      'GetCardList',
    ]),
    ...mapCouponActions([
      'GetCouponList',
    ]),
    selectCase () {
      this.GetCardList({ // 获取卡列表
        page: 1,
        pagesize: 100000,
        sendtype: 'system',
        usetype: 'luckdraw',
        usedid: this.$route.query.id || '',
        caseid: this.CaseId,
      }).then((res) => {
        res.list = res.list || []
        for (var n = 0; n < res.list.length; n++) {
          res.list[n].select = true
        }
        this.cardList = res.list
      })
      this.GetCouponList({ // 获取券列表
        page: 1,
        pagesize: 100000,
        sendtype: 'system',
        usetype: 'luckdraw',
        usedid: this.$route.query.id || '',
        caseid: this.CaseId,
      }).then((res) => {
        res.list = res.list || []
        for (var n = 0; n < res.list.length; n++) {
          res.list[n].select = true
        }
        this.couponList = res.list
      })
    },
    checkPhone (val) {
      return !!(/^1[345789]\d{9}$/.test(val))
    },
    cardChange () {
      for (var n = 0; n < this.cardList.length; n++) {
        if (this.cardList[n].CardId === this.addPrizeInfo.CouponCardId) {
          this.addPrizeInfo.Stock = this.cardList[n].TotalCount - this.cardList[n].UsedCount
          break
        }
      }
    },
    couponChange () {
      for (var n = 0; n < this.couponList.length; n++) {
        if (this.couponList[n].CouponId === this.addPrizeInfo.CouponCardId) {
          this.addPrizeInfo.Stock = this.couponList[n].TotalCount - this.couponList[n].UsedCount
          break
        }
      }
    },
    checkIsReality () {
      if (!this.addPrizeInfo.IsReality) {
        for (var n in this.addPrizeInfo) {
          if (n !== 'PrizeType' && n !== 'PrizeImg' && n !== 'PrizeDesc' && n !== 'IsReality' && n !== 'Probability') {
            this.addPrizeInfo[n] = ''
          }
        }
      }
    },
    checkData () { // 校验活动信息
      if (this.postData.CaseId === '') {
        this.$message({
          type: 'error',
          message: '请选择案场'
        })
        return false
      }
      if (this.postData.Name === '') {
        this.$message({
          type: 'error',
          message: '活动标题不能为空'
        })
        return false
      }
      if (this.postData.ActivityMainImg === '') {
        this.$message({
          type: 'error',
          message: '请先上传活动主图'
        })
        return false
      }
      if (this.postData.BeginDate === '') {
        this.$message({
          type: 'error',
          message: '活动开始时间不能为空'
        })
        return false
      }
      if (this.postData.EndDate === '') {
        this.$message({
          type: 'error',
          message: '活动截止时间不能为空'
        })
        return false
      }
      if (new Date(this.postData.BeginDate).getTime() > new Date(this.postData.EndDate).getTime()) {
        this.$message({
          type: 'error',
          message: '活动截止时间不能小于开始时间'
        })
        return false
      }
      if (this.postData.LuckdrawRule === '') {
        this.$message({
          type: 'error',
          message: '活动规则说明不能为空'
        })
        return false
      }
      if (this.postData.ActivityTitle === '') {
        this.$message({
          type: 'error',
          message: '分享标题不能为空'
        })
        return false
      }
      if (this.postData.ShareImg === '') {
        this.$message({
          type: 'error',
          message: '请先上传分享图片'
        })
        return false
      }
      if (this.postData.ShareContent === '') {
        this.$message({
          type: 'error',
          message: '分享文案不能为空'
        })
        return false
      }
      if (!this.postData.Prizes.length) {
        this.$message({
          type: 'error',
          message: '请添加至少一项奖品'
        })
        return false
      }
      var num = 0
      for (var n = 0; n < this.postData.Prizes.length; n++) {
        num += this.postData.Prizes[n].Probability - 0
      }
      if (num !== 100) {
        this.$message({
          type: 'error',
          message: '奖品中奖概率总和须为100%'
        })
        return false
      }
      if (this.postData.LuckdrawNum - 0 < 1 || (this.postData.LuckdrawNum - 0) % 1 !== 0) {
        this.$message({
          type: 'error',
          message: '抽奖次数须为大于0正整数'
        })
        return false
      }
      if (this.postData.ShareType === 'newuser') {
        if (this.postData.ShareAddNum - 0 < 1 || (this.postData.ShareAddNum - 0) % 1 !== 0) {
          this.$message({
            type: 'error',
            message: '分享新增抽奖次数须为大于0正整数'
          })
          return false
        }
      }
      if (this.postData.IsInternalDefault) {
        var bool = true
        for (var a = 0; a < this.postData.Prizes.length; a++) {
          if (this.postData.Prizes[a].Defaults && this.postData.Prizes[a].Defaults.length) {
            bool = false
          }
        }
        if (bool) {
          this.$message({
            type: 'error',
            message: '请添加内定奖品附属手机号'
          })
          return false
        }
      }
      return true
    },
    rebackList () { // 返回列表页
      this.$router.push({ name: 'listOfLotteryActivities' })
    },
    submitLuckdrawData () { // 提交活动信息
      if (this.postData.CaseId === '' && this.defaultCaseId !== '') {
        this.postData.CaseId = this.defaultCaseId
      }
      if (!this.checkData()) {
        return false
      }
      if (this.submitOff) {
        this.submitOff = false
        this.postData.ShareAddNum = this.postData.ShareAddNum - 0
        this.postData.LuckdrawNum = this.postData.LuckdrawNum - 0
        if (!this.postData.IsInternalDefault) {
          for (var n = 0; n < this.postData.Prizes.length; n++) {
            this.postData.Prizes[n].Defaults = []
          }
        }
        for (var a = 0; a < this.postData.Prizes.length; a++) {
          this.postData.Prizes[a].Remainder = 0
          this.postData.Prizes[a].Status = 1
          if (this.postData.Prizes[a].IsReality) {
            if (this.postData.Prizes[a].ValidDays === '') {
              delete this.postData.Prizes[a].ValidDays
            }
            if (this.postData.Prizes[a].VerificationStart === '' || this.postData.Prizes[a].VerificationEnd === '') {
              delete this.postData.Prizes[a].VerificationStart
              delete this.postData.Prizes[a].VerificationEnd
              this.postData.Prizes[a].ValidDays = this.postData.Prizes[a].ValidDays - 0
            }
          } else {
            delete this.postData.Prizes[a].VerificationStart
            delete this.postData.Prizes[a].VerificationEnd
            delete this.postData.Prizes[a].ValidDays
          }
        }
        // console.log(JSON.stringify(this.postData))
        if (this.$route.query.id) { // 编辑模式
          this.editLuckdraw(this.postData).then((res) => {
            // console.log(JSON.stringify(this.postData))
            this.submitOff = true
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$router.push({ name: 'listOfLotteryActivities' })
          })
        } else { // 新增模式
          this.addLuckdraw(this.postData).then((res) => {
            // console.log(JSON.stringify(this.postData))
            this.submitOff = true
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$router.push({ name: 'listOfLotteryActivities' })
          })
        }
      }
    },
    addPrizeItemPhone (index) { // 编辑奖品内定号码
      this.editPrizePhoneIndex = index
      this.addPhoneTableData = (this.postData.Prizes[index].Defaults || []).slice(0)
      this.showAddPhone = true
    },
    deletePrizeItemPhone (index) { // 删除奖品内定号码
      this.addPhoneTableData.splice(index, 1)
      this.postData.Prizes[this.editPrizePhoneIndex].Defaults.splice(index, 1)
    },
    findSamePhone (num) { // 验重手机号
      for (var n = 0; n < this.addPhoneTableData.length; n++) {
        if (this.addPhoneTableData[n].Tel === num) {
          return false
        }
      }
      return true
    },
    addPhoneInPrize () { // 添加内定奖品手机号
      if (this.checkPhone(this.addPhoneNum) && this.addPhoneNum !== '' && this.findSamePhone(this.addPhoneNum)) {
        this.addPhoneTableData.push({
          Tel: this.addPhoneNum,
        })
        this.postData.Prizes[this.editPrizePhoneIndex].Defaults.push({
          Tel: this.addPhoneNum,
        })
        this.addPhoneNum = ''
      } else if (!this.findSamePhone(this.addPhoneNum)) {
        this.$message({
          type: 'error',
          message: '请勿填写重复手机号'
        })
      } else {
        this.$message({
          type: 'error',
          message: '请填写正确手机号'
        })
      }
    },
    editPrizeItem (item, index) { // 编辑奖品信息
      this.editPrizeOff = true
      this.editPrizeIndex = index
      this.addPrizeInfo = { ...item }
      if (item.VerificationStart === '' || item.VerificationStart === '0001-01-01T00:00:00Z') {
        this.verificationType = 1
      } else {
        this.verificationType = 2
      }
      this.addPrize()
    },
    deletePrizeItem (index) { // 删除奖品
      this.$confirm('确认删除此奖品信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.postData.Prizes[index].CouponCardType === 'card') {
          for (var n = 0; n < this.cardList.length; n++) {
            if (this.cardList[n].CardId === this.postData.Prizes[index].CouponCardId) {
              this.cardList[n].select = true
            }
          }
        } else {
          for (var a = 0; a < this.couponList.length; a++) {
            if (this.couponList[a].CouponId === this.postData.Prizes[index].CouponCardId) {
              this.couponList[a].select = true
            }
          }
        }
        this.postData.Prizes.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    prizeTypeChange () { // 新增奖品类型切换
      for (var n in this.addPrizeInfo) {
        if (n !== 'PrizeType' && n !== 'IsReality') {
          this.addPrizeInfo[n] = ''
        }
      }
      this.addPrizeInfo.IsReality = 1
    },
    savePrizeItem () { // 保存新增奖品信息
      if (this.addPrizeInfo.PrizeType === 'couponcard') { // 卡券
        if (this.addPrizeInfo.CouponCardType === '') {
          this.$message({
            type: 'error',
            message: '卡券类型不能为空'
          })
          return false
        }
        if (this.addPrizeInfo.CouponCardId === '') {
          this.$message({
            type: 'error',
            message: '卡券不能为空'
          })
          return false
        }
        if (this.addPrizeInfo.PrizeImg === '') {
          this.$message({
            type: 'error',
            message: '奖品图片不能为空'
          })
          return false
        }
        if (this.addPrizeInfo.Probability === '' || Number(this.addPrizeInfo.Probability) <= 0 || Number(this.addPrizeInfo.Probability) > 100) {
          this.$message({
            type: 'error',
            message: '中奖概率须为大于0且小于等于100数字'
          })
          return false
        }
        if (this.addPrizeInfo.Stock === '' || Number(this.addPrizeInfo.Stock) % 1 !== 0 || Number(this.addPrizeInfo.Stock) <= 0) {
          this.$message({
            type: 'error',
            message: '奖品数量须为大于0正整数'
          })
          return false
        }
        if (this.addPrizeInfo.CouponCardType === 'card') {
          for (var n = 0; n < this.cardList.length; n++) {
            if (this.cardList[n].CardId === this.addPrizeInfo.CouponCardId) {
              this.addPrizeInfo.PrizeName = this.cardList[n].CardName
              this.cardList[n].select = false
            }
          }
        } else {
          for (var a = 0; a < this.couponList.length; a++) {
            if (this.couponList[a].CouponId === this.addPrizeInfo.CouponCardId) {
              this.addPrizeInfo.PrizeName = this.couponList[a].CouponName
              this.couponList[a].select = false
            }
          }
        }
      } else if (this.addPrizeInfo.PrizeType === 'third') { // 第三方
        if (this.addPrizeInfo.PrizeName === '') {
          this.$message({
            type: 'error',
            message: '奖品名称不能为空'
          })
          return false
        }
        if (this.addPrizeInfo.Probability === '' || (this.addPrizeInfo.Probability - 0) <= 0 || (this.addPrizeInfo.Probability - 0) > 100) {
          this.$message({
            type: 'error',
            message: '中奖概率须为大于0且小于等于100数字'
          })
          return false
        }
        if ((this.addPrizeInfo.Stock === '' || (this.addPrizeInfo.Stock - 0) % 1 !== 0 || (this.addPrizeInfo.Stock - 0) <= 0) && this.addPrizeInfo.IsReality) {
          this.$message({
            type: 'error',
            message: '奖品数量须为大于0正整数'
          })
          return false
        }
        if (this.verificationType === 1 && this.addPrizeInfo.IsReality) {
          if (!this.addPrizeInfo.ValidDays || (this.addPrizeInfo.ValidDays - 0) % 1 !== 0 || (this.addPrizeInfo.ValidDays - 0) <= 0) {
            this.$message({
              type: 'error',
              message: '有效期须为大于0正整数'
            })
            return false
          }
          this.addPrizeInfo.VerificationStart = ''
          this.addPrizeInfo.VerificationEnd = ''
        } else if (this.addPrizeInfo.IsReality) {
          if (this.addPrizeInfo.VerificationStart === '') {
            this.$message({
              type: 'error',
              message: '有效期开始时间不能为空'
            })
            return false
          }
          if (this.addPrizeInfo.VerificationEnd === '') {
            this.$message({
              type: 'error',
              message: '有效期截止时间不能为空'
            })
            return false
          }
          if (new Date(this.addPrizeInfo.VerificationStart).getTime() > new Date(this.addPrizeInfo.VerificationEnd).getTime()) {
            this.$message({
              type: 'error',
              message: '有效期开始时间不能大于截止时间'
            })
            return false
          }
          this.addPrizeInfo.ValidDays = ''
        }
        if (this.addPrizeInfo.PrizeImg === '') {
          this.$message({
            type: 'error',
            message: '奖品图片不能为空'
          })
          return false
        }
      }
      this.addPrizeInfo.Stock = this.addPrizeInfo.Stock - 0
      this.addPrizeInfo.Probability = this.addPrizeInfo.Probability - 0
      this.addPrizeInfo.ValidDays = this.addPrizeInfo.ValidDays - 0
      if (this.editPrizeOff) {
        this.postData.Prizes.splice(this.editPrizeIndex, 1, { ...this.addPrizeInfo })
      } else {
        this.postData.Prizes.push({ ...this.addPrizeInfo, Defaults: [] })
      }
      this.closeAddPrize()
      this.prizeTypeChange()
      // console.log(JSON.stringify(this.postData.Prizes))
    },
    handleAvatarSuccess (res, file) { // 添加奖品图片
      this.addPrizeInfo.PrizeImg = res.result.url
    },
    handleMainImgSuccess (res, file) {
      this.postData.ActivityMainImg = res.result.url
    },
    handleShareImgSuccess (res, file) {
      this.postData.ShareImg = res.result.url
    },
    cardCouponChange () { // 切换选取卡券类型
      this.addPrizeInfo.Stock = ''
      this.addPrizeInfo.CouponCardId = ''
    },
    cutTemplate (index) { // 切换模板
      if (!this.isread) {
        this.templateActiveIndex = index
        this.postData.TplId = this.templateList[index].TplId
      }
    },
    dbTemplateClick (index) { // 更换背景图
      if (!this.isread) {
        this.$refs['templateImg' + index][0].click()
      }
    },
    templateImgChange (item, e) { // 图片更换
      if (e.target.files[0]) {
        this.toolClass.upload({
          file: e.target.files[0]
        }).then((res) => {
          item.currentImg = res.result.url
          this.postData.Imgs[0] = {
            ImgUrl: res.result.url
          }
        })
      }
    },
    resetCurrentImg (item, index) { // 重置背景图
      if (!this.isread) {
        item.currentImg = ''
        if (this.templateActiveIndex === index) this.postData.Imgs = []
        this.$refs['templateImg' + index][0].value = ''
      }
    },
    addPrize () { // 新增奖品
      this.centerDialogVisible = true
    },
    closeAddPrize () { // 关闭新增奖品
      this.centerDialogVisible = false
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import "page.scss";
.mainForm {
  width: 100%;
  li {
    margin-bottom: 20px;
    div.flex-h {
      align-items: center;
      & > * {
        margin-right: 20px;
      }
      > div {
        white-space: nowrap;
        > * {
          display: inline-block;
          margin-right: 5px;
        }
      }
    }
    > span {
      line-height: 40px;
      min-width: 100px;
      margin-right: 10px;
      em {
        color: red;
      }
    }
  }
  .el-table.el-table--fit.el-table--enable-row-hover {
    border: 1px solid #eee;
    border-bottom: none;
  }
  .currentImg:hover{
    cursor: pointer;
  }
}
</style>
