<template>
  <section class="dm-wrap" v-loading="loading">
    <div class="clearfix pb22">
      <el-input v-model="listParams.keyword" style="width:239px;" placeholder="请输入内容" clearable @change="refresh"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-date-picker style="width: 327px" v-model="listParams.dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="refresh"></el-date-picker>
      <el-select style="width: 135px" clearable v-model="listParams.activeStatus" placeholder="全部状态" @change="refresh">
        <el-option v-for="item in activeStatusOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-select style="width: 135px" clearable v-model="listParams.putonType" placeholder="全部内容" @change="refresh">
        <el-option v-for="item in putonTypeOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-checkbox v-model="listParams.onlySelf" :true-label="1" :false-label="0" @change="refresh">仅看本人</el-checkbox>
      <div class="fr">
        <el-button type="primary" @click="goForm({}, 'add')">新建计划</el-button>
      </div>
    </div>
    <el-table tooltipEffect="light" style="width: 100%" :class="{ emptyTable: Array.isArray(tableList) && tableList.length > 0 }">
      <el-table-column align="left" label="弹窗内容"></el-table-column>
      <el-table-column align="left" label="定向人群" width="250"></el-table-column>
      <el-table-column align="left" label="投放页面"></el-table-column>
      <el-table-column align="left" label="投放时间"></el-table-column>
      <el-table-column align="left" label="状态"></el-table-column>
      <el-table-column align="left" label="操作" width="170"></el-table-column>
    </el-table>
    <div class="group-table" v-for="(group, i) in tableList" :key="i">
      <div class="group-title">
        <p class="title">
          计划名称：{{ group.name }}<i>{{ formatDateTimeByType(group.beginTime, 'yyyy-MM-dd') + '至' + formatDateTimeByType(group.endTime, 'yyyy-MM-dd') }}</i>
        </p>
        <div class="btn-group">
          <el-button type="text" v-if="5 > group.popupList.length" @click="goForm(group, 'edit')">添加弹窗</el-button>
          <dm-delete v-if="group.popupList.every(el => el.activeStatus != 2)" tips="是否删除此弹窗计划？" @confirm="delGroup(group)">
            <el-button type="text">删除</el-button>
          </dm-delete>
        </div>
      </div>
      <el-table tooltipEffect="light" style="width: 100%" :data="group.popupList">
        <el-table-column align="left" label="弹窗内容">
          <template slot-scope="scope">
            <el-popover placement="top" width="246" trigger="click" v-if="scope.row.putonType == 1">
              <el-image fill="contain" :src="scope.row.popupImageDetails ? scope.row.popupImageDetails.imageUrl : ''"></el-image>
              <template slot="reference">
                <div class="demo-image__preview">
                  <i class="iconfont icon-yulan"></i>
                  <el-image fit="cover" :src="scope.row.popupImageDetails ? scope.row.popupImageDetails.imageUrl : ''"></el-image>
                </div>
              </template>
            </el-popover>
            <img style="width: 40px;height:40px" v-else src="../../assets/img/coupon.png" alt="" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="定向人群" width="250" :show-overflow-tooltip="true">
          <template slot-scope="scope">{{ scope.row.popupMemberGroupList | memberGroup }} </template>
        </el-table-column>
        <el-table-column align="left" label="投放页面" :show-overflow-tooltip="true">
          <template slot-scope="scope">{{ scope.row.putonPageList | pageList }} </template>
        </el-table-column>
        <el-table-column align="left" label="投放时间" prop="createTime">
          <template slot-scope="scope">
            <div>{{ formatDateTimeByType(scope.row.beginTime, 'yyyy-MM-dd HH:mm') }} 至</div>
            <div>{{ formatDateTimeByType(scope.row.endTime, 'yyyy-MM-dd HH:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="状态" prop="status">
          <template slot-scope="scope">
            <span><i class="dot" :style="'background:' + (scope.row.activeStatus === 1 ? '#FAAD14' : scope.row.activeStatus === 2 ? '#1890FF' : '#c0c4cc') + ';'"></i> {{ scope.row.activeStatus | statusFilter }}</span>
            <el-tooltip v-if="scope.row.manualEndFlag" slot="label" open-delay="200" :content="'手动结束时间：' + formatDateTimeByType(scope.row.manualEndTime, 'yyyy-MM-dd HH:mm')" placement="top"> <i class="iconfont icon-tishi" style="color:#C0C4CC;margin-left:2px;font-size:14px;"></i></el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="170">
          <template slot-scope="scope">
            <el-button v-if="scope.row.activeStatus === 2 || scope.row.activeStatus === 3" type="text" @click="goForm(group, 'edit')">查看</el-button>
            <dm-delete v-if="scope.row.activeStatus === 2" @confirm="stopPop(scope.row)" tips="是否停止该条数据?">
              <el-button type="text">停止</el-button>
            </dm-delete>
            <el-button v-if="scope.row.activeStatus === 1" type="text" @click="goForm(group, 'edit')">编辑</el-button>
            <dm-delete v-if="scope.row.activeStatus === 1 || scope.row.activeStatus === 3" @confirm="removePop(scope.row)" tips="是否删除此弹窗?">
              <el-button type="text">删除</el-button>
            </dm-delete>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <dm-pagination v-show="tableList.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
  </section>
</template>

<script>
import { popPlanList, removePopup, stopPopup, removePopupPlan } from '@/service/api/popApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import timeCounts from '@/components/timeCount/index.vue';
import tableMethods from '@/mixins/tableMethods.js';
const activeStatusOpt = [
  { value: 1, label: '未开始' },
  { value: 2, label: '进行中' },
  { value: 3, label: '已结束' }
];
const putonTypeOpt = [
  { value: 1, label: '图片' },
  { value: 2, label: '卡券' }
];
export default {
  name: 'pop-list',
  components: {
    timeCounts
  },
  mixins: [tableMethods],
  data() {
    return {
      activeStatusOpt: activeStatusOpt,
      putonTypeOpt: putonTypeOpt,
      loading: false,
      tableList: [],
      listParams: {
        dateTime: ['', ''],
        activeStatus: '', // 弹窗活动状态（1：未开始，2：进行中，3：已结束）
        putonType: '', // 投放类型（1：图片，2：卡券）
        onlySelf: 0, // 仅看本人（0：否，1：是）
        currentPage: 1,
        pageSize: 20
      },
      total: 0
    };
  },
  filters: {
    statusFilter(status) {
      switch (status) {
        case 1:
          return '未开始';
          break;
        case 2:
          return '进行中';
          break;
        case 3:
          return '已结束';
          break;
      }
    },
    memberGroup(val) {
      let member = [];
      val.map(item => {
        member.push(item.groupName);
      });
      return member.join('/');
    },
    pageList(val) {
      let page = [];
      val.map(item => {
        page.push(item.name);
      });
      return page.join('/');
    }
  },
  created() {
    this.$store.commit('mutations_breadcrumb', [
      { name: '营销管理', path: '' },
      { name: '弹窗推广', path: '' },
      { name: '计划列表', path: '' }
    ]);
    this.getTableList();
  },
  methods: {
    formatDateTimeByType,
    async getTableList() {
      let params = { ...this.listParams };
      const [beginTime, endTime] = params.dateTime || [];
      if (beginTime && endTime) {
        params.beginTime = new Date(beginTime).getTime();
        params.endTime = new Date(endTime).getTime();
      }
      delete params.dateTime;
      console.log(params);
      const res = await popPlanList(params);
      if (res.errorCode === 0 && res.result) {
        this.tableList = res.result.result;
      }
    },
    goForm(group, type) {
      if (type === 'add') {
        this.$router.push(`/popup/add`);
      } else {
        this.$router.push(`/popup/edit?id=${group.id}`);
      }
    },
    delGroup(group) {
      removePopupPlan({ popupPlanId: group.id }).then(res => {
        if (res.errorCode == 0) {
          this.$message.success('删除成功');
          this.getTableList();
        }
      });
    },
    removePop(pop) {
      removePopup({ popupId: pop.id }).then(res => {
        this.$message.success('删除成功');
        this.getTableList();
      });
    },
    stopPop(pop) {
      stopPopup({ popupId: pop.id }).then(res => {
        this.$message.success('弹窗计划已停止');
        this.getTableList();
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.emptyTable /deep/.el-table__empty-block,
.group-table /deep/.el-table__header-wrapper {
  display: none;
}
/deep/.el-image {
  .el-image-viewer__actions {
    display: none;
  }
  .el-image-viewer__close {
    top: 10px;
    right: 392px;
    .el-icon-circle-close {
      font-size: 33px;
      color: rgba($color: #ffffff, $alpha: 0.8);
    }
  }
}
.demo-image__preview {
  position: relative;
  width: 40px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
  .icon-yulan {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
    padding: 10px 0 0 11px;
    box-sizing: border-box;
    color: #ffffff;
    font-size: 18px;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 4px;
    cursor: pointer;
  }
  &:hover {
    .icon-yulan {
      display: block;
    }
  }
}
.group-table {
  .group-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
    height: 34px;
    background: #f5f7fa;
    .title {
      padding-left: 16px;
      font-size: 14px;
      font-weight: bold;
      color: #606266;
      line-height: 20px;
      i {
        margin-left: 39px;
        font-size: 12px;
        font-weight: 400;
        font-style: unset;
        color: #909399;
        line-height: 17px;
      }
    }
    .btn-group {
      padding-left: 10px;
      width: 170px;
      box-sizing: border-box;
    }
  }
  .dot {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 100%;
    background: #c0c4cc;
  }
}
// /deep/.el-popover,
// /deep/.el-popper {
//   cursor: default !important;
// }
</style>
