<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="search"></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')" :disabled="total >= 10">新建计划（{{ total }}/10）</el-button>
      </div>
    </div>
    <el-alert class="mb10 inline-block" title="" type="warning" :closable="false">
      <span slot="title"><i class="el-icon-info mr10"></i>扫码营销计划按优先级由高到低匹配执行，越上方的优先级越高</span>
    </el-alert>
    <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="2">计划名称</el-col>
        <el-col :span="4">创建时间</el-col>
        <el-col :span="2">状态</el-col>
        <el-col :span="4">执行时间</el-col>
        <el-col :span="3">合计营销次数</el-col>
        <el-col :span="2" v-if="$store.state.marketing.openFlag">创建人</el-col>
        <el-col :span="4">操作</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="2">{{ item.ecmPlanName }}</el-col>
              <el-col :span="4">
                <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="2">
                <div v-if="item.nowStatus == 0" class="dm-status--warning">待执行</div>
                <div v-else class="dm-status--success">执行中</div>
              </el-col>
              <el-col :span="4">
                <p class="cell-time">
                  {{ formatDateTimeByType(item.beginDate, 'yyyy-MM-dd-HH-mm-ss') }} ~<br />
                  {{ formatDateTimeByType(item.endDate, 'yyyy-MM-dd-HH-mm-ss') }}
                </p>
              </el-col>
              <el-col :span="3">{{ item.timesForPeople || '--' }}</el-col>
              <el-col :span="2" v-if="$store.state.marketing.openFlag">{{ item.creatorName || 0 }}</el-col>
              <el-col :span="4">
                <el-button type="text" @click="toRecord(item)">记录</el-button>
                <template v-if="item.canEdit !== false">
                  <el-button type="text" v-if="item.effectType == 0 || item.effectType == 1" @click="editData(item)">编辑</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(item)" tips="是否下线该计划?">
                  <el-button type="text">下线</el-button>
                </dm-delete>
                <dm-delete v-if="item.putonStatus !== 2 && item.canEdit !== false" @confirm="delData(item)" 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>
    <!-- 不需要分页，只取前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 { formatDateTimeByType, deepClone } from '@/utils/index.js';
import { loadEcmList, deleteEcm, offlineEcmPlan, changeEcmPlanSort } from '@/service/api/ecmApi.js';
export default {
  name: 'scan-list',
  data() {
    return {
      dateTime: [],
      listParams: {
        beginTime: '',
        endTime: '',
        onlineStatus: '', // onlineStatus字段：不填为有效记录 2：历史记录
        searchName: '',
        currentPage: 1,
        pageSize: 20,
        showSelfFlag: '',
        effectAction: 'scanning' // 新增字段：effectAction 当effectAction=scanning时 按level_sort倒序
      },
      hoverIdx: -1,
      total: 0,
      loading: false,
      tableList: []
    };
  },
  components: {
    draggable
  },
  created() {
    this.getTableList();
    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() {
      if (this.dateTime) {
        this.listParams.beginTime = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd');
        this.listParams.endTime = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd');
      } else {
        this.listParams.beginTime = '';
        this.listParams.endTime = '';
      }
      const params = { ...this.listParams };
      if (params.effectType === '') {
        params.effectType = -1; // 全部时效的默认值是-1
      }
      this.loading = true;
      try {
        let res = await loadEcmList(params);
        const tableList = res.result.result || [];
        this.tableList = tableList.map(v => {
          v.nowStatus = new Date() > new Date(v.beginDate);
          return v;
        });
        this.total = res.result.totalCount;
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },
    //编辑
    editData(row) {
      this.$router.push('/scan/edit/' + row.ecmPlanId);
    },
    // 记录
    toRecord(row) {
      this.$router.push({ path: `/scan/currentlist/${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: '下线失败!' });
      }
    },
    sortByDrag(arr, index, tindex) {
      // index是当前元素下标，tindex是拖动到的位置下标。
      if (index > tindex) {
        arr.splice(tindex, 0, arr[index]);
        arr.splice(index + 1, 1);
      } else {
        arr.splice(tindex + 1, 0, arr[index]);
        arr.splice(index, 1);
      }
      return arr;
    },
    // 拖拽结束
    onDragEnd(data) {
      let { newIndex, oldIndex } = data;
      const ecmPlanId = this.tableList[oldIndex].ecmPlanId;
      const tableList = this.sortByDrag(deepClone(this.tableList), oldIndex, newIndex); // 目标table
      // preEcmPlanId  拖动后位置前的ecmId
      // afterEcmPlanId 拖动后位置后的ecmId
      // by后端：如果拖到最顶端，preEcmPlanId  不传。 如果拖到最底端  afterEcmPlanId 不传
      const params = {
        ecmPlanId // 要拖动的ecmId
      };
      if (newIndex == 0) {
        // 第一位
        params.afterEcmPlanId = tableList[newIndex + 1].ecmPlanId;
      } else if (newIndex == this.tableList.length - 1) {
        // 最后一位
        params.preEcmPlanId = tableList[newIndex - 1].ecmPlanId;
      } else {
        params.afterEcmPlanId = tableList[newIndex + 1].ecmPlanId;
        params.preEcmPlanId = tableList[newIndex - 1].ecmPlanId;
      }

      // 提交
      this.loading = true;
      changeEcmPlanSort(params)
        .then(res => {
          this.loading = false;
          this.getTableList();
          this.$message({ message: res.message || '操作成功', type: 'success' });
        })
        .catch(err => {
          this.loading = false;
        });
      // 提交
      // this.loading = true;
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 300,
        ghostClass: 'ghost'
      };
    }
  }
};
</script>
