<template>
  <div style="padding: 20px">
    <!-- 第一步 -->
    <div v-if="steps == 1">
      <h3>基本信息</h3>
      <el-form ref="form" :rules="rules" :model="shopInfo" label-width="200px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="storeRaffle.title">
              <el-input
                :show-word-limit="true"
                type="text"
                maxlength="12"
                style="width: 300px"
                placeholder="请输入名称"
                v-model="shopInfo.storeRaffle.title"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="活动时间:"
              prop="storeRaffle.dateRange"
              style="margin-top: 20px"
            >
              <el-date-picker
                v-model="shopInfo.storeRaffle.dateRange"
                type="datetimerange"
                range-separator="-"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="datePicker"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item
              label="活动透出图片:"
              prop="storeRaffle.pic"
              style="margin-top: 20px"
            >
              <el-upload
                class="upload-demo"
                :http-request="(data) => requestUpload(data)"
                drag
                :limit="1"
                action="#"
                accept=".png,.jpg,.jpeg"
                :show-file-list="false"
              >
                <template v-if="shopInfo.storeRaffle.pic">
                  <el-image
                    style="width: 100%; height: 100%"
                    :src="shopInfo.storeRaffle.pic"
                    :fit="fit"
                  ></el-image>
                </template>
                <template v-else>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                  <div class="el-upload__tip" slot="tip">
                    图片要求:大小不超过2M,尺寸为600px * 100px
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item
              label="每个ID抽奖次数"
              prop="storeRaffle.userLimitNum"
              style="margin-top: 20px"
            >
              <el-input-number
                v-model="shopInfo.storeRaffle.userLimitNum"
                style="width: 300px"
                :controls="false"
                max="9999"
                min="1"
                step="1"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              label="参与活动用户资格"
              prop="storeRaffle.joinType"
              style="margin-top: 20px"
            >
              <el-radio-group v-model="shopInfo.storeRaffle.joinType">
                <el-radio :label="0">所有人</el-radio>
                <el-radio :label="1">固定时间下单</el-radio>
              </el-radio-group>

              <div v-if="shopInfo.storeRaffle.joinType == 1">
                <el-date-picker
                  v-model="shopInfo.storeRaffle.dateRange1"
                  type="datetimerange"
                  range-separator="-"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="xdPicker"
                >
                </el-date-picker>
                <div style="margin-top: 10px">
                  且下单金额累计满
                  <el-input-number
                    v-model="shopInfo.storeRaffle.orderFullAmount"
                    :controls="false"
                    max="9999"
                    min=""
                    step="1"
                  ></el-input-number
                  >元
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: center">
            <el-button type="primary" @click="submitForm(2)">下一步</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 第二步 -->
    <div v-if="steps == 2">
      <h3>设置奖品</h3>
      <span style="color: orange">建议奖品数量不超过五个</span>
      <div
        style="background: #f4f4f4; padding: 20px; margin-top: 20px"
        v-for="(item, index) in shopInfo.storeRaffleGiftList"
        :key="index"
      >
        <i
          @click="removePrize(item, index, 'Raffle')"
          class="el-icon-delete"
          style="cursor: pointer; color: red; position: absolute; right: 50px"
        ></i>
        <el-form
          ref="form2"
          :model="item"
          :rules="rulesFor"
          label-width="160px"
        >
          <el-row style="width: 90%">
            <el-col :span="18">
              <el-form-item label="奖品类型:" prop="giftType">
                <el-radio-group
                  v-model="item.giftType"
                  @change="radioChange(item)"
                >
                  <el-radio :label="0">代金券</el-radio>
                  <el-radio :label="1">免单商品</el-radio>
                  <el-radio :label="2">下单折扣</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="商品折扣比例%:"
                prop="discountRatio"
                v-if="item.giftType == 2"
              >
                <el-input-number
                  v-model="item.discountRatio"
                  style="width: 300px"
                  :controls="false"
                  max="100"
                  min="0"
                  step="1"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="奖品数量:" prop="giftNum">
                <el-input-number
                  v-model="item.giftNum"
                  style="width: 300px"
                  :controls="false"
                  max="9999"
                  min="1"
                  step="1"
                ></el-input-number>
              </el-form-item>

              <el-form-item label="中奖概率%" prop="giftRatio">
                <el-input-number
                  v-model="item.giftRatio"
                  style="width: 300px"
                  :controls="false"
                  max="100"
                  min="1"
                  step="1"
                ></el-input-number>
              </el-form-item>

              <el-form-item
                label="选择代金券"
                prop="userLimitNum"
                v-if="item.giftType == 0"
              >
                <el-button
                  type="primary"
                  size="mini"
                  style="pointer-events: all"
                  @click="Choose(item, 'djq')"
                  >选择代金券</el-button
                >
                <el-table
                  v-if="item.storeVoucherVos"
                  v-loading="loading"
                  :data="item.storeVoucherVos"
                >
                  <el-table-column label="ID" align="center" prop="id" />
                  <el-table-column label="名称" align="center" prop="title" />
                  <el-table-column label="类型" align="center">
                    <template slot-scope="scope">
                      {{
                        scope.row.type == 1
                          ? "独立券"
                          : scope.row.type == 2
                          ? "连锁券"
                          : scope.row.type == 3
                          ? "联合券"
                          : ""
                      }}
                    </template>
                  </el-table-column>

                  <el-table-column label="推广方式" align="center">
                    <template slot-scope="scope">
                      {{
                        scope.row.showType == 0
                          ? "全网自动推出"
                          : scope.row.showType == 1
                          ? "定向渠道推广"
                          : ""
                      }}
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="总发放数量"
                    align="center"
                    prop="sendNum"
                  />
                  <el-table-column
                    label="已领取数量"
                    align="center"
                    prop="receiveNum"
                  />
                  <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        style="color: #00b529"
                        @click="removeVercher(item, scope.$index)"
                        >移除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-form-item
                label="选择商品"
                prop="userLimitNum"
                v-if="item.giftType == 1 || item.giftType == 2"
              >
                <el-button
                  type="primary"
                  size="mini"
                  @click="Choose(item, 'spu')"
                  style="pointer-events: all"
                  >选择商品</el-button
                >

                <el-table
                  v-if="item.spuList"
                  v-loading="loading"
                  :data="item.spuList"
                  @selection-change="handleSelectionChange"
                  row-key="id"
                >
                  <!-- <el-table-column type="selection" width="55" align="center" /> -->
                  <el-table-column label="商品Id" align="center" prop="id" />
                  <el-table-column label="商品信息" align="center">
                    <template slot-scope="scope">
                      <div
                        style="
                          display: flex;
                          flex-direction: row;
                          justify-content: space-between;
                          align-items: center;
                        "
                      >
                        <el-image
                          style="width: 30px; height: 30px"
                          :src="scope.row.pic"
                          :preview-src-list="[scope.row.pic]"
                        >
                        </el-image>
                        <div
                          :title="scope.row.title"
                          style="
                            width: 80px;
                            height: auto;
                            word-wrap: break-word;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                          "
                        >
                          {{ scope.row.title }}
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="分类"
                    align="center"
                    prop="categoryName"
                  />
                  <el-table-column label="商品状态" align="center">
                    <template slot-scope="scope">
                      {{
                        scope.row.spuStatus == 2
                          ? "售罄"
                          : scope.row.spuStatus == 0
                          ? "上架"
                          : scope.row.spuStatus == 1
                          ? "下架"
                          : ""
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="销量"
                    align="center"
                    prop="salesVolume"
                  />
                  <el-table-column label="价格" align="center" width="120">
                    <template slot-scope="scope">
                      {{ scope.row.originalPrice }}元/{{ scope.row.unit }}
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" align="center" width="120">
                    <template slot-scope="scope">
                      {{
                        scope.row.spuType == 0
                          ? "农商商品"
                          : scope.row.spuType == 1
                          ? "同城秒送商品"
                          : scope.row.spuType == 2
                          ? "会员专区"
                          : ""
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" align="center" width="120">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        style="color: #00b529"
                        @click="removeVercherspu2(item, scope.$index)"
                        >移除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-button type="text" @click="addPrize">添加奖品</el-button>

      <el-col :span="24" style="text-align: center">
        <el-button @click="submitForm(1, 'step')">上一步</el-button>
        <el-button type="primary" @click="submitForm(3)">下一步</el-button>
      </el-col>
    </div>

    <!-- 第三步 -->
    <div v-if="steps == 3">
      <h3>配置获得抽奖次数任务</h3>
      <div
        style="background: #f4f4f4; padding: 20px; margin-top: 20px"
        v-for="(item, index) in shopInfo.storeRaffleTaskList"
        :key="index"
      >
        <i
          @click="removePrize(item, index, 'Task')"
          class="el-icon-delete"
          style="cursor: pointer; color: red; position: absolute; right: 50px"
        ></i>
        <el-form
          ref="form3"
          :model="item"
          label-width="160px"
          :rules="rulesThree"
        >
          <el-row style="width: 90%">
            <el-col :span="18">
              <el-form-item label="任务类型:" prop="taskType">
                <el-radio-group v-model="item.taskType">
                  <el-radio :label="0">浏览商品</el-radio>
                  <el-radio :label="1">加购商品</el-radio>
                  <el-radio :label="2">店铺下单</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                v-if="item.taskType != 2"
                :label="
                  item.taskType == 0
                    ? '浏览时间(秒)'
                    : item.taskType == 1
                    ? '加购商品数量'
                    : ''
                "
                prop="taskVal"
              >
                <el-input-number
                  v-model="item.taskVal"
                  style="width: 300px"
                  :controls="false"
                  max="9999"
                  min=""
                  step="1"
                  :placeholder="
                    item.taskType == 0
                      ? '请输入浏览时间'
                      : item.taskType == 1
                      ? '加购商品数量'
                      : ''
                  "
                ></el-input-number>
              </el-form-item>
              <el-form-item label="奖励抽奖次数" prop="rewardNum">
                <el-input-number
                  v-model="item.rewardNum"
                  style="width: 300px"
                  :controls="false"
                  max="9999"
                  min="1"
                  step="1"
                  placeholder="请输入奖励抽奖次数"
                ></el-input-number>
              </el-form-item>

              <el-form-item label="完成任务限制" prop="taskLimitType">
                <el-radio-group v-model="item.taskLimitType">
                  <el-radio :label="0">活动时间限制次数</el-radio>
                  <el-radio :label="1">每天限制次数</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="可完成任务次数" prop="taskLimitNum">
                <el-input-number
                  v-model="item.taskLimitNum"
                  style="width: 300px"
                  :controls="false"
                  max="9999"
                  min=""
                  step="1"
                  placeholder="请输入可完成任务次数"
                ></el-input-number>
                <div v-if="item.taskType == 2" style="color: orange">
                  避免用户下单后退单,以此来获得抽奖机会薅羊毛,建议奖励抽奖次数配置少一点
                </div>
              </el-form-item>
              <el-form-item
                label="选择商品"
                prop="userLimitNum"
                v-if="item.taskType != 2"
              >
                <el-button
                  type="primary"
                  size="mini"
                  @click="Choose(item, 'spu')"
                  style="pointer-events: all"
                  >选择商品</el-button
                >

                <el-table
                  v-if="item.spuList"
                  v-loading="loading"
                  :data="item.spuList"
                  @selection-change="handleSelectionChange"
                  row-key="id"
                >
                  <!-- <el-table-column type="selection" width="55" align="center" /> -->
                  <el-table-column label="商品Id" align="center" prop="id" />
                  <el-table-column label="商品信息" align="center">
                    <template slot-scope="scope">
                      <div
                        style="
                          display: flex;
                          flex-direction: row;
                          justify-content: space-between;
                          align-items: center;
                        "
                      >
                        <el-image
                          style="width: 30px; height: 30px"
                          :src="scope.row.pic"
                          :preview-src-list="[scope.row.pic]"
                        >
                        </el-image>
                        <div
                          :title="scope.row.title"
                          style="
                            width: 80px;
                            height: auto;
                            word-wrap: break-word;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                          "
                        >
                          {{ scope.row.title }}
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="分类"
                    align="center"
                    prop="categoryName"
                  />
                  <el-table-column label="商品状态" align="center">
                    <template slot-scope="scope">
                      {{
                        scope.row.spuStatus == 2
                          ? "售罄"
                          : scope.row.spuStatus == 0
                          ? "上架"
                          : scope.row.spuStatus == 1
                          ? "下架"
                          : ""
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="销量"
                    align="center"
                    prop="salesVolume"
                  />
                  <el-table-column label="价格" align="center" width="120">
                    <template slot-scope="scope">
                      {{ scope.row.originalPrice }}元/{{ scope.row.unit }}
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" align="center" width="120">
                    <template slot-scope="scope">
                      {{
                        scope.row.spuType == 0
                          ? "农商商品"
                          : scope.row.spuType == 1
                          ? "同城秒送商品"
                          : scope.row.spuType == 2
                          ? "会员专区"
                          : ""
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" align="center" width="120">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        style="color: #00b529"
                        @click="removeVercherspu(item, scope.$index)"
                        >移除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-button type="text" @click="addPrize3">添加奖品</el-button>

      <el-form ref="form4" label-width="160px" :rules="rulesRule">
        <el-form-item label="活动规则" prop="contont">
          <el-button type="primary" size="mini" @click="addRule"
            >生成规则</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-input
            readonly
            type="textarea"
            :rows="20"
            placeholder="请输入内容"
            v-model="contont"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <el-col :span="24" style="text-align: center">
        <el-button @click="submitForm(2, 'step')">上一步</el-button>
        <el-button type="primary" @click="submitFormOK">保存并发布</el-button>
      </el-col>
    </div>

    <el-dialog title="选择代金券" :visible.sync="VoucherDialog" width="60%">
      <voucherList :dialog="false" @voucherChoose="voucherChoose"></voucherList>
    </el-dialog>

    <el-dialog
      title="选择商品"
      :visible.sync="SpuDialog"
      width="60%"
      :destroy-on-close="true"
    >
      <voucherSpuList
        :selectData="selectSpuRow"
        :dialog="false"
        @voucherChoose="voucherChooseSpu"
      ></voucherSpuList>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SpuDialog = false">取 消</el-button>
        <el-button type="primary" @click="SpuDialogOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { storeRaffleSave, storeRaffleInfo } from "@/api/marketing/lottery";
import voucherSpuList from "./components/spulist.vue";
import voucherList from "./components/voucherlist.vue";
import axios from "axios";
import moment from "moment";
import { getToken } from "@/utils/auth";
import { getStoreInfo } from "@/api/common/index";
export default {
  components: { voucherList, voucherSpuList },
  data() {
    return {
      SpuDialog: false,
      VoucherDialog: false,
      headers: {
        Auth: "Bearer " + getToken(),
        "Content-type": "multipart/form-data",
      },
      steps: 1,
      rulesRule: {
        contont: [
          { required: true, message: "请生成活动规则", trigger: "blur" },
        ],
      },
      rulesFor: {
        discountRatio: [
          { required: true, message: "请输入折扣比例", trigger: "blur" },
        ],
        giftNum: [
          { required: true, message: "请输入奖品数量", trigger: "blur" },
        ],
        giftRatio: [
          { required: true, message: "请输入奖品概率", trigger: "blur" },
        ],
        giftType: [
          { required: true, message: "请输入奖品类型", trigger: "blur" },
        ],
      },

      rulesThree: {
        taskType: [
          { required: true, message: "请选择任务类型", trigger: "blur" },
        ],
        taskVal: [
          { required: true, message: "请输入任务要求", trigger: "blur" },
        ],
        rewardNum: [
          { required: true, message: "请输入奖励抽取次数", trigger: "blur" },
        ],
        taskLimitType: [
          { required: true, message: "请选择任务限制", trigger: "blur" },
        ],
      },
      rules: {
        "storeRaffle.title": [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        "storeRaffle.dateRange": [
          { required: true, message: "请选择活动时间", trigger: "blur" },
        ],
        "storeRaffle.pic": [
          { required: true, message: "请上传图片", trigger: "blur" },
        ],
        "storeRaffle.userLimitNum": [
          { required: true, message: "请输入每个ID抽奖次数", trigger: "blur" },
        ],
        "storeRaffle.joinType": [
          {
            required: true,
            message: "请选择参与活动用户资格",
            trigger: "blur",
          },
        ],
      },
      shopInfo: {
        storeRaffle: {
          title: "",
          dateRange: [],
          pic: "",
          userLimitNum: "1",
          joinType: 0,
          orderStartTime: "",
          orderEndTime: "",
          startTime: "",
          endTime: "",
        },

        storeRaffleGiftList: [
          {
            discountRatio: "",
            giftIds: "",
            giftNum: "",
            giftRatio: "",
            giftType: 0,
          },
        ],
        storeRaffleTaskList: [
          {
            rewardNum: "",
            taskIds: "",
            taskLimitNum: "",
            taskLimitType: 0,
            taskType: 0,
            taskVal: "",
          },
        ],
      },
      selectRow: {},
      selectSpuRow: {},
      spuRemoveList: [],
      contont: "",
      tablevalue: null,
      pageinfo: {
        page: 1,
        size: 10,
        total: 0,
      },
      storeInfo: {},
    };
  },
  mounted() {
    this.getInfo();
    this.getStore();
  },
  methods: {
    getStore() {
      getStoreInfo().then((res) => {
        if (res.code == 200) {
          this.storeInfo = res.data;
        }
      });
    },
    getInfo() {
      storeRaffleInfo(this.$route.query.id).then((res) => {
        if (res.code === 200) {
          console.log(res.data);
          this.shopInfo.storeRaffle = res.data.storeRaffle;
          this.shopInfo.storeRaffleTaskList = res.data.storeRaffleTaskVoList;
          // if (res.data.storeRaffleGiftVoList) {
          //   res.data.storeRaffleGiftVoList.forEach((e) => {
          //     if (e.giftRatio) {
          //       e.giftRatio = e.giftRatio * 100;
          //     }
          //     if (e.discountRatio) {
          //       e.discountRatio = e.discountRatio * 100;
          //     }
          //   });
          // }
          this.shopInfo.storeRaffleGiftList = res.data.storeRaffleGiftVoList;
          if (this.shopInfo.storeRaffle.startTime) {
            const startTime = new Date(this.shopInfo.storeRaffle.startTime);
            const endTime = new Date(this.shopInfo.storeRaffle.endTime);
            this.$set(this.shopInfo.storeRaffle, "dateRange", [
              startTime,
              endTime,
            ]);
          }

          if (this.shopInfo.storeRaffle.startTime) {
            const orderStartTime = new Date(
              this.shopInfo.storeRaffle.orderStartTime
            );
            const orderEndTime = new Date(
              this.shopInfo.storeRaffle.orderEndTime
            );
            this.$set(this.shopInfo.storeRaffle, "dateRange1", [
              orderStartTime,
              orderEndTime,
            ]);
          }
        }
      });
    },
    submitFormOK() {
      for (let i = 0; i < this.shopInfo.storeRaffleTaskList.length; i++) {
        const e = this.shopInfo.storeRaffleTaskList[i];
        if (e.taskType != 2) {
          if (!e.taskIds) {
            this.$message.error("请先选择商品！");
            return; // 如果满足条件，跳出函数，不再继续执行循环
          }
        }
      }
      if (!this.contont) {
        this.$message.error("请生成活动规则！");
        return;
      }
      const form = this.$refs.form3;
      form.forEach((e) => {
        e.validate((valid) => {
          if (valid) {
            this.saveImpl();
          }
        });
      });
    },
    saveImpl() {
      this.$confirm("是否确认保存?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(this.shopInfo);
          // this.shopInfo.storeRaffleGiftList.forEach((e) => {
          //   e.discountRatio = e.discountRatio * 0.01;
          //   e.giftRatio = e.giftRatio * 0.01;
          // });
          // this.shopInfo.storeRaffleGiftList.forEach((e) => {
          //   e.discountRatio = e.discountRatio * 0.01;
          // });
          storeRaffleSave(this.shopInfo).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "保存成功!",
              });
              this.$store.dispatch("tagsView/delView", this.$route); //关闭当前页
              this.$router.replace({
                path: "/marketing/marketing/lottery/index",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(val) {
      this.spuRemoveList = val;
    },
    // radioChange(val) {
    // val.giftIds = "";
    // this.selectRow.storeVoucherVos = [];
    // this.selectSpuRow.spuList = [];
    // },
    removeVercherspu2(record, index) {
      record.spuList.splice(index, 1);
      let ids = record.spuList.map((item) => item.id);
      record.giftIds = `[${ids.toString()}]`;
    },
    removeVercherspu(record, index) {
      record.spuList.splice(index, 1);
      let ids = record.spuList.map((item) => item.id);
      record.taskIds = `[${ids.toString()}]`;
    },
    removeVercher(record, index) {
      record.storeVoucherVos.splice(index, 1);
      let ids = record.spuList.map((item) => item.id);
      record.giftIds = `[${ids.toString()}]`;
    },
    SpuDialogOk() {
      console.log(this.selectSpuRow);
      if (this.steps == 2) {
        let ids = this.tablevalue.map((item) => item.id);
        let old = this.selectSpuRow.giftIds
          ? JSON.parse(this.selectSpuRow.giftIds)
          : [];
        let list = [];
        console.log("old", old);
        if (old.length < 1) {
          list = ids;
        } else {
          list = [...old, ...ids];
        }
        this.selectSpuRow.giftIds = "[" + list.toString() + "]";
        if (this.selectSpuRow.spuList) {
          this.selectSpuRow.spuList = [
            ...this.selectSpuRow.spuList,
            ...this.tablevalue,
          ];
        } else {
          this.selectSpuRow.spuList = this.tablevalue;
        }
      } else {
        let ids = this.tablevalue.map((item) => item.id);
        let old = this.selectSpuRow.taskIds
          ? JSON.parse(this.selectSpuRow.taskIds)
          : [];
        let list = [];
        if (old.length < 1) {
          list = ids;
        } else {
          list = [...old, ...ids];
        }
        this.selectSpuRow.taskIds = "[" + list.toString() + "]";
        if (this.selectSpuRow.spuList) {
          this.selectSpuRow.spuList = [
            ...this.selectSpuRow.spuList,
            ...this.tablevalue,
          ];
        } else {
          this.selectSpuRow.spuList = this.tablevalue;
        }
      }
      this.SpuDialog = false;
    },
    voucherChooseSpu(val) {
      this.tablevalue = val;
    },
    voucherChoose(val) {
      this.selectRow.giftIds = "[" + val.id + "]";
      this.VoucherDialog = false;
      this.selectRow.storeVoucherVos = [];
      this.selectRow.storeVoucherVos.push(val);
      // this.selectRow.storeVoucherVos.push(val);
    },
    Choose(record, type) {
      if (type == "djq") {
        this.selectRow = record;
        this.VoucherDialog = true;
      } else if (type == "spu") {
        this.selectSpuRow = record;
        this.SpuDialog = true;
      }
    },
    removePrize(record, index, type) {
      if (type == "Task") {
        this.shopInfo.storeRaffleTaskList.splice(index, 1);
      } else {
        this.shopInfo.storeRaffleGiftList.splice(index, 1);
      }
    },
    addPrize3() {
      if (this.shopInfo.storeRaffleTaskList.length >= 3) {
        this.$message.error("抽奖任务不能超过3个！");
        return;
      }
      this.shopInfo.storeRaffleTaskList.push({
        rewardNum: "",
        taskIds: "",
        taskLimitNum: "",
        taskLimitType: 0,
        taskType: 0,
        taskVal: "",
      });
    },
    addPrize() {
      if (this.shopInfo.storeRaffleGiftList.length >= 6) {
        this.$message.error("奖品设置不能超过6个！");
        return;
      }
      this.shopInfo.storeRaffleGiftList.push({
        discountRatio: "",
        giftIds: "",
        giftNum: "",
        giftRatio: "",
        giftType: 0,
      });
    },
    submitForm(index, type) {
      if (type) {
        this.steps = index;
      } else {
        if (index == 2) {
          this.$refs.form.validate((valid) => {
            if (valid) {
              this.steps = index;
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        } else if (index == 3) {
          console.log(this.shopInfo);
          this.addRule();
          for (let i = 0; i < this.shopInfo.storeRaffleGiftList.length; i++) {
            const e = this.shopInfo.storeRaffleGiftList[i];
            if (!e.giftIds) {
              this.$message.error("请先选择商品或者代金券");
              return; // 如果满足条件，跳出函数，不再继续执行循环
            }
          }
          const form = this.$refs.form2;
          console.log(form);
          form.forEach((e) => {
            e.validate((valid) => {
              if (valid) {
                // 校验通过的逻辑
                this.steps = index;
                console.log("表单校验通过");
              } else {
                // 校验不通过的逻辑
                console.log("表单校验不通过");
              }
            });
          });
        } else {
          this.steps = index;
        }
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 可以获取图片参数
    async requestUpload(data) {
      const formdata = new FormData();
      formdata.append("file", data.file);
      const res = await axios.post(
        `${process.env.VUE_APP_NSY_UPLOAD_API}/api/third/op/v1/third/uploadPic`,
        formdata,
        {
          headers: this.headers,
        }
      );
      if (res.data.data) {
        this.shopInfo.storeRaffle.pic = res.data.data;
      }
    },

    datePicker(val) {
      console.log(val);
      this.shopInfo.storeRaffle.startTime = moment(val[0]).valueOf();
      this.shopInfo.storeRaffle.endTime = moment(val[1]).valueOf();
    },
    xdPicker(val) {
      this.shopInfo.storeRaffle.orderStartTime = moment(val[0]).valueOf();
      this.shopInfo.storeRaffle.orderEndTime = moment(val[1]).valueOf();
    },

    addRule() {
      this.contont = "";
      this.contont += `一、活动主题`;
      this.contont += `\n【抽取免单大礼】`;
      this.contont += `\n二、活动时间`;
      this.contont += `\n\b\b\b ${moment(this.shopInfo.storeRaffle.startTime).format(
        "YYYY-MM-DD"
      )}-${moment(this.shopInfo.storeRaffle.endTime).format("YYYY-MM-DD")}`;
      this.contont += `\n三、活动参与要求`;
      this.contont += `\n\b1）用户需在农商直采平台注册登录`;
      this.contont += `  ${
        this.shopInfo.storeRaffle.joinType == 1
          ? "\n\b2）需在" +
            moment(this.shopInfo.storeRaffle.orderStartTime).format(
              "YYYY-MM-DD"
            ) +
            moment(this.shopInfo.storeRaffle.orderEndTime).format(
              "YYYY-MM-DD"
            ) +
            "内，在陕西农商网（店铺名称）有过下单行为，且累计满足" +
            this.shopInfo.storeRaffle.orderFullAmount +
            "元"
          : ""
      }`;
      this.contont += `\n四、活动方式`;
      this.contont += ` \n\b2）可通过完成其他方式获得抽奖次数`;
      let info = "";

      this.shopInfo.storeRaffleTaskList.forEach((e) => {
        if (e.taskType == 0) {
          info += `\n\b\b\b浏览商品${e.taskVal}s,获得${e.rewardNum}次抽奖机会`;
        }
        if (e.taskType == 1) {
          info += `\n\b\b\b加购商品${e.taskVal}件,获得${e.rewardNum}次抽奖机会`;
        }
        if (e.taskType == 2) {
          info += `\n\b\b\b在${this.storeInfo.storeName}店铺内下单任意商品,获得${e.rewardNum}次抽奖机会`;
        }
      });
      this.contont += info;
      this.contont += `\n\b2）可通过完成其他方式获得抽奖次数`;
      this.contont += `\n五、奖品信息`;
      let jp = "";
      this.shopInfo.storeRaffleGiftList.forEach((e) => {
        if (e.giftType == 0) {
          jp += `\n\b\b\b1）店铺${e.giftNum}元代金券`;
        }
        if (e.giftType == 1) {
          jp += `\n\b\b\b下单店铺商品,可享免单（固定商品选其一,${e.giftNum}件商品免单）`;
        }
        if (e.giftType == 2) {
          jp += `\n\b\b\b下单店铺商品，可享低折优惠（固定商品选其一，${e.giftNum}件享受低折，）`;
        }
      });
      this.contont += jp;
      this.contont += `\n获奖须知虚拟奖品:
      \n\b(1)代金券:获奖者代金券成功领取后将自动存入获奖者的券包,可在农商直采“我的、代金券"中查询并至${this.storeInfo.storeName}使用。
      \n\b(2)免单商品：获奖者请及时领取下单，如超过活动时间未进行下单，将无法保证领取资格。
      \n\b(3)下单折扣：获奖者请及时领取下单，如超过活动时间未进行下单，将无法保证领取资格。`;
      this.contont += `
        \n六、温馨提示
        \n\b1）活动参与者应仔细阅读本活动须知，参与本活动则视为已阅读、知晓并同意遵守本次活动规则。系统发生故障或遭受第三方攻击及其他主办方无法控制的情形，主办不对因网络传输原因而导致参加者提交的信息错误承担任何责任。如遇不可抗力、网络突发故障范围内，主办方对前述情形所导致的一后果不承担任何责任，并有权相应地取消、终止、修改、暂停或延迟本次活动。
        \n\b2）为保证活动公平，若发现有参与者使用任何不正当手段参加活动，主办方有权在不事先通知的前提下取消其活动参与及获奖资格，包括但不限于：使用非法工具分享、下载、安装、注册、登陆多个账号及其他不正当手段进行的恶意刷量行为，使用相同地址收件及不遵守本活动规则参与活动，影响活动正常有序进行的其他行为。
        \n\b3）禁止利用抽奖活动进行赌博活动等违法违规行为；若在活动前后发现违法违规行为，不仅限于冒用欺诈、赌博、冒用他人身份等用户，主办方有权取消活动参与资格及中奖资格。
        \n\b4）未满18周岁的消费者需在家长(即法定监护人)的陪伴下参加本次活动并行使相关权利
              `;
    },
  },
};
</script>

<style></style>
