<template>
  <section class="dm-wrap pop-form" v-loading="loading">
    <div>
      <el-form ref="form" :model="group" label-width="92px" :rules="rules" :hide-required-asterisk="true">
        <el-form-item label="计划名称：" prop="name">
          <dm-input v-model="group.name" class="w400" placeholder="请输入内容" :maxlength="20"></dm-input>
        </el-form-item>
        <el-form-item label="推广场景：" prop="check">
          <el-checkbox-group v-model="group.scene">
            <el-checkbox label="新品推广"></el-checkbox>
            <el-checkbox label="活动预热"></el-checkbox>
            <el-checkbox label="卡券发放"></el-checkbox>
            <el-checkbox label="进群有礼"></el-checkbox>
            <el-checkbox label="引流开卡"></el-checkbox>
            <el-checkbox label="签到日历"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="dateTime" label="计划时间：">
          <el-date-picker v-model="group.dateTime" @change="filedAllPopDate" :disabled="!!group.id" :picker-options="pickerOptions" :default-time="['00:00:00', '23:59:59']" class="w400" type="datetimerange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          <el-tooltip open-delay="200" content="计划时间不能和列表中已有计划重叠" placement="top">
            <i class="iconfont icon-tishi" style="display:inline-block;color:#C0C4CC;margin-left:2px;font-size:14px;"></i>
          </el-tooltip>
        </el-form-item>
        <p class="line"></p>
        <h2 style="font-size: 16px;font-weight: 600;color: #303133;line-height: 62px;margin:7px 0 0 10px;">弹窗</h2>
        <div v-for="(pop, elIndex) in group.popupList" :key="elIndex">
          <div class="popBox">
            <div class="form_detail">
              <el-form-item label="投放内容：" required>
                <el-radio-group v-model="pop.putonType" :disabled="pop.activeStatus == 2" @change="label => closeTypeChange(label, elIndex)">
                  <el-radio :label="1">图片</el-radio>
                  <el-radio :label="2">卡券</el-radio>
                </el-radio-group>
                <!-- 投放内容  图片 -->
                <div class="upload_box" v-if="pop.putonType === 1">
                  <el-form-item :prop="`content_${elIndex}`">
                    <dm-upload-file class="pop_dm_upload_file" width="400px" :disabled="pop.activeStatus == 2" :action="`${config.api}/api-plug/upload-img?requestProject=marketing`" withCredentials :on-remove="index => handleRemove(index, elIndex)" :before-upload="file => beforeAvatarUpload(file, elIndex)" :on-success="(response, file) => successAvatarUpload(response, file, elIndex)" :file-list="pop.fileList">
                      <template slot="tip">上传jpg/png/gif文件，建议尺寸750x690px，且不超过500kb </template>
                      <template v-slot:file-item="{ fileData }">
                        <div class="file-list-item">
                          <el-image style="width: 70px; height: 70px" :src="fileData.imageUrl || pop.popupImageDetails.imageUrl" fit="cover"></el-image>
                          <p class="info">
                            <el-tooltip v-if="showFileNameTip(fileData.name)" placement="top">
                              <div style="max-width: 260px" slot="content">{{ fileData.name }}</div>
                              <span class="file-name">{{ fileData.name }}</span>
                            </el-tooltip>
                            <span v-else>{{ fileData.name }}</span>
                            <span class="file-size">({{ fileData.size | fileSize }}kb)</span>
                          </p>
                        </div>
                      </template>
                    </dm-upload-file>
                  </el-form-item>
                  <el-form-item label="跳转链接：" class="pop_img_link">
                    <el-tag :closable="pop.activeStatus != 2" type="info" @close="deleteImgLink(pop)" @click="setImgLink(pop)" style="margin-right: 10px;line-height: 20px;height: auto;color: #606266" v-if="pop.popupImageDetails.link && pop.popupImageDetails.link.id">
                      {{ pop.popupImageDetails.link.name }}
                    </el-tag>
                    <el-button type="text" :disabled="pop.activeStatus == 2" @click="setImgLink(pop)" v-else>设置</el-button>
                  </el-form-item>

                  <linktools :linkVisible.sync="pop.linkToolsVisible" :linkData="pop.popupImageDetails.link" :can-save="true" :showType="showType" @linkSelect="val => linkSelect(val, elIndex)" />
                </div>
                <!-- 投放内容  卡券 -->
                <template v-else>
                  <el-form-item :prop="`content_${elIndex}`" v-if="pop.popupCouponDetails">
                    <div v-for="(item, cardIndex) in pop.popupCouponDetails.couponList" :key="cardIndex" style="width:400px;">
                      <div :class="['card-item', cardIndex === 0 ? 'first-card-item' : '']">
                        <p class="info">
                          <span class="type">{{ item.cardType === 0 ? '抵金券' : item.cardType === 1 ? '折扣券' : '兑换券' }}</span>
                          {{ item.cardName }}
                        </p>
                        <i class="iconfont icon-shanchu" v-if="pop.activeStatus != 2" @click="deleteCoupon(cardIndex, elIndex)"></i>
                      </div>
                    </div>
                    <el-button @click="showDialog(elIndex)" :disabled="pop.activeStatus == 2" style="margin-top:10px;" v-if="pop.popupCouponDetails.couponList.length <= 4">选择卡券</el-button>
                  </el-form-item>
                </template>
              </el-form-item>
              <el-form-item label="投放页面：" :prop="`putonPageList_${elIndex}`">
                <template v-if="pop.putonPageList.length">
                  <el-tag :closable="pop.activeStatus != 2" type="info" v-for="page in pop.putonPageList" :key="page.id" @close="deletePage(pop, page.id)" style="margin-right: 10px;color:#606266">
                    {{ page.name }}
                  </el-tag>
                </template>
                <el-button type="text" :disabled="pop.activeStatus == 2" @click="showPutonPage(pop, elIndex)">设置</el-button>
              </el-form-item>
              <el-form-item :prop="`dateTime_${elIndex}`" label="投放时间：">
                <el-date-picker v-model="pop.dateTime" :picker-options="pickerOptions2" @focus="checkGroupDate" @blur="datePickerBulr(elIndex)" @change="time => changePoptime(time, elIndex)" :disabled="pop.activeStatus == 2" :default-time="['00:00:00', '23:59:59']" class="w400" type="datetimerange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                <el-tooltip open-delay="200" content="投放时间不能超过本次计划时间" placement="top">
                  <i class="iconfont icon-tishi" style="display:inline-block;color:#C0C4CC;margin-left:2px;font-size:14px;"></i>
                </el-tooltip>
              </el-form-item>
              <el-form-item label="弹出频次：" :prop="`popupType_${elIndex}`">
                <el-radio-group v-model="pop.popupType" :disabled="pop.activeStatus == 2" class="block_radio">
                  <el-radio :label="1">在用户未完全关闭小程序的情况下，识别用户身份，首次进入弹出，下次进入不再弹出</el-radio>
                  <el-radio :label="2">在用户未完全关闭小程序的情况下，用户每次进入都弹出</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item :prop="`autoCloseFlag_${elIndex}`" label="自动关闭：">
                <el-switch v-model="pop.autoCloseFlag" :active-value="1" :inactive-value="0"></el-switch><span style="font-size:12px;color:#909399;margin-left:8px;">（ 开启后，弹窗会在倒计时后自动关闭 ）</span>
                <el-form-item v-if="pop.autoCloseFlag"> 设置<el-input-number v-model="pop.autoCloseDelay" @change="resetField(`autoCloseFlag_${elIndex}`)" controls-position="right" :min="1" :max="10" :disabled="pop.activeStatus == 2" style="width:90px;margin:0 10px 0 9px;"></el-input-number>秒 后自动关闭 </el-form-item>
              </el-form-item>
            </div>
            <div class="preview">
              <div class="container-content">
                <img v-if="pop.putonType === 1" :src="pop.popupImageDetails.imageUrl" />
                <img v-else src="./assets/img/card.png" />
              </div>
            </div>
          </div>
          <el-form-item label="定向人群：" :prop="`popupMemberGroupList_${elIndex}`">
            <vue-gic-member-group :max-limit="10" :defaltSelected="pop.popupMemberGroupList" :projectName="projectName" :headerList="headerList" :readonly="pop.activeStatus == 2" @handleDataTransferred="data => handleDataTransferred(data, elIndex)" @handleDataLeft="(selectedData, selectionToRemove) => handleDataLeft(selectedData, selectionToRemove, elIndex)"></vue-gic-member-group>
          </el-form-item>
          <div class="sort">
            <el-popover placement="bottom" width="400" trigger="click" popper-class="pop_sort_popover" :disabled="pop.activeStatus == 2">
              <el-radio-group v-model="pop.sortNum" size="small" @change="sortChange">
                <template v-for="(option, opi) in sortOptions">
                  <el-radio v-if="opi !== 0" :key="'option' + opi" :label="opi" :disabled="popSort[opi]"><i :style="'display:inline-block;width:12px;height:12px;margin-right:8px;border-radius: 2px;background-color:' + btnColor[opi] + ';'"></i>{{ option }}</el-radio>
                </template>
              </el-radio-group>
              <el-button slot="reference" round type="primary" :style="'color:#ffffff;border-color: ' + btnColor[pop.sortNum] + ';' + 'background-color:' + btnColor[pop.sortNum] + ';'">{{ sortOptions[pop.sortNum] }}</el-button>
            </el-popover>
            <p class="tip" style="font-size:12px;cursor:default;">点击设置弹窗优先级，当用户命中同一页面多个弹窗时，按优先级顺序弹出一个即停止</p>
            <i class="sort_line"></i>
            <el-button type="info" round class="delete_btn" :disabled="pop.activeStatus == 2" @click="detelePop(elIndex)">删除</el-button>
            <i class="sort_line"></i>
          </div>
        </div>
        <vue-gic-card :showCardDialog.sync="showCardDialog" :cardLimit="-1" :cardType="null" @selectCard="selectCard"> </vue-gic-card>
        <el-dialog title="投放页面" :visible.sync="putonPageDialog">
          <el-select class="select-page" v-model="putonForm.id" placeholder="请选择投放页面" @change="putonPageChange">
            <el-option v-for="page in putonPageList" :label="page.name" :value="page.id" :key="page.id"></el-option>
          </el-select>
          <el-select class="select-page" v-if="putonForm && putonForm.type == 6" v-model="putonForm.customPageId" placeholder="请选择投放页面">
            <el-option v-for="page in customPageList" :label="page.title" :value="page.pageId" :key="page.pageId"></el-option>
          </el-select>
          <div slot="footer" class="dialog-footer">
            <el-button @click="putonPageDialog = false">取 消</el-button>
            <el-button type="primary" @click="putonPageChangeComfirm">确 定</el-button>
          </div>
        </el-dialog>
        <div class="addBtn" v-if="surplus" @click="addPop">
          <i class="iconfont icon-jia"></i>
          <p>还可添加{{ surplus }}个弹窗</p>
        </div>
      </el-form>
    </div>
    <div class="bottomBtn">
      <el-button @click="$router.go(-1)">取消</el-button> <el-button type="primary" @click="submit">{{ group.id ? '保存' : '确认新建' }}</el-button>
    </div>
  </section>
