<template>
  <section class="dm-wrap" v-loading="loading">
    <div class="pb22 clearfix">
      <el-select class="dm-select" clearable="" v-model="listParams.effectType" placeholder="选择时效" @change="search">
        <el-option v-for="(v, i) in effectTypeOption" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-select class="dm-select" clearable v-model="listParams.marketingType" placeholder="选择营销方式" @change="search">
        <el-option v-for="(v, i) in showMarketingTypeOptions" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <dm-activity-select class="vertical-middle w150 mr5" onlySelect width="150" :actId.sync="listParams.marketingActivityId" @actUpdate="search"></dm-activity-select>
      <el-select class="dm-select" clearable v-model="listParams.onlineStatus" placeholder="选择状态" @change="search">
        <el-option v-for="(v, i) in onlineOptions" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <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" />
      <el-button class="fr" type="primary" @click="$router.push('/ecm/add')">新建计划</el-button>
      <el-tooltip class="fr" content="只记录删除计划或编辑“进行中”计划的操作日志" placement="top" open-delay="200">
        <el-button style="margin-right:10px" @click="$router.push('/ecm/log')">操作日志</el-button>
      </el-tooltip>
    </div>
    <el-table tooltipEffect="light" :data="tableList" style="width: 100%" element-loading-text="拼命加载中">
      <el-table-column align="left" fixed="left" :min-width="200" show-overflow-tooltip label="计划名称">
        <template slot-scope="scope">
          <el-button v-if="xsxsFlag && isOpenFlag(scope.row.analyseJson)" style="vertical-align: middle;text-overflow: ellipsis;overflow: hidden;white-space: nowrap;width: 100%;text-align:left" type="text" @click="toTouch(scope.row)">
            <img style="vertical-align: middle;" src="../../assets/img/data.png" />
            <span style="vertical-align: middle;">{{ scope.row.ecmPlanName }}</span>
          </el-button>
          <span v-else>{{ scope.row.ecmPlanName }}</span>
        </template>
      </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="header" slot-scope="scope">
          <span>
            <span>{{ v.label }}</span>
            <el-tooltip v-if="v.prop == 'timesForPeople'" content="刷新获取最新营销人次统计" placement="top" :open-delay="200">
              <i class="el-icon-refresh" @click="loadEcmList"></i>
            </el-tooltip>
          </span>
        </template>
        <template slot-scope="scope">
          <span class="vertical-middle" 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="160" fixed="right">
        <template slot-scope="scope">
          <template v-if="scope.row.canEdit !== false">
            <el-button type="text" v-if="(scope.row.effectType == 0 || scope.row.effectType == 1) && scope.row.onlineStatus != 2" @click="editData(scope.row)">编辑</el-button>
            <el-button type="text" v-else-if="scope.row.effectType == 2 || scope.row.onlineStatus == 2" @click="$router.push(`/ecm/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>
          <!-- <el-button type="text" @click="toRecord(scope.row)">记录</el-button>
          <el-button type="text" @click="toTouch(scope.row)" v-if="xsxsFlag && isOpenFlag(scope.row.analyseJson)">触达效果</el-button> -->
          <el-dropdown style="margin-left:8px" trigger="click" @command="onCommand($event, scope.row)">
            <el-button type="text">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="1">记录</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.effectType !== 2 && scope.row.onlineStatus === 1 && scope.row.canEdit !== false" @confirm="offlineEcmPlan(scope.row)" :command="2">下线</el-dropdown-item>
              <el-dropdown-item v-if="xsxsFlag && isOpenFlag(scope.row.analyseJson)" :command="3">触达效果</el-dropdown-item>
              <!-- <el-dropdown-item :command="4">复制新建</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <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 activitySelect from '@/components/activity-select/index.vue';
