<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>
    </div>
    <el-table tooltipEffect="light" :data="tableList" style="width: 100%" element-loading-text="拼命加载中">
      <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="260" 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" @click="editData(scope.row)">编辑</el-button>
            <el-button type="text" v-if="scope.row.effectType == 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>
        </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: 'ecmPlanName', minWidth: '160', align: 'left', fixed: 'left' },
        {
          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 `单次(<i class="el-icon-time fz18 vertical-middle"></i>${formatDateTimeByType(row.execTime, 'yyyy-MM-dd HH:mm:ss')})`;
              } 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 = '<span class="dm-status--success">已上线</span>';
                break;
              case 2:
                result = '<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;
          }
        }
      ],
      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;
    },
    //编辑
    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 } });
    },
    // 删除
    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;
        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;
        }
      });
    }
  },
  computed: {
    isOpenFlag(item) {
      return item => {
        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>
