<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: '/flashSale' }">秒杀</el-breadcrumb-item>
          <el-breadcrumb-item>{{ isEdit ? '编辑' : '新建' }}秒杀</el-breadcrumb-item>
        </el-breadcrumb>
        <h3>
          <span>{{ isEdit ? '编辑' : '新建' }}秒杀</span>
        </h3>
      </div>
      <div class="section" v-loading="loading">
        <el-form :model="flashSaleForm" :rules="flashSaleRules" ref="flashSaleForm" label-width="110px" class="demo-ruleForm" label-position="right">
          <el-form-item label="活动名称" prop="activityName">
            <el-input v-model.trim="flashSaleForm.activityName" :disabled="isEdit" class="w-300" type="text" placeholder="活动名称将会在小程序秒杀组件中展示" @input="value => goodsLimit(value)">
              <span slot="suffix">{{ proNameLen }}/9</span>
            </el-input>
          </el-form-item>
          <!-- 数据对话厅现在不接入，统一传值为空 -->
          <!-- <el-form-item label="数据对话">
            <dm-activity-select :repProjectName="projectName" width="300" :actId.sync="flashSaleForm.dataTalkId" :showAdd="false"></dm-activity-select>
          </el-form-item> -->
          <el-form-item label="时间范围" required>
            <el-date-picker :default-time="['00:00:00', '23:59:59']" :picker-options="pickerOptions" :disabled="isEdit" class="date-picker" style="width:400px" v-model="dateValue" type="datetimerange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="适用对象" label-width="120px" class="label-icons" prop="memberSearchType">
            <el-tooltip class="tips-content" popper-class="store-tips" effect="dark" content="秒杀活动将忽略商品设置的会员等级，以活动适用对象为主" placement="top-start">
              <i class="iconfont icon-xinxixianshi" style="color:#909399"></i>
            </el-tooltip>
            <el-radio v-model="flashSaleForm.memberSearchType" :disabled="isEdit" :label="1">全部会员</el-radio>
            <el-radio v-model="flashSaleForm.memberSearchType" :disabled="isEdit" :label="2">会员分组</el-radio>
            <el-radio v-model="flashSaleForm.memberSearchType" :disabled="isEdit" :label="3">会员筛选</el-radio>
          </el-form-item>
          <el-form-item v-if="flashSaleForm.memberSearchType === 2">
            <vue-gic-member-group style="padding-left:0" :defaltSelected="defaltSelected" :height="height" :projectName="projectName" :headerList="headerList" :effectiveStatus="effectiveStatus" @handleDataTransferred="handleDataTransferred" @handleDataLeft="handleDataLeft"> </vue-gic-member-group>
          </el-form-item>
          <el-form-item v-if="flashSaleForm.memberSearchType === 3">
            <div v-if="channel === 0">
              <vue-gic-people :projectName="projectName" :isAdd="isAdd" :searchBackTxt.sync="searchBackTxt" :conditionList.sync="conditionList" :triggerReset="true" :useId="useId" :hasSearchData="hasSearchData" :sceneValue="sceneValue" ref="peopleFilter" @findFilter="findFilter" @getBackData="getBackData" @editHide="editHide" @editShow="editShow" @hideBtn="hideBtn" />
              <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>
            <!-- <div v-if="channel === 1">{{ peopleFilterInfo }}</div>
              -->
            <el-popover placement="top-start" width="400" trigger="hover" :content="searchParams">
              <el-button slot="reference" type="text">{{ peopleFilterInfo }}</el-button>
            </el-popover>
          </el-form-item>
          <el-form-item label="购买限制">
            <el-checkbox-group v-model="flashSaleForm.limit" @change="changeLimit">
              <el-checkbox label="1" :disabled="isEdit">忽略商品&nbsp;(仅对礼品生效)&nbsp;的限购</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="活动列表背景色">
            <el-radio-group v-model="flashSaleForm.activityBackGround">
              <el-radio :label="0">白色</el-radio>
              <el-radio :label="1">灰色</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="活动列表顶图">
            <el-upload class="avatar-uploader" with-credentials :action="uploadAction" :headers="headersUpload" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload">
              <div class="preview-picture" v-if="flashSaleForm.activityImageUrl">
                <i class="el-icon-zoom-in" @click.stop="previewPicture"></i>
                <i class="el-icon-delete" style="margin-left:6px" @click.stop="deletePicture"></i>
              </div>
              <img v-if="flashSaleForm.activityImageUrl" :src="flashSaleForm.activityImageUrl" class="avatar" style="width:100px;height:100px" />
              <div v-else class="avatar-icon">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <span style="display:block;font-size:12px;color:#606266;line-height: 17px;">上传图片</span>
              </div>
            </el-upload>
            <p class="avatar-text">图片宽度≥700px，高度≤1500px，大小不超过 2 MB，未上传展示默认图</p>
            <el-dialog :visible.sync="dialogVisibleImg">
              <img width="100%" :src="flashSaleForm.activityImageUrl" alt />
            </el-dialog>
          </el-form-item>
          <el-form-item label="活动商品设置">
            <div class="add-sku-content">
              <div class="add-table" v-if="selectList.length">
                <el-table :data="selectList" ref="multipleTable" style="width: 100%" :row-key="getRowKeys" default-expand-all :tree-props="{ children: 'children' }">
                  <el-table-column label="商品信息" min-width="200px">
                    <template slot-scope="{ row }">
                      <div style="display: flex">
                        <!-- 保持第一级节点的排序框左对齐 -->
                        <div style="padding-left: 40px;" v-if="row.level == 1"></div>
                        <div class="gift-info" style="display: flex" v-if="row.giftType">
                          <img :src="row.mainImageUrl" alt />
                          <div class="info-name">
                            <p class="pro-ellipsis" :class="[row.giftType ? 'height40' : '']">{{ row.proName }}</p>
                            <p class="category-ellipsis">礼品编码：{{ row.proCode }}</p>
                          </div>
                        </div>
                        <div class="gift-info" style="display: flex" v-else>
                          <img v-if="row.mainImageUrl" :src="row.mainImageUrl" alt />
                          <img v-if="!isEdit && row.cardType === 2 && !row.mainImageUrl" src="../../../../static/img/quan02.png" alt />
                          <img v-if="!isEdit && row.cardType === 0 && !row.mainImageUrl" src="../../../../static/img/quan01.png" alt />
                          <img v-if="!isEdit && row.cardType === 1 && !row.mainImageUrl" src="../../../../static/img/quan03.png" alt />
                          <img v-if="isEdit && row.giftProType === 2 && !row.mainImageUrl" src="../../../../static/img/quan02.png" alt />
                          <img v-if="isEdit && row.giftProType === 0 && !row.mainImageUrl" src="../../../../static/img/quan01.png" alt />
                          <img v-if="isEdit && row.giftProType === 1 && !row.mainImageUrl" src="../../../../static/img/quan03.png" alt />
                          <div class="info-name">
                            <p class="pro-ellipsis">{{ row.proTitle }}</p>
                            <p class="category-ellipsis" v-if="row.proReferId.split(',').length > 1">--</p>
                            <p class="category-ellipsis" v-else>{{ row.remarks || '--' }}</p>
                            <p class="category-ellipsis" v-if="row.proReferId.split(',').length === 1 && row.exchangeFixDateBegin && row.exchangeFixDateEnd">{{ getTimeAll(row.exchangeFixDateBegin) }}至{{ getTimeAll(row.exchangeFixDateEnd) }}</p>
                            <p class="category-ellipsis" v-if="row.proReferId.split(',').length === 1 && !row.exchangeFixDateBegin && !row.exchangeFixDateEnd">长期有效</p>
                            <p class="category-ellipsis" v-if="row.proReferId.split(',').length !== 1">--</p>
                          </div>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="原价" v-if="!isEdit">
                    <template slot-scope="{ row }">{{ row.integralCost }}积分+{{ row.cashCost }}元</template>
                  </el-table-column>
                  <el-table-column label="当前库存" v-if="!isEdit">
                    <template slot-scope="{ row }">{{ row.virtualStock }}</template>
                  </el-table-column>
                  <el-table-column label="活动价格">
                    <template slot-scope="{ row }">
                      <!-- <div v-if="!(row.giftType && row.children && row.children.length)"><el-input v-model.trim="row.activityIntegral" placeholder="输入积分" size="small" class="w-110" @blur="limitIntergral(row.activityIntegral)"></el-input></div>
                      <div v-if="!(row.giftType && row.children && row.children.length)" class="mt10"><el-input v-model.trim="row.activityPrice" placeholder="输入现金" size="small" class="w-110"></el-input></div> -->
                      <div v-if="!(row.giftType && row.children && row.children.length) && !isEdit"><el-input v-model.trim="row.activityIntegral" placeholder="输入积分" size="small" class="w-110" @blur="limitIntergral(row.activityIntegral)"></el-input></div>
                      <div v-if="!(row.giftType && row.children && row.children.length) && !isEdit" class="mt10"><el-input v-model.trim="row.activityPrice" placeholder="输入现金" size="small" class="w-110"></el-input></div>
                      <span v-if="isEdit">{{ row.activityIntegral }}积分+{{ row.activityPrice }}元</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="活动库存" :render-header="isEdit ? renderHeader : renderHeader2">
                    <template slot-scope="{ row }">
                      <div v-if="!(row.giftType && row.children && row.children.length) && !isEdit"><el-input v-model.trim="row.activityStock" placeholder="输入库存" size="small" class="w-110"></el-input></div>
                      <div v-if="!(row.giftType && row.children && row.children.length) && !isEdit" class="mt10"><el-input v-model.trim="row.activityExchangeLimit" placeholder="输入限兑数量" size="small" class="w-110"></el-input></div>
                      <span v-if="isEdit">{{ row.activityStock }}/{{ row.activityTotalStock }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="限兑数量" v-if="isEdit">
                    <template slot-scope="{ row }">{{ row.activityExchangeLimit }}</template>
                  </el-table-column>
                  <el-table-column label="参与活动">
                    <template slot-scope="{ row }">
                      <el-switch v-if="!isEdit && row.isShow" v-model="row.activityProStatus"></el-switch>
                      <el-switch v-if="row.isShow && isEdit" v-model="row.activityProStatus" disabled></el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="90px">
                    <template slot-scope="{ row }">
                      <div style="font-size:0px">
                        <el-button type="text" v-if="row.giftType && row.children && row.children.length && !row.isShow && isEdit && !overStatus" class="mr20" @click="updateSkuStock(row)">调整库存</el-button>
                        <el-popover placement="top" trigger="click" ref="popover2" @show="getStockDetail(row.activityProId)">
                          <div>
                            <el-select v-model="stockType" style="width:100px;">
                              <el-option label="增加" :value="1"></el-option>
                              <!-- <el-option label="减少" :value="0"></el-option> -->
                            </el-select>
                            <el-input-number v-model="stock" width="140" style="margin-left:-6px;" controls-position="right" :min="0" :max="999999"></el-input-number>
                          </div>
                          <!-- <p>当前商品库存：</p> -->
                          <div class="popver-button" style="margin-top:18px;text-align:right">
                            <el-button type="dafault" size="small" @click="$refs.popover2.showPopper = false">取消</el-button>
                            <el-button type="primary" size="small" class="ml10 ml10" @click="handleCostPrice">确认</el-button>
                          </div>
                          <el-button slot="reference" type="text" v-if="!row.giftType && isEdit && !overStatus" class="mr20">调整库存</el-button>
                        </el-popover>
                        <el-popover placement="top" trigger="click" ref="popover3" @show="getStockDetail(row.activityProId)">
                          <div>
                            <el-select v-model="stockType" style="width:100px;">
                              <el-option label="增加" :value="1"></el-option>
                              <!-- <el-option label="减少" :value="0"></el-option> -->
                            </el-select>
                            <el-input-number v-model="stock" width="140" style="margin-left:-6px;" controls-position="right" :min="0" :max="999999"></el-input-number>
                            <!-- <el-input-number v-model.trim="stock" width="140" clearable controls-position="right" :min="0" :max="999999">
                              <el-select v-model="stockType" slot="prepend" style="width:100px;">
                                <el-option label="增加" :value="1"></el-option>
                                <el-option label="减少" :value="0"></el-option>
                              </el-select>
                            </el-input-number> -->
                          </div>
                          <div class="popver-button" style="margin-top:18px;text-align:right">
                            <el-button type="dafault" size="small" @click="$refs.popover3.showPopper = false">取消</el-button>
                            <el-button type="primary" size="small" class="ml10 ml10" @click="handleCostPrice">确认</el-button>
                          </div>
                          <el-button slot="reference" type="text" v-if="row.giftType && row.children && !row.children.length && !row.isShow && isEdit && !overStatus" class="mr20">调整库存</el-button>
                        </el-popover>
                        <el-button type="text" v-if="!row.giftType && !overStatus" @click="deleteSelectList(row)">删除</el-button>
                        <el-button type="text" v-if="row.giftType && !row.isShow && !overStatus" class="mr12" @click="deleteSelectList(row)">删除</el-button>
                        <el-button type="text" v-if="row.giftType && row.children && row.children.length && row.isExpand" @click="changeExpand(row)">收起</el-button>
                        <el-button type="text" v-if="row.giftType && row.children && row.children.length && !row.isExpand" @click="changeExpand(row)">展开</el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="add-sku">
                <div class="add-sku-button">
                  <el-button @click="addGoods" type="text" :disabled="isEdit || selectList.length === 20">添加商品&nbsp;({{ selectList.length }}/20)</el-button>
                </div>
              </div>
            </div>
          </el-form-item>
          <div class="confim-btn" :style="{ width: fixedWidth + 'px' }">
            <el-form-item class="fix-btn">
              <el-button type="primary" size="small" v-if="!isEdit" @click="submitForm('flashSaleForm')">确认新建</el-button>
              <el-button type="primary" size="small" v-else @click="submitForm('flashSaleForm')">保存</el-button>
              <!-- <el-button size="small" @click="goBack">返回</el-button> -->
            </el-form-item>
          </div>
        </el-form>
      </div>
      <goods-select v-if="goodsDialog" :selectListMore="selectListMore" @closeGoodsSelect="closeGoodsSelect" @getSelectList="getSelectList"></goods-select>
      <update-sku-stock v-if="skuStockDialog" :skuStockData="skuStockData" @closeSkuStock="closeSkuStock"></update-sku-stock>
    </div>
  </div>
</template>

<script>
import qs from 'qs';
import request from '../../../service/request.js';
import getInputVal from '../../../utils/common.js';
import goodsSelect from '../../../components/goodsSelect';
import copy from '../../../utils/clone.js';
import updateSkuStock from '../../../components/updateSkuStock';
export default {
  components: {
    goodsSelect,
    updateSkuStock
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          // return time.getTime() > Date.now()//选当前时间之前的时间
          return time.getTime() < Date.now(); //选当前时间之后的时间
        }
      },
      dialogVisibleImg: false,
      stockType: 1,
      stock: '',
      isEdit: false,
      loading: false,
      getTimeAll: getInputVal.formatDate,
      getTime: getInputVal.getTime,
      getTime2: getInputVal.getTime2,
      getHours: getInputVal.getHours,
      proNameLen: 0,
      fixedWidth: document.documentElement.clientWidth - 200,
      flashSaleForm: {
        activityName: '',
        dataTalkId: '', // 数据对话id
        beginTime: '',
        endTime: '',
        memberSearchType: 1, // 会员类型
        limit: [], // 购买限制
        ignoreLimitFlag: 0,
        activityBackGround: 0,
        activityImageUrl: '' // 活动列表顶图
      },
      flashSaleRules: {
        activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        // activityTime: [{ required: true, message: '请选择时间范围', trigger: 'change' }],
        memberSearchType: [{ required: true, trigger: 'change' }]
      },
      projectName: 'integral-mall',
      defaltSelected: [], //  默认穿梭窗已选入数据
      height: 543, // 穿梭窗高度， 默认是543
      // projectName: 'mall', // 默认是memberTag
      headerList: ['isRealTime', 'latestUpdateTime', 'updateType', 'effectiveStatus', 'effectiveDate'], // 表头配置，默认全部，分组名称默认显示不可配置
      effectiveStatus: 1,
      // 人群筛选器
      // projectName: 'mall', // 当前项目名
      searchBackTxt: '', // 保存选中的筛选条件用来不走接口查缩略信息
      getSaveData: '',
      conditionList: [],
      usePeopleFilter: false,
      sceneValue: 'member', // 场景值
      useId: '', // 模板id
      hasSearchData: '', // 当前页回显的数据(接口返回)
      operateType: true, // 编辑的时候是false 新增是true 例如列表筛选是开始true 编辑改成false
      toggleTag: false, // 控制(确认取消)按钮显示的参数,仅供参考,可自行修改
      saveTag: false, // 控制(保存)按钮显示的参数,仅供参考,可自行修改
      searchParams: {}, //查询数据数据
      responseParams: [], //回显的数据
      channel: 0,
      // 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: ''
      },
      goodsDialog: false, // 选择商品弹窗
      selectList: [], // 选中的商品
      selectListCopy: [],
      selectListMore: [],
      isExpand: true, // 收起与展开的显示
      skuStockDialog: false, // 开启和关闭修改实物礼品多规格sku
      skuStockData: [], // 修改实物礼品过规格数据
      activityProList: [],
      activityId: '',
      overStatus: false // 编辑时判断活动是否已结束，true为结束，false为未结束
    };
  },
  created() {
    this.isEdit = this.$route.query.edit;
    this.activityId = this.$route.query.activityId;
    if (this.$route.query.activityId) {
      this.getMess();
    }
  },
  methods: {
    renderHeader(h, { column, $index }, index) {
      return h('span', {}, [h('span', {}, '活动库存'), h('el-popover', { props: { placement: 'top-start', width: '200', trigger: 'hover', content: '活动剩余库存/活动总库存' } }, [h('i', { slot: 'reference', class: 'iconfont icon-xinxixianshi' }, '')])]);
    },
    renderHeader2(h, { column, $index }, index) {
      return h('span', {}, [h('span', {}, '活动库存'), h('el-popover', { props: { placement: 'top-start', width: '200', trigger: 'hover', content: '设置后将会从礼品本身的库存中扣除相应的库存作为活动库存' } }, [h('i', { slot: 'reference', class: 'iconfont icon-xinxixianshi' }, '')])]);
    },
    // 获取详情
    getMess() {
      // get-activity-detail
      let params = {
        activityId: this.activityId
      };
      request.post('/api-integral-mall/get-activity-detail', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          let resResult = res.data.result;
          this.flashSaleForm.activityName = resResult.activityName;
          // this.flashSaleForm.dataTalkId = resResult.dataTalkId;
          this.flashSaleForm.dataTalkId = '';
          this.flashSaleForm.memberSearchType = resResult.memberSearchType;
          this.flashSaleForm.limit = resResult.ignoreLimitFlag ? ['1'] : [];
          this.flashSaleForm.activityBackGround = resResult.activityBackGround;
          this.flashSaleForm.activityImageUrl = resResult.activityImageUrl;
          this.flashSaleForm.beginTime = resResult.beginTime;
          this.flashSaleForm.endTime = resResult.endTime;
          //编辑时根据活动结束时间与当前时间做对比，判断是否已结束，已结束活动编辑时只能查看，不能进行调整库存及删除操作
          let time = new Date();
          if (this.flashSaleForm.endTime < time.getTime()) {
            this.overStatus = true;
          } else {
            this.overStatus = false;
          }
          // this.flashSaleForm.activityName = resResult.memberSearchType ,
          if (resResult.memberSearchType === 2) {
            this.defaltSelected = resResult.memberSearchParams;
          } else if (resResult.memberSearchType === 3) {
            this.searchParams = resResult.memberSearchParams;
          }
          if (resResult.activityProList) {
            this.selectList = [];
            resResult.activityProList.forEach((item, index) => {
              if (item.giftProType === 3) {
                this.selectList.push({
                  isShow: false,
                  activityProStatus: true,
                  activityExchangeLimit: item.activityExchangeLimit,
                  activityIntegral: item.activityIntegral,
                  activityPrice: item.activityPrice,
                  activityStock: item.activityStock,
                  activityTotalStock: item.activityTotalStock,
                  integralMallProId: item.giftProId,
                  giftProType: item.giftProType,
                  giftType: 1,
                  mainImageUrl: item.giftImageUrl,
                  proCode: item.giftCode,
                  proName: item.proName,
                  activityProId: item.activityProId,
                  children: []
                });
                if (item.activityProSkuList && item.activityProSkuList.length) {
                  item.activityProSkuList.forEach(it => {
                    this.selectList[index].children.push({
                      isShow: true,
                      activityProStatus: it.activityProStatus ? true : false,
                      activityExchangeLimit: it.activityExchangeLimit,
                      activityIntegral: it.activityIntegral,
                      activityPrice: it.activityPrice,
                      activityStock: it.activityStock,
                      activityTotalStock: it.activityTotalStock,
                      integralMallProId: it.giftProSkuId,
                      // giftProType: item.giftProType,
                      giftType: 1,
                      level: 1,
                      mainImageUrl: item.giftImageUrl,
                      proCode: item.giftCode,
                      proName: item.proName
                    });
                  });
                }
              } else {
                this.selectList.push({
                  isShow: false,
                  activityProStatus: true,
                  activityExchangeLimit: item.activityExchangeLimit,
                  activityIntegral: item.activityIntegral,
                  activityPrice: item.activityPrice,
                  activityStock: item.activityStock,
                  activityTotalStock: item.activityTotalStock,
                  integralMallProId: item.giftProId,
                  giftType: 0,
                  giftProType: item.giftProType,
                  mainImageUrl: item.giftImageUrl,
                  proCode: item.giftCode,
                  putEffectiveMode: item.putEffectiveMode,
                  proReferId: item.proReferId,
                  exchangeFixDateBegin: item.putBeginDate,
                  exchangeFixDateEnd: item.putEndDate,
                  proTitle: item.proSubTitle
                  // remarks: item.remarks
                  // proName: item.giftName
                });
              }
            });
          }
          console.log(this.selectList);
          this.loading = false;
        } else {
          this.$message.error(res.data.message);
          this.loading = false;
        }
      });
    },
    // 选中活动商品
    getSelectList(val) {
      if (val) {
        // this.isExpand = true;
        this.selectListCopy = val;
        this.selectListCopy.forEach(item => {
          item.giftType = item.type;
          item.isShow = false;
          item.activityProStatus = true;
          item.activityExchangeLimit = ''; // 限兑
          item.activityIntegral = ''; // 活动积分
          item.activityPrice = ''; // 活动价格
          item.activityStock = ''; // 活动库存
          item.isExpand = true;
          let giftProStandardJson = item.giftProStandardJson ? JSON.parse(item.giftProStandardJson) : [];
          if (giftProStandardJson.length) {
            item.children = JSON.parse(item.skuJson);
            item.children.forEach(it => {
              it.mainImageUrl = item.mainImageUrl;
              it.proName = item.proName;
              it.proCode = it.giftProSkuStandCode;
              it.integralCost = it.giftProSkuIntegral;
              it.cashCost = it.giftProSkuCash;
              it.virtualStock = it.stock;
              it.level = 1;
              it.giftType = item.giftType;
              it.integralMallProId = it.giftProSkuId;
              it.activityProStatus = true;
              it.isShow = true;
              it.activityExchangeLimit = ''; // 限兑
              it.activityIntegral = ''; // 活动积分
              it.activityPrice = ''; // 活动价格
              it.activityStock = ''; // 活动库存
            });
          }
        });
        this.selectList = copy(this.selectListCopy);
        console.log(this.selectList);
      }
    },
    getRowKeys(row) {
      //唯一值，一般都未id
      return row.integralMallProId;
    },
    changeExpand(row) {
      row.isExpand = !row.isExpand;
      this.$refs.multipleTable.toggleRowExpansion(row);
    },
    // 删除选择的数据
    deleteSelectList(item, index) {
      console.log(item);
      console.log(index);
      this.selectList.forEach((it, index) => {
        if (it.integralMallProId === item.integralMallProId) {
          this.selectList.splice(index, 1);
        }
      });
    },
    // 开启和关闭选择商品弹窗
    addGoods() {
      this.selectListMore = this.selectList;
      this.goodsDialog = true;
    },
    closeGoodsSelect(val) {
      this.goodsDialog = false;
    },
    // 开启和关闭修改实物礼品多规格sku
    updateSkuStock(item) {
      console.log(item);
      this.skuStockDialog = true;
      this.skuStockData = item;
    },
    closeSkuStock() {
      this.skuStockDialog = false;
    },
    changeLimit(value) {
      if (value.length) {
        this.flashSaleForm.ignoreLimitFlag = 1;
      } else {
        this.flashSaleForm.ignoreLimitFlag = 0;
      }
      console.log(this.flashSaleForm.ignoreLimitFlag);
    },
    // 秒杀活动名称字数限制
    goodsLimit(value) {
      this.$nextTick(() => {
        this.flashSaleForm.activityName = getInputVal.getInputVal(value, 9);
        this.proNameLen = getInputVal.getZhLen(this.flashSaleForm.activityName);
      });
    },
    handleDataTransferred(data) {
      this.defaltSelected = data;
    },
    handleDataLeft(selectedData, selectionToRemove) {
      this.defaltSelected = selectedData;
    },
    //人群筛选器使用的方法
    // 父组件调用子组件方法,触发父组件事件
    getData() {
      var that = this;
      that.$refs.peopleFilter.confirmSet();
      that.usePeopleFilter = true;
    },
    // 子组件触发父组件事件,返回过滤条件数据
    findFilter(value) {
      // var that = this;
      this.searchParams = value;
      console.log(this.searchParams);
    },
    // 取消
    cancelFilter() {
      var that = this;
      that.$refs.peopleFilter.cancelSet();
    },
    // 获取需要回显的数据, 供保存时候使用
    getBackData(val) {
      var that = this;
      that.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();
      }
    },
    // 保存当前模板,对接保存接口
    //校验积分
    limitIntergral(value) {
      console.log(value);
    },
    // 预览
    previewPicture() {
      this.dialogVisibleImg = true;
    },
    deletePicture() {
      this.flashSaleForm.activityImageUrl = '';
    },
    beforeUpload(file) {
      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' && file.type !== 'image/gif') {
        this.$message.error('请上传jpg，png，gif格式的图片');
        return false;
      }
      if (localStorage.getItem('sign')) {
        this.headersUpload.sign = localStorage.getItem('sign');
      } else {
        this.headersUpload.sign = '';
      }
      var that = this;
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        reader.onload = function(event) {
          let image = new Image();
          image.onload = function() {
            let width = this.width;
            // let height = this.height;
            if (width < 700 || width > 1500) {
              that.$message.error('请上传正确的图片尺寸');
              reject();
            }
            resolve();
          };
          image.src = event.target.result;
        };
        reader.readAsDataURL(file);
      });
    },
    handleSuccess(response, file, fileList) {
      if (response.errorCode === 0) {
        this.$message.success('上传成功');
        this.flashSaleForm.activityImageUrl = response.result[0].qcloudImageUrl;
      } else {
        this.$message.error(response.message);
      }
    },
    // 保存
    submitForm(flashSaleForm) {
      if (this.selectList.length) {
        console.log(this.selectList);
        this.selectList.forEach((item, index) => {
          // console.log(111);
          this.activityProList.push({
            activityExchangeLimit: item.activityExchangeLimit,
            activityIntegral: item.activityIntegral,
            activityPrice: item.activityPrice,
            activityProStatus: 1,
            activityStock: item.activityStock,
            giftProId: item.integralMallProId,
            activityProSkuList: []
          });
          // console.log(222);
          if (item.children && item.children.length) {
            // console.log(item.activityProSkuList);
            console.log(this.activityProList[index].activityProSkuList);
            item.children.forEach(it => {
              // console.log(333);
              // console.log(item.activityProSkuList);
              this.activityProList[index].activityProSkuList.push({
                activityExchangeLimit: it.activityExchangeLimit,
                activityIntegral: it.activityIntegral,
                activityPrice: it.activityPrice,
                activityProStatus: it.activityProStatus ? '1' : '0',
                activityStock: it.activityStock,
                giftProId: item.integralMallProId,
                giftProSkuId: it.integralMallProId
              });
              console.log(44);
            });
          }
        });
        console.log(this.activityProList);
      } else {
        this.$message.error('请选择参加活动的商品');
        return false;
      }
      if (!this.flashSaleForm.activityImageUrl) {
        this.$message.error('请上传活动列表顶图');
        return false;
      }
      if (this.defaltSelected.length < 1 && this.flashSaleForm.memberSearchType === 2) {
        //没有选择会员分组
        this.$message.error('请选择会员分组');
        return false;
      }
      if (this.flashSaleForm.memberSearchType === 3) {
        console.log(this.toggleTag, !this.getSaveData);
        if (this.toggleTag && !this.getSaveData) {
          this.$message.error('请选中人群筛选器的数据');
          return false;
        }
      }
      let memberLabelId;
      // if (this.flashSaleForm.memberLabelType === 1) {
      //   memberLabelId = '';
      //   this.searchParams = '';
      //   this.responseParams = '';
      // } else if (this.flashSaleForm.memberLabelType === 2) {
      //   memberLabelId = [];
      //   // 处理会员分组的数据
      //   for (let item of this.defaltSelected) {
      //     memberLabelId.push(item.memberTagGroupId);
      //   }
      //   memberLabelId = memberLabelId.join(',');
      //   this.searchParams = '';
      //   // this.responseParams = '';
      // } else if (this.flashSaleForm.memberLabelType === 3) {
      //   memberLabelId = '';
      // }
      if (this.flashSaleForm.memberLabelType === 2) {
        memberLabelId = [];
        for (let item of this.defaltSelected) {
          memberLabelId.push(item.memberTagGroupId);
        }
        memberLabelId = memberLabelId.join(',');
      }
      if (!this.flashSaleForm.beginTime && !this.flashSaleForm.endTime) {
        this.$message.error('请选择活动时间');
        return false;
      }
      this.$refs[flashSaleForm].validate(valid => {
        if (valid) {
          let params = {
            activityName: this.flashSaleForm.activityName,
            // dataTalkId: this.flashSaleForm.dataTalkId, // 数据对话id
            dataTalkId: '', // 数据对话id
            beginTime: this.flashSaleForm.beginTime,
            endTime: this.flashSaleForm.endTime,
            memberSearchType: this.flashSaleForm.memberSearchType, // 会员类型
            ignoreLimitFlag: this.flashSaleForm.ignoreLimitFlag,
            activityBackGround: this.flashSaleForm.activityBackGround,
            activityImageUrl: this.flashSaleForm.activityImageUrl, // 活动列表顶图
            memberSearchParams: this.flashSaleForm.memberSearchType === 1 ? '' : this.flashSaleForm.memberSearchType === 2 ? this.memberLabelId : this.flashSaleForm.memberSearchType === 3 ? this.searchParams : '', // 人群筛选器或会员分组数据
            activityProList: this.activityProList
          };
          let data = JSON.stringify(params);
          let params2 = {
            data: data
          };
          if (!this.isEdit) {
            request.post('/api-integral-mall/create-activity', qs.stringify(params2)).then(res => {
              if (res.data.errorCode === 0) {
                this.$message.success('新建成功');
                this.$router.push({
                  name: 'flashSale'
                });
                this.loading = false;
              } else {
                this.$message.error(res.data.message);
                this.loading = false;
              }
            });
          } else {
            request.post('/api-integral-mall//update-activity', qs.stringify(params2)).then(res => {
              if (res.data.errorCode === 0) {
                this.$message.success('保存成功');
                this.$router.push({
                  name: 'flashSale'
                });
                this.loading = false;
              } else {
                this.$message.error(res.data.message);
                this.loading = false;
              }
            });
          }
        }
      });
    }
  },
  computed: {
    dateValue: {
      get() {
        return [this.flashSaleForm.beginTime, this.flashSaleForm.endTime];
      },
      set(val) {
        // [this.flashSaleForm.beginTime, this.flashSaleForm.endTime] = val ? [this.getTimeAll(val[0]), this.getTimeAll(val[1])] : ['', ''];
        [this.flashSaleForm.beginTime, this.flashSaleForm.endTime] = val ? val : ['', ''];
      }
    }
  }
};
</script>
<style scoped>
.section {
  background: #fff;
  margin: 24px;
  padding: 24px;
}
.w-300 {
  width: 300px;
}
.w-280 {
  width: 280px;
}
.w-140 {
  width: 140px;
}
.w-110 {
  width: 110px;
}
.mt10 {
  margin-top: 10px;
}
.mr20 {
  margin-right: 20px;
}
.mr12 {
  margin-right: 12px;
}
.height40 {
  height: 40px;
}
.tips-content {
  position: absolute;
  left: -40px;
}
/* .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
} */
/* 固定按钮 */
.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;
}
/* 图片上传 */
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-icon {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar-uploader-icon {
  width: 20px;
  height: 20px;
  font-size: 20px;
  color: #c0c4cc;
  display: block;
  margin: auto;
  margin-top: 26px;
  margin-bottom: 11px;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  display: block;
  background: #f5f7fa;
  border: 1px dashed #c4c6cf;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.preview-picture {
  position: absolute;
  width: 100px;
  height: 100px;
  color: #fff;
  line-height: 100px;
  vertical-align: middle;
  display: none;
  font-size: 20px;
  background: rgba(0, 0, 0, 0.5);
  z-index: 30;
}
.avatar-uploader:hover .preview-picture {
  display: block;
}
.avatar-text {
  font-size: 12px;
  font-weight: 400;
  color: #909399;
  line-height: 17px;
  margin-top: 8px;
}
/* 添加商品 */

.add-sku-content {
  border: 1px solid #e4e7ed;
}
.add-table {
  margin: 10px 13px;
  background: #f7f8fa;
}
.add-sku {
  margin: 10px 13px;
  padding-top: 7px;
  padding-left: 8px;
  padding-bottom: 7px;
  background: #f7f8fa;
}
.add-sku-button {
  width: 130px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px dashed #c4c6cf;
  text-align: center;
}
.add-sku-button .el-button {
  color: #606266;
}
.add-sku-button .el-button:hover {
  color: #597ef7;
}

.gift-info img {
  width: 60px;
  height: 60px;
  background: #ffffff;
  border: 1px solid #dcdfe6;
  margin-right: 10px;
  /* border-radius: 4px; */
  /* padding: 4px; */
  /* border: 1px solid #dcdfe6; */
}
.info-name {
  display: inline-block;
  vertical-align: top;
  width: 80%;
}
.pro-ellipsis {
  color: #303133;
  /* height: 45px; */
  line-height: 18px;
  /* width: 230px; */
  font-size: 14px;
}
.category-ellipsis {
  color: #909399;
  font-size: 13px;
}
.el-icon-edit {
  margin-left: 5px;
  cursor: pointer;
}
.operate-span {
  font-size: 13px;
  cursor: pointer;
}
.intergral-edit .el-icon-edit {
  display: none;
}
.intergral-edit:hover .el-icon-edit {
  display: inline-block;
}
.icon-xinxixianshi {
  margin-left: 5px;
  color: #909399;
  font-size: 14px;
  cursor: pointer;
}
.page-info {
  padding: 8px 16px;
  box-sizing: border-box;
  border-radius: 4px;
  background: #f4f4f5;
  color: #606266;
  margin-bottom: 22px;
  line-height: 1.5;
}
.page-info h3 {
  font-size: 13px;
  color: #606266;
  margin-bottom: 4px;
}
.page-info .el-icon-info {
  color: #1890ff;
  margin-right: 10px;
  font-size: 14px;
}
</style>
<style>
.add-table .el-table [class*='el-table__row--level'] .el-table__expand-icon {
  display: none !important;
}
.store-tips {
  width: 200px;
  position: absolute;
  left: -10px;
}
.label-icons .el-form-item__label {
  padding-right: 40px !important;
}
</style>