import { loadEcmList, deleteEcm, offlineEcmPlan, getUseStoredFalg, getXsxsFalg } from '@/service/api/ecmApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import { ecmTypes } from '@/config/ecm.js';
const marketingTypeOptions = [{ value: '', label: '所有发送类型', visible: true }, ...JSON.parse(JSON.stringify(ecmTypes))]; // eslint-disable-line
export default {
  name: 'ecm',
  data() {
    return {
      effectTypeOption: [
        { value: '', label: '所有时效' },
        { value: 0, label: '触点' },
        { value: 1, label: '重复' },
        { value: 2, label: '单次' }
      ], // eslint-disable-line
      onlineOptions: [
        { value: '', label: '所有状态' },
        { value: 0, label: '未开始' },
        { value: 1, label: '进行中(待执行)' },
        { value: 2, label: '已结束(执行完毕)' }
      ], // eslint-disable-line
      marketingTypeOptions,
      listParams: {
        effectType: '', // 全部失效的默认值是-1,提交时判断''改为-1
        marketingType: '',
        marketingActivityId: '',
        onlineStatus: '',
        searchName: '',
        currentPage: 1,
        pageSize: 20,
        showSelfFlag: ''
      },
      xsxsFlag: 0, // 销售线索开关 1 开 0 关
      total: 0,
      loading: false,
      tableHeader: [
        {
          label: '时效',
          prop: 'effectType',
          minWidth: '160',
          align: 'left',
          formatter(row) {
            if (row.effectType == 0) {
              return '触点';
            } else if (row.effectType == 1) {
              /** '重复执行频率(1:天; 2:周 3:月)' **/
              const html = row.execDateType == 1 ? '每天' : row.execDateType == 2 ? '每周' : '每月';
              return `重复(${html})`;
            } else if (row.effectType == 2) {
              /** '单次执行类型(1:立即执行; 0:定时执行)' **/
              if (row.execType == 0) {
                return `<span class="vertical-middle">单次(</span><i class="el-icon-time fz16 vertical-middle" style="margin-right:2px"></i><span class="vertical-middle">${formatDateTimeByType(row.execTime, 'yyyy-MM-dd HH:mm:ss')})</span>`;
              } else {
                return '单次(立即执行)';
              }
            }
          }
        },
        { label: '营销方式', prop: 'marketingType', minWidth: '140', align: 'left' },
        {
          label: '数据对话',
          prop: 'marketingActivityName',
          minWidth: '140',
          align: 'left',
          formatter(row) {
            return row.marketingActivityName || '--';
          }
        },
        { label: '营销人次', prop: 'timesForPeople', minWidth: '120', align: 'left' },
        {
          label: '状态',
          prop: 'onlineStatus',
          minWidth: '140',
          align: 'left',
          formatter(row) {
            let result = '--';
            switch (row.onlineStatus) {
              case 0:
                result = '<span class="dm-status--primary">未开始</span>';
                break;
              case 1:
                result = row.effectType == 2 ? '<span class="dm-status--primary">待执行</span>' : '<span class="dm-status--primary--flash"></span><span class="vertical-middle">进行中</span>';
                break;
              case 2:
                result = row.effectType == 2 ? '<span class="dm-status--info">执行完毕</span>' : '<span class="dm-status--info">已结束</span>';
                break;
            }
            return result;
          }
        },
        {
          label: '计划触达人数',
          prop: 'ecmMemberNum',
          minWidth: '120',
          align: 'left',
          formatter(row) {
            let openFlag = JSON.parse(row.analyseJson);
            if (!openFlag) openFlag = {};
            return openFlag.open_flag == 0 || (!row.ecmMemberNum && row.ecmMemberNum != 0) ? '--' : row.ecmMemberNum;
          }
        },
        {
          label: '触达人数',
          prop: 'ecmSuccessNum',
          minWidth: '120',
          align: 'left',
          formatter(row) {
            let openFlag = JSON.parse(row.analyseJson);
            if (!openFlag) openFlag = {};
            return openFlag.open_flag == 0 || (!row.ecmSuccessNum && row.ecmSuccessNum != 0) ? '--' : row.ecmSuccessNum;
          }
        },
        {
          label: '转化人数',
          prop: 'ecmTranNum',
          minWidth: '120',
          align: 'left',
          formatter(row) {
            let openFlag = JSON.parse(row.analyseJson);
            if (!openFlag) openFlag = {};
            return openFlag.open_flag == 0 || (!row.ecmTranNum && row.ecmTranNum != 0) ? '--' : row.ecmTranNum;
          }
        },
        {
          label: '线索转化收益',
          prop: 'ecmTranIncome',
          minWidth: '120',
          align: 'left',
          formatter(row) {
            let openFlag = JSON.parse(row.analyseJson);
            if (!openFlag) openFlag = {};
            return openFlag.open_flag == 0 || (!row.ecmTranIncome && row.ecmTranIncome != 0) ? '--' : row.ecmTranIncome.toFixed(2);
          }
        },
        {
          label: '卡券收益',
          prop: 'cardSalesAmt',
          minWidth: '120',
          align: 'left',
          formatter(row) {
            let openFlag = JSON.parse(row.analyseJson);
            if (!openFlag) openFlag = {};
            return openFlag.open_flag == 0 || (!row.cardSalesAmt && row.cardSalesAmt != 0) ? '--' : row.cardSalesAmt.toFixed(2);
          }
        }
      ],
      tableList: []
    };
  },
  components: {
    activitySelect
  },
  created() {
    this.setXsxsFlag();
    getUseStoredFalg().then(res => {
      if (res.result.useStoredFlag) {
        this.marketingTypeOptions.find(el => el.value == 'grade').visible = true;
      }
    });
    this.loadEcmList();
    this.$store.commit('aside_handler', false);
    this.$store.commit('mutations_breadcrumb', [
      { name: '营销管理', path: '' },
      { name: '智能营销', path: '/ecm' }
    ]); // eslint-disable-line
  },
  methods: {
    search() {
      this.listParams.currentPage = 1;
      this.loadEcmList();
    },
    handleSizeChange(val) {
      this.listParams.pageSize = val;
      this.loadEcmList();
    },
    handleCurrentChange(val) {
      this.listParams.currentPage = val;
      this.loadEcmList();
    },
    async loadEcmList() {
      this.loading = true;
      const params = { ...this.listParams };
      if (params.effectType === '') {
        params.effectType = -1; // 全部时效的默认值是-1
      }
      let res = await loadEcmList(params);
      this.tableList = res.result.result || [];
      this.total = res.result.totalCount;
      this.loading = false;
    },
    //编辑
    copyData(row) {
      this.$router.push('/ecm/copy/' + row.ecmPlanId);
    },
    //编辑
    editData(row) {
      this.$router.push('/ecm/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 } });
    },
    // 触达效果
    toTouch(row) {
      this.$router.push({ path: `/ecm/touch/${row.ecmPlanId}`, query: { name: row.ecmPlanName, createTime: row.createTime } });
    },
    // 删除
    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.loadEcmList();
        } 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.loadEcmList();
        } else {
          this.$tips({ type: 'error', message: res.message || '下线失败!' });
        }
      } catch (err) {
        this.$tips({ type: 'error', message: '下线失败!' });
      }
    },
    setXsxsFlag() {
      // 是否开启销售线索
      getXsxsFalg().then(res => {
        this.xsxsFlag = res.result;
        this.$store.state.marketing.xsxsFlag = res.result;
        if (this.xsxsFlag == 0) {
          let arr = [];
          this.tableHeader.forEach(item => {
            if (item.label != '线索转化收益' && item.label != '转化人数' && item.label != '触达人数' && item.label != '计划触达人数') {
              arr.push(item);
            }
          });
          this.tableHeader = arr;
        }
        if (this.xsxsFlag) {
          // this.marketingTypeOptions.find(el => el.value == 'qywx').visible = true;
          this.marketingTypeOptions.find(el => el.value == 'qfxx').visible = true;
        }
      });
    },
    async onCommand(command, row) {
      if (command == 1) {
        this.toRecord(row);
      } else if (command == 2) {
        await this.$confirm('是否下线该计划?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        this.offlineEcmPlan(row);
      } else if (command == 3) {
        this.toTouch(row);
      } else if (command == 4) {
        this.copyData(row);
      }
    }
  },
  computed: {
    isOpenFlag(item) {
      return item => {
        if (!item) return false;
        item = JSON.parse(item);
        if (!item) item = {};
        if (item.open_flag == 0) {
          return false;
        } else {
          return true;
        }
      };
    },
    showMarketingTypeOptions() {
      return this.marketingTypeOptions.filter(el => el.visible == true);
    }
  }
};
</script>

<style lang="scss" scoped>
.el-icon-refresh {
  color: #909399;
  cursor: pointer;
  &:hover {
    color: #606266;
  }
}
</style>