</template>
<script>
// eslint-disable-next-line
import { getPopupPlan, saveOrUpdatePopupPlan, queryPopupLinkList, removePopup, customPageList } from '@/service/api/popApi.js';
import draggable from 'vuedraggable'; // 拖拽
import { _debounce } from '@/utils/index'; // 防抖
import config from '@/config';
import elUploadWrap from '@/components/upload/el-upload-wrap';
import Linktools from '@/components/linktools-fulls/index.vue';
const defaultPop = {
  // 弹窗id
  id: '',
  // 商户id
  enterpriseId: '',
  // 弹窗计划id
  popupPlanId: '',
  // 投放类型（1：图片，2：卡券）
  putonType: 1,
  // 投放页面列表
  putonPageList: [
    // {
    // // 弹窗链接id
    // id: '',
    // // 节点类型（1:普通链接, 6:自定义链接）
    // type: 1,
    // // 链接名称
    // name: '',
    // // 链接内容
    // content: '',
    // // 自定义链接pageId
    // customPageId: '',
    // // 自定义链接名称
    // customPageName: '',
    // }
  ],
  // 投放的会员分组
  popupMemberGroupList: [
    // {
    //   // 会员分组id
    //   memberTagGroupId: '',
    //   // 会员分组名称
    //   groupName: ''
    // }
  ],
  linkToolsVisible: false,
  // 投放详情 - 图片
  popupImageDetails: {
    // 图片链接
    imageUrl: '',
    // 链接信息（链接小工具）
    link: ''
  },
  showCardDialog: false,
  // 投放详情 - 卡券
  popupCouponDetails: {
    // 样式（1：系统默认样式）
    styleType: 1,
    // 卡券列表
    couponList: [
      // {
      //   // 优惠券id
      //   coupCardId: '',
      //   // 卡券类型（0：抵金券，1：折扣券，2：兑换券）
      //   cardType: 0,
      //   // 卡券名称
      //   cardName: ''
      // }
    ]
  },
  // 是否自动关闭（0否 1是）
  autoCloseFlag: 0,
  // 自动关闭时间（秒）
  autoCloseDelay: 0,
  // 是否手动结束（0否 1是）
  manualEndFlag: 0,
  // 手动结束时间（时间戳）
  manualEndTime: 0,
  // 排序优先级（从1开始）
  sortNum: 1,
  // 投放开始时间（时间戳）
  beginTime: 0,
  // 投放结束时间（时间戳）
  endTime: 0,
  // 弹出类型（1首次弹出 2每次弹出）
  popupType: 1,
  // 创建日期（时间戳）
  createTime: 0,
  // 更新时间（时间戳）
  updateTime: 0,
  // 创建人id
  creatorId: '',
  // 创建人名称
  creatorName: '',
  // 弹窗活动状态（1：未开始，2：进行中，3：已结束）
  activeStatus: 1
};
export default {
  name: 'pop-form',
  components: {
    elUploadWrap,
    draggable,
    Linktools
  },
  props: {
    value: [Array, Number, String]
  },
  data() {
    const validateDateLessYear = (rule, value, callback) => {
      const date = this.group.dateTime;
      if (!date[0] || !date[1]) {
        callback(new Error('计划时间不能为空'));
      }
      callback();
    };
    return {
      loading: false,
      projectName: 'marketing', //当前项目名
      config: config,
      group: {
        operateType: 1, // 操作类型（1：新增，2：更新）
        id: '', // 弹窗计划id（新增不传，更新必传）
        name: '', // 计划名称
        scene: [], // 推广场景
        dateTime: [], // 计划时间
        popupList: [] // 弹窗列表
      },
      dateTimeCheck: true,
      dateTimeTip: '',
      rules: {
        name: [{ required: true, message: '请输入计划名称', trigger: 'change' }],
        dateTime: [{ required: true, validator: validateDateLessYear, trigger: 'change' }]
      },
      headerList: ['effectiveStatus'], // 会员分组 表头配置，默认全部，分组名称默认显示不可配置
      showType: 0, // 显示类型,插件默认0:显示全部 ,1: (底部导航);2: (公众号菜单:只有小程序的,没有h5)
      // 0 最高   1 较高   2 普通   3 较低   4 最低
      btnColor: { 1: '#FF555E', 2: '#FAAD14', 3: '#C4C6CF', 4: '#1890FF', 5: '#52C41A' },
      popSort: { 1: false, 2: false, 3: false, 4: false, 5: false },
      sortOptions: ['', '最高', '较高', '普通', '较低', '最低'],
      showCardDialog: false,
      putonPageDialog: false,
      dateDelay: 1,
      timeRange: ['00:00:00 - 02:00:00'],
      putonForm: {
        // // 弹窗链接id
        id: '',
        // 节点类型（1:普通链接, 6:自定义链接）
        type: 1,
        // 链接名称
        name: '',
        // 链接内容
        content: '',
        // 自定义链接pageId
        customPageId: '',
        // 自定义链接名称
        customPageName: ''
      },
      curIndex: 0,
      putonPageList: [],
      customPageList: [], // 自定义页面列表
      minDate: new Date(), // 计划时间（始）
      pickerOptions: {
        // 时间范围6个月
        disabledDate: time => {
          const startTime = new Date(this.minDate).getTime();
          return time < new Date(startTime - 24 * 3600 * 1000) || time > new Date(startTime + 183 * 24 * 3600 * 1000);
        }
      },
      pickerOptions2: {
        // 时间范围6个月
        disabledDate: time => {
          if (this.group.dateTime[0] && this.group.dateTime[1]) {
            const startTime = new Date(new Date(this.group.dateTime[0]) > new Date() ? new Date(this.group.dateTime[0]) : new Date()).getTime();
            // const endTime = new Date(this.group.dateTime[1]);
            return time <= new Date(startTime - 24 * 3600 * 1000) || time > new Date(this.group.dateTime[1]);
          } else {
            return true;
          }
        }
      }
    };
  },
  computed: {
    surplus() {
      return this.group.popupList ? 5 - this.group.popupList.length : 5;
    }
  },
  filters: {
    fileSize(arg1) {
      // 除法
      let int1 = Number(arg1);
      let int2 = 1024;
      return ((int1 / int2) * Math.pow(10, 0)).toFixed(2);
    },
    colorFilter(sort) {
      return this.btnColor[sort];
    }
  },
  created() {
    const path = this.$route.path;
    if (path == '/popup/edit') {
      this.getDetail();
    }
    this.getPopupLinkList();
  },
  methods: {
    async getDetail() {
      const res = await getPopupPlan({ popupPlanId: this.$route.query.id });
      if (res.errorCode === 0 && res.result) {
        let groupPlan = { ...res.result };
        this.minDate = new Date(groupPlan.beginTime) > new Date() ? new Date(groupPlan.beginTime) : new Date();
        groupPlan.dateTime = [new Date(groupPlan.beginTime), new Date(groupPlan.endTime)];
        groupPlan.scene = typeof groupPlan.scene == 'string' ? groupPlan.scene.split(',') : [];
        if (Array.isArray(groupPlan.popupList)) {
          groupPlan.popupList = groupPlan.popupList.map((item, index) => {
            this.addrules(index);
            if (item.putonType == 1) {
              item.linkToolsVisible = false;
              item.popupImageDetails.link = JSON.parse(item.popupImageDetails.link || '{}');
              item.popupCouponDetails = {};
            }
            item.dateTime = [new Date(item.beginTime), new Date(item.endTime)];
            this.popSort[item.sortNum] = true;
            return item;
          });
        }
        Object.keys(this.group).forEach(key => {
          this.group[key] = groupPlan[key];
        });
      }
    },
    submit: _debounce(function() {
      if (this.loading) {
        return;
      }
      this.$refs.form.validate(vali => {
        if (!vali) return;

        if (!this.group.id) {
          delete this.group.id;
        }
        this.group.operateType = this.group.id ? 2 : 1;
        if (Array.isArray(this.group.popupList)) {
          this.group.popupList = this.group.popupList.map(el => {
            if (el.putonType == 1) {
              el.popupCouponDetails = null;
            }
            if (el.putonType == 2) {
              el.popupImageDetails = null;
            }
            return el;
          });
        }
        this.loading = true;
        const params = Object.assign({}, this.group);
        params.scene = params.scene.join(',');
        params.beginTime = new Date(params.dateTime[0]).getTime();
        params.endTime = new Date(params.dateTime[1]).getTime();
        delete params.dateTime;
        params.popupList.map(pop => {
          pop.beginTime = new Date(pop.dateTime[0]).getTime();
          pop.endTime = new Date(pop.dateTime[1]).getTime();
        });
        saveOrUpdatePopupPlan(params)
          .then(res => {
            this.$message.success('保存成功');
            this.loading = false;
            this.$router.go(-1);
          })
          .catch(err => {
            this.loading = false;
          });
      });
    }),
    addPop() {
      const index = this.group.popupList.length;
      this.addrules(index);
      // let sortNum = 0;
      for (const key in this.popSort) {
        if (!this.popSort[key]) {
          const pop = JSON.parse(JSON.stringify(defaultPop));
          this.popSort[`${key}`] = true;
          this.group.popupList.push(Object.assign({}, pop, { sortNum: key, fileList: [] }));
          return;
        }
      }
    },
    addrules(index) {
      // 投放内容
      this.rules[`content_${index}`] = [
        {
          required: true,
          validator: (rule, value, callback) => {
            const index = Number(rule.field.split('_')[1]);
            const item = this.group.popupList[index];
            if (item.putonType == 1 && item.popupImageDetails && !item.popupImageDetails.imageUrl) {
              callback(new Error('请上传图片'));
            }
            if (item.putonType == 2 && item.popupCouponDetails && (!Array.isArray(item.popupCouponDetails.couponList) || item.popupCouponDetails.couponList == 0)) {
              callback(new Error('请选择卡券'));
            }
            callback();
          },
          trigger: 'change'
        }
      ];
      // 定向人群
      this.rules[`popupMemberGroupList_${index}`] = [
        {
          required: true,
          validator: (rule, value, callback) => {
            const index = Number(rule.field.split('_')[1]);
            const item = this.group.popupList[index];
            if (item.popupMemberGroupList && !item.popupMemberGroupList.length) {
              callback(new Error('请选择定向人群'));
            }
            if (item.popupMemberGroupList && item.popupMemberGroupList.length > 10) {
              callback(new Error('会员分组数量不能超过10个'));
            }
            callback();
          },
          trigger: 'change'
        }
      ];
      // 投放页面
      this.rules[`putonPageList_${index}`] = [
        {
          required: true,
          validator: (rule, value, callback) => {
            const index = Number(rule.field.split('_')[1]);
            const item = this.group.popupList[index];
            if (item.putonPageList && !item.putonPageList.length) {
              callback(new Error('请选择投放页面'));
            }
            callback();
          },
          trigger: 'change'
        }
      ];
      // 投放时间
      this.rules[`dateTime_${index}`] = [
        {
          required: true,
          validator: (rule, value, callback) => {
            const index = Number(rule.field.split('_')[1]);
            const item = this.group.popupList[index];
            if (this.group.dateTime[0] && this.group.dateTime[1]) {
              const startTime = this.group.dateTime[0].getTime();
              const endTime = this.group.dateTime[1].getTime();
              const popStartTime = item.dateTime && item.dateTime[0].getTime();
              const popEndTime = item.dateTime && item.dateTime[1].getTime();
              if (!item.dateTime) {
                callback(new Error('请选择投放时间'));
              } else if (popStartTime < startTime || popEndTime > endTime) {
                callback(new Error('弹窗投放时间需在计划时间内'));
              }
            } else {
              callback(new Error('请先选择计划时间'));
            }
            callback();
          },
          trigger: 'bulr'
        }
      ];
      // 弹出频次
      this.rules[`popupType_${index}`] = [
        {
          required: true,
          validator: (rule, value, callback) => {
            const index = Number(rule.field.split('_')[1]);
            const item = this.group.popupList[index];
            if (!item.popupType) {
              callback(new Error('请选择弹出频次'));
            }
            callback();
          },
          trigger: 'change'
        }
      ];
      // 自动关闭
      this.rules[`autoCloseFlag_${index}`] = [
        {
          required: true,
          validator: (rule, value, callback) => {
            const index = Number(rule.field.split('_')[1]);
            const item = this.group.popupList[index];
            if (item.autoCloseFlag === 1 && !item.autoCloseDelay) {
              callback(new Error('请输入自动关闭时间'));
            }
            callback();
          },
          trigger: 'blur'
        }
      ];
    },
    resetField(field) {
      this.$refs.form.validateField(field);
    },
    //  获取投放页面列表
    getPopupLinkList() {
      this.axios.get(`${config.api}/api-marketing/query-popup-link-list?requestProject=marketing`).then(res => {
        if (res.data.errorCode === 0 && res.data.result) {
          this.putonPageList = res.data.result;
        }
      });
      const params = {
        pageType: 1,
        status: 1,
        pageSize: 100,
        currentPage: 1,
        requestProject: 'gic-web'
      };
      customPageList(params).then(res => {
        if (res.errorCode == 0) {
          this.customPageList = res.result.result || [];
        }
      });
    },
    putonPageChange(pageId) {
      const page = this.putonPageList.filter(item => item.id == pageId);
      this.putonForm = { ...page[0] };
    },
    putonPageChangeComfirm() {
      this.group.popupList[this.curIndex].putonPageList[0] = { ...this.putonForm };
      this.putonPageDialog = false;
      this.resetField(`putonPageList_${this.curIndex}`);
    },
    filedAllPopDate() {
      const params = {
        beginTime: new Date(this.group.dateTime[0]).getTime(),
        endTime: new Date(this.group.dateTime[1]).getTime()
      };
      this.axios.post(`${config.api}/api-marketing/check-popup-plan-time?requestProject=marketing`, params).then(res => {
        if (res.data.errorCode !== 0) {
          this.$message({
            type: 'error',
            message: res.data.message
          });
        } else {
          this.group.popupList.map((item, index) => this.resetField(`dateTime_${index}`));
        }
      });
    },
    datePickerBulr(elIndex) {
      this.dateDelay = 1;
      this.resetField(`dateTime_${elIndex}`);
    },
    changePoptime(time, elIndex) {
      this.resetField(`dateTime_${elIndex}`);
    },
    showFileNameTip(text) {
      const span = document.createElement('span');
      span.innerHTML = text;
      document.body.appendChild(span);
      const width = span.offsetWidth;
      document.body.removeChild(span);
      return width > 278;
    },
    // 投放内容-图片 删除
    handleRemove(index, elIndex) {
      this.group.popupList[elIndex].fileList = [];
      this.group.popupList[elIndex].popupImageDetails.imageUrl = '';
    },
    // 投放内容-图片 上传之前校验
    beforeAvatarUpload(file, elIndex) {
      const isJPG = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
      const isLt500kb = file.size / 1024 < 500;
      if (!isJPG) {
        this.$message.warning('只能上传JPG/PNG/GIF格式文件!');
        return false;
      }
      if (!isLt500kb) {
        this.$message.warning('上传头像图片大小不能超过500kb!');
        return false;
      }
      return true;
    },
    successAvatarUpload(response, file, elIndex) {
      const { name, size } = file;
      const imageUrl = response.result[0].qcloudImageUrl;
      if (response.errorCode === 0) {
        this.$tips({ type: 'success', message: '上传成功' });
        this.group.popupList[elIndex].fileList = [{ name, size, imageUrl }];
        this.group.popupList[elIndex].popupImageDetails.imageUrl = imageUrl;
        this.resetField(`content_${elIndex}`);
      } else {
        this.$tips({ type: 'error', message: '上传失败' });
      }
    },
    // 投放内容-卡券 选择
    selectCard(val) {
      const pop = this.group.popupList[this.curIndex];
      const couponList = pop.popupCouponDetails.couponList;
      if (couponList.length >= 5) {
        return this.$tips({ type: 'warning', message: '最多不超过5张卡券' });
      }
      if (val) {
        const hasChoose = couponList.some(coupon => coupon.coupCardId === val.coupCardId);
        if (!hasChoose) {
          couponList.push({ ...val });
          this.showCardDialog = false;
        } else {
          this.$tips({ type: 'warning', message: '卡券已存在' });
        }
      } else {
        this.showCardDialog = false;
      }
    },
    showDialog(elIndex) {
      this.curIndex = elIndex;
      this.showCardDialog = true;
    },
    deleteCoupon(cardIndex, elIndex) {
      let item = this.group.popupList[elIndex].popupCouponDetails;
      item.couponList.splice(cardIndex, 1);
    },
    closeTypeChange(label, elIndex) {
      this.group.popupList[elIndex].fileList = [];
      this.group.popupList[elIndex].popupImageDetails = { imageUrl: '', link: {} };
      this.group.popupList[elIndex].popupCouponDetails = { couponList: [], styleType: 1 };
    },
    // 定向人群筛选
    handleDataTransferred(data, elIndex) {
      let item = this.group.popupList[elIndex];
      item.popupMemberGroupList = [...data];
      this.resetField(`popupMemberGroupList_${elIndex}`);
    },
    handleDataLeft(selectedData, selectionToRemove, elIndex) {
      let item = this.group.popupList[elIndex];
      item.popupMemberGroupList = [...selectedData];
      this.resetField(`popupMemberGroupList_${elIndex}`);
    },
    setImgLink(pop) {
      if (pop.activeStatus != 2) {
        pop.linkToolsVisible = true;
      }
    },
    // 链接小工具 选择
    linkSelect(val, elIndex) {
      this.group.popupList[elIndex].popupImageDetails.link = val;
      this.group.popupList[elIndex].linkToolsVisible = false;
    },
    // 链接小工具 选择
    deleteImgLink(pop) {
      if (pop.activeStatus != 2) {
        pop.popupImageDetails.link = {};
      }
      // this.group.popupList[elIndex].popupImageDetails.link = {};
    },
    showPutonPage(pop, elIndex) {
      if (pop.activeStatus != 2) {
        this.putonPageDialog = true;
        this.curIndex = elIndex;
        this.putonForm = this.group.popupList[elIndex].putonPageList[0] || { id: '', type: 1, name: '', content: '', customPageId: '', customPageName: '' };
      }
    },
    // 投放页面 删除
    deletePage(pop, pageId) {
      if (pop.activeStatus != 2) {
        pop.putonPageList = pop.putonPageList.filter(item => item.id != pageId);
      }
    },
    checkGroupDate() {
      if (this.dateDelay === 1) {
        this.dateDelay = 0;
        if (!this.group.dateTime[0]) {
          this.$message.error('请先选择计划时间！');
          setTimeout(function() {
            this.dateDelay = 1;
          }, 500);
        }
      }
    },
    // 级别更改
    sortChange() {
      this.popSort = { 1: false, 2: false, 3: false, 4: false, 5: false };
      this.group.popupList.map(item => {
        this.popSort[item.sortNum] = true;
      });
      // console.log(this.popSort);
    },
    // 删除弹窗
    detelePop(elIndex) {
      this.$confirm('此操作将删除该弹窗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.group.popupList.splice(elIndex, 1);
        this.sortChange();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.line {
  box-sizing: content-box;
  padding: 0 24px;
  margin-left: -24px;
  width: 100%;
  height: 1px;
  background: #e4e7ed;
}
.addBtn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 40px auto 0;
  width: 230px;
  height: 100px;
  color: #909399;
  background: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
  .iconfont {
    margin-bottom: 16px;
    font-size: 15px;
  }
  p {
    color: #909399;
    line-height: 20px;
  }
  &:hover {
    background: #f0f5ff;
    .icon-jia {
      color: #1890ff;
    }
  }
}
.popBox {
  display: flex;
  justify-content: space-between;
  width: 100%;
  .form_detail {
    .upload_box {
      width: 501px;
      min-height: 120px;
      padding: 20px 0 20px 19px;
      box-sizing: border-box;
      background: #f5f7fa;
      .pop_img_link {
        margin-top: 18px;
        /deep/ .el-form-item__label {
          text-align: left;
          line-height: 20px;
          // padding-right: 0 !important;
          // width: 70px !important;
        }
        /deep/ .el-form-item__content {
          line-height: 20px;
          // margin-left: 70px !important;
        }
      }
    }
    .block_radio {
      padding-top: 5px;
      margin-bottom: -18px;
      .el-radio {
        display: block;
        margin: 0 0 18px;
        line-height: 22px;
      }
    }
  }
}
.pop_dm_upload_file {
  /deep/ .file-item {
    width: 363px;
    height: 96px;
    border: 1px solid #c0ccda;
    background: #ffffff;
    .file-item-content {
      height: 100%;
    }
    .file-list-item {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height: 100%;
      .info {
        margin-left: 15px;
        max-width: 278px;
        word-break: break-all;
        font-size: 14px;
        color: #606266;
        line-height: 1;
        cursor: default;
        .file-name {
          display: inline-block;
          width: 278px;
          max-width: 278px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .file-size {
          margin-left: 4px;
          color: #909399;
        }
      }
    }
  }
}
.card-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 250px;
  height: 32px;
  margin-top: 10px;
  .info {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 220px;
    height: 100%;
    padding-left: 10px;
    box-sizing: border-box;
    font-size: 14px;
    color: #303133;
    background: #ffffff;
    border-radius: 2px;
    border: 1px dashed #c4c6cf;
    .type {
      display: inline-block;
      height: 22px;
      padding: 0 8px;
      margin-right: 10px;
      background: #f0f5ff;
      border-radius: 2px;
      border: 1px solid #adc6ff;
      font-size: 12px;
      color: #2f54eb;
      line-height: 22px;
    }
  }
  .icon-shanchu {
    font-size: 22px;
    cursor: pointer;
    &:hover {
      color: #ff555e;
    }
  }
}
.first-card-item {
  margin-top: 0;
}
.group-set-transfer {
  padding: 0;
  height: 619px;
  width: 1160px;
  div {
    flex: 1;
  }
}
/deep/ .is-error .group-set-transfer .el-input__inner {
  border-color: #dcdfe6;
}
.sort {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  box-sizing: border-box;
  width: 100%;
  margin-bottom: 40px;
  .tip {
    margin-left: 10px;
    color: #909399;
  }
  .sort_line {
    display: block;
    margin: 0 10px;
    height: 1px;
    min-width: 53px;
    background: #e4e7ed;
  }
  & :nth-child(3) {
    flex: 1;
    margin-right: 12px;
  }
}
.el-popper {
  min-width: 75px;
  width: 75px;
  .el-radio-group {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    width: 88px;
    height: 184px;
    padding: 9px 0;
    .el-radio {
      display: block;
      margin: 0;
      line-height: 34px;
      height: 34px;
      /deep/ .el-radio__input {
        display: none;
      }
    }
    .is-disabled .el-radio__label i {
      opacity: 0.6;
    }
  }
}
.preview {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 262px;
  height: 530px;
  margin: 0px auto 20px;
  background-image: url('./assets/img/popPreviewBg.png');
  background-repeat: no-repeat;
  background-size: contain;

  .container-content {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    padding-top: 115px;
    img {
      width: 70%;
    }
  }
}
.select-page {
  width: 45%;
}
.bottomBtn {
  position: fixed;
  bottom: 0;
  right: 0;
  display: flex;
  z-index: 99;
  justify-content: center;
  align-items: center;
  height: 60px;
  width: 100%;
  background: #ffffff;
}
.delete_btn {
  background: #f0f5ff;
  color: #909399;
  border: 0;
}
.delete_btn.is-disabled:hover {
  background: #f0f5ff;
  color: #909399;
  border: 0;
}
.delete_btn:not(.is-disabled):hover {
  background: #fff1f0;
  color: #ff555e;
}
</style>
<style lang="scss">
.pop_dm_upload_file .file-item-content .file-success,
.pop_dm_upload_file .file-item-content .file-close {
  align-self: flex-start;
  margin-top: 10px;
}
.pop_dm_upload_file .upload-file .el-upload-list {
  display: none;
}
.pop_sort_popover {
  min-width: 88px !important;
  width: 88px !important;
  padding: 0;
}
.pop_sort_popover .el-radio {
  width: 100%;
}
.pop_sort_popover .el-radio .el-radio__label {
  display: block;
  width: 100%;
  height: 34px;
  padding: 0;
  text-align: center;
}
.pop_sort_popover .is-checked .el-radio__label {
  color: #1890ff !important;
  background: #f5f7fa;
}
.pop_sort_popover .is-checked .el-radio__label i {
  opacity: 1 !important;
}
.pop-form .el-radio-group .is-checked .el-radio__label {
  color: #606266;
}
.pop-form .el-form .is-success .el-input__inner {
  border: 1px solid #dcdfe6;
}
</style>
