<template>
  <section class="dm-wrap" v-loading="loading">
    <div class="pb22 clearfix">
      <el-date-picker class="w400 ml10" v-model="dateTime" type="daterange" range-separator="至" start-placeholder="创建开始时间" end-placeholder="创建结束时间" @change="refresh"></el-date-picker>
      <el-input v-model="listParams.searchName" class="w200" placeholder="输入计划名称/创建人" clearable @change="search"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-checkbox class="vertical-middle" v-if="$store.state.marketing.isShowSelf" v-model="listParams.showSelfFlag" :true-label="1" :false-label="0" label="仅看本人" border @change="search" />
      <div class="fr">
        <el-button @click="$router.push('/scan/history-list')">查看历史计划</el-button>
        <el-button type="primary" @click="$router.push('/scan/add')">新建计划</el-button>
      </div>
    </div>
    <div class="imitation-table drag-table" style="width:100%;">
      <el-row class="thead">
        <el-col :span="1"></el-col>
        <el-col :span="2">优先级</el-col>
        <el-col :span="5">封面</el-col>
        <el-col :span="5">创建时间</el-col>
        <el-col :span="4">启用状态</el-col>
        <el-col :span="5">操作</el-col>
      </el-row>
      <!-- <div> -->
      <!-- v-model="tableList" -->
      <draggable tag="div" class="tbody" handle=".icon-paixu1" v-bind="dragOptions" @end="onDragEnd">
        <transition-group type="transition">
          <div class="td" v-for="(item, key) in tableList" :key="item.ecmPlanId" @mouseover="hoverIdx = item.ecmPlanId" @mouseout="hoverIdx = -1" :class="{ active: hoverIdx === item.ecmPlanId }">
            <el-row>
              <el-col :span="1"><i class="iconfont icon-paixu1 slideIcon place-font-color cursor fz12"></i></el-col>
              <el-col :span="2">{{ key + 1 }}</el-col>
              <el-col :span="5">
                <fill-image :url="item.imageUrl" width="40" height="40" shape="square" />
              </el-col>
              <el-col :span="5">
                <p class="cell-time">
                  {{ formatDateTimeByType(item.createTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}<br />
                  <span>{{ formatDateTimeByType(item.createTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</span>
                </p>
              </el-col>
              <el-col :span="4">
                <el-switch @change="changeStatus(item)" :value="Boolean(item.status)" />
              </el-col>
              <el-col :span="5">
                <template v-if="item.canEdit !== false">
                  <el-button type="text" @click="toRecord(scope.row)">记录</el-button>
                  <el-button type="text" v-if="item.effectType == 0 || item.effectType == 1" @click="editData(scope.row)">编辑</el-button>
                  <el-button type="text" v-if="item.effectType == 2" @click="$router.push(`/scan/info/${item.ecmPlanId}`)">详情</el-button>
                </template>
                <dm-delete v-if="item.effectType !== 2 && item.onlineStatus === 1 && item.canEdit !== false" @confirm="offlineEcmPlan(scope.row)" tips="是否下线该计划?">
                  <el-button type="text">下线</el-button>
                </dm-delete>
                <dm-delete v-if="item.putonStatus !== 2 && item.canEdit !== false" @confirm="delData(scope.row)" tips="是否删除该计划?">
                  <el-button type="text">删除</el-button>
                </dm-delete>
              </el-col>
            </el-row>
          </div>
        </transition-group>
      </draggable>
      <div v-if="tableList.length === 0" class="el-table__empty-block" style="width: 100%;"><span class="el-table__empty-text">暂无数据</span></div>
      <!-- </div> -->
    </div>
    <!-- <el-table tooltipEffect="light" :data="tableList" style="width: 100%" element-loading-text="拼命加载中">
      <el-table-column label="优先级" type="index" width="80"></el-table-column>
      <el-table-column v-for="(v, i) in tableHeader" :fixed="v.fixed" :show-overflow-tooltip="v.tooltip" :width="v.width" :min-width="v.minWidth" :align="v.align" :key="i" :prop="v.prop" :label="v.label" :formatter="v.formatter">
        <template slot-scope="scope">
          <span v-if="v.formatter" v-html="v.formatter(scope.row)"></span>
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100" align="left" prop="creatorName" label="创建人" v-if="$store.state.marketing.openFlag"></el-table-column>
      <el-table-column label="操作" align="left" width="220" fixed="right">
        <template slot-scope="scope">
          <template v-if="scope.row.canEdit !== false">
            <el-button type="text" @click="toRecord(scope.row)">记录</el-button>
            <el-button type="text" v-if="scope.row.effectType == 0 || scope.row.effectType == 1" @click="editData(scope.row)">编辑</el-button>
            <el-button type="text" v-if="scope.row.effectType == 2" @click="$router.push(`/scan/info/${scope.row.ecmPlanId}`)">详情</el-button>
          </template>
          <dm-delete v-if="scope.row.effectType !== 2 && scope.row.onlineStatus === 1 && scope.row.canEdit !== false" @confirm="offlineEcmPlan(scope.row)" tips="是否下线该计划?">
            <el-button type="text">下线</el-button>
          </dm-delete>
          <dm-delete v-if="scope.row.putonStatus !== 2 && scope.row.canEdit !== false" @confirm="delData(scope.row)" tips="是否删除该计划?">
            <el-button type="text">删除</el-button>
          </dm-delete>
        </template>
      </el-table-column>
    </el-table> -->
    <!-- 不需要分页，只取前20 -->
    <!-- <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 draggable from 'vuedraggable';
import activitySelect from '@/components/activity-select/index.vue';
import { formatDateTimeByType } from '@/utils/index.js';
import { loadEcmList, deleteEcm, offlineEcmPlan } from '@/service/api/ecmApi.js';
export default {
  name: 'scan-list',
  data() {
    return {
      dateTime: [],
      listParams: {
        onlineStatus: '', // onlineStatus字段：不填为有效记录 2：历史记录
        searchName: '',
        currentPage: 1,
        pageSize: 20,
        showSelfFlag: '',
        effectAction: 'scanning' // 新增字段：effectAction 当effectAction=scanning时 按level_sort倒序
      },
      total: 0,
      loading: false,
      // tableHeader: [
      //   { label: '计划名称', prop: 'ecmPlanName', minWidth: '160', align: 'left' },
      //   {
      //     label: '创建时间',
      //     prop: 'createTime',
      //     minWidth: '120',
      //     align: 'left',
      //     formatter(row) {
      //       const date = formatDateTimeByType(row.createTime, 'yyyy-MM-dd-HH-mm-ss', true);
      //       return date.y + '\n' + date.h;
      //     }
      //   },
      //   {
      //     label: '状态',
      //     prop: 'onlineStatus',
      //     width: '160',
      //     align: 'left',
      //     formatter(row) {
      //       let result = '--';
      //       switch (row.onlineStatus) {
      //         case 0:
      //           result = '<span class="dm-status--primary">待上线</span>';
      //           break;
      //         case 1:
      //           result = '<span class="dm-status--success">已上线</span>';
      //           break;
      //         case 2:
      //           result = '<span class="dm-status--info">已下线</span>';
      //           break;
      //       }
      //       return result;
      //     }
      //   },
      //   {
      //     label: '执行时间',
      //     prop: 'createTime',
      //     minWidth: '120',
      //     align: 'left',
      //     formatter(row) {
      //       const date = formatDateTimeByType(row.createTime, 'yyyy-MM-dd-HH-mm-ss', true);
      //       return date.y + '\n' + date.h;
      //     }
      //   },
      //   { label: '合计营销次数', prop: 'timesForPeople', width: '160', align: 'left' }
      // ],
      tableList: []
    };
  },
  components: {
    activitySelect,
    draggable
  },
  created() {
    this.getTableList();
    this.$store.commit('aside_handler', true);
    this.$store.commit('mutations_breadcrumb', [{ name: '扫码营销', path: '' }, { name: '营销计划', path: '/scan' }]); // eslint-disable-line
  },
  methods: {
    formatDateTimeByType,
    search() {
      this.listParams.currentPage = 1;
      this.getTableList();
    },
    // handleSizeChange(val) {
    //   this.listParams.pageSize = val;
    //   this.getTableList();
    // },
    // handleCurrentChange(val) {
    //   this.listParams.currentPage = val;
    //   this.getTableList();
    // },
    async getTableList() {
      this.loading = true;
      if (this.dateTime) {
        this.listParams.createBeginTime = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd');
        this.listParams.createEndTime = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd');
      } else {
        this.listParams.createBeginTime = '';
        this.listParams.createEndTime = '';
      }
      const params = { ...this.listParams };
      if (params.effectType === '') {
        params.effectType = -1; // 全部时效的默认值是-1
      }
      let res = await loadEcmList(params);
      console.log(res);
      this.tableList = res.result.result || [];
      this.total = res.result.totalCount;
      this.loading = false;
    },
    //编辑
    editData(row) {
      this.$router.push('/scan/edit/' + row.ecmPlanId);
    },
    // 记录
    toRecord(row) {
      const prefix = row.effectType == 1 ? 'batchlist' : row.effectType == 2 ? 'oncelist' : 'currentlist';
      this.$router.push({ path: `/ecm/${prefix}/${row.ecmPlanId}`, query: { name: row.ecmPlanName } });
    },
    // 删除
    async delData(row) {
      try {
        let res = await deleteEcm({ ecmPlanId: row.ecmPlanId });
        if (res.errorCode === 0) {
          this.$tips({ type: 'success', message: '删除成功!' });
          if (this.tableList.length === 1 && this.listParams.currentPage !== 1) {
            this.listParams.currentPage--;
          }
          this.getTableList();
        } else {
          this.$tips({ type: 'error', message: res.message || '删除失败!' });
        }
      } catch (err) {
        this.$tips({ type: 'error', message: '删除失败!' });
      }
    },
    // 下线
    async offlineEcmPlan(row) {
      try {
        let res = await offlineEcmPlan({ ecmPlanId: row.ecmPlanId });
        if (res.errorCode === 0) {
          this.$tips({ type: 'success', message: '下线成功!' });
          this.getTableList();
        } else {
          this.$tips({ type: 'error', message: res.message || '下线失败!' });
        }
      } catch (err) {
        this.$tips({ type: 'error', message: '下线失败!' });
      }
    },
    // 拖拽结束
    onDragEnd(data) {
      // 提交
      // this.loading = true;
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 300,
        ghostClass: 'ghost'
      };
    }
  }
};
</script>
