<template>
  <section v-loading="loading">
    <div class="dm-wrap clearfix">
      <div class="page-tip">历史数据限制：2018年11月15日之前的历史营销计划，没有详细数据</div>
      <el-date-picker class="w250" v-model="dateTime" :clearable="false" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="search"></el-date-picker>
      <el-select class="dm-select" clearable v-model="listParams.success" placeholder="所有条件" @change="search">
        <el-option v-for="(v, i) in successOptions" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-select class="dm-select" placeholder="所有条件" v-model="listParams.status" @change="changeStatus">
        <el-option label="正在进行中" :value="1"></el-option>
        <el-option label="已删除" :value="0"></el-option>
      </el-select>
      <!-- <el-button type="text" @click="goHistory"> 历史记录</el-button> -->
      <el-button icon="iconfont icon-icon_yunxiazai" class="fr" type="primary" v-if="buttonLimit" :limit-code="buttonCode" @click="exportCurrentSendDetails"> 导出列表</el-button>
    </div>
    <div class="dm-wrap" style="padding-top: 0">
      <el-table ref="multipleTable" tooltipEffect="light" :data="infoList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column min-width="120" label="发送内容">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" open-delay="300" placement="top-start">
              <div style="max-width:400px;" slot="content">
                <pre>{{ scope.row.title }}</pre>
              </div>
              <div class="ellipsis">{{ scope.row.title }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column v-for="(v, i) in infoHeader" :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 style="font-weight: 500">{{ v.label }}</span>
              <el-tooltip v-if="v.prop == 'successCount'" placement="top" :open-delay="200">
                <i class="iconfont icon-xinxixianshi" style="color:#909399;font-size:14px"></i>
                <div slot="content">
                  <div>指的是GIC系统成功提交针对这些用户的营销行为，并不是指的实际触达成功，如：</div>
                  成功通过服务号接口进行消息群发；<br />
                  成功向短信运营商提交需要发送短信的用户名单；<br />
                  成功通过企微群发接口下发群发任务；<br />
                  成功通过话务任务接口下发话务任务；
                </div>
              </el-tooltip>
              <el-tooltip v-else-if="v.prop == 'failedCount'" placement="top" :open-delay="200">
                <i class="iconfont icon-xinxixianshi" style="color:#909399;font-size:14px"></i>
                <div slot="content">
                  <div>指的是GIC系统未成功提交针对这些用户的营销行为，如：</div>
                  未成功通过服务号接口进行消息群发；<br />
                  未成功向短信运营商提交需要发送短信的用户名单；<br />
                  未成功通过企微群发接口下发群发任务；<br />
                  未成功通过话务任务接口下发话务任务；
                </div>
              </el-tooltip>
            </span>
          </template>
          <template slot-scope="scope">
            <span v-if="v.formatter" v-html="v.formatter(scope.row)"></span>
            <component v-else-if="v.component" :is="v.component"></component>
            <span v-else>{{ scope.row[v.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发送时间" align="left" width="120" prop="createTime" v-if="effectType != 0 && effectType != 2">
          <template slot-scope="scope">
            <p class="cell-time">
              {{ formatDateTimeByType(scope.row.createTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}<br />
              <span>{{ formatDateTimeByType(scope.row.createTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</span>
            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="dm-wrap">
      <el-input v-model="userMemberInfo" class="w250 mb20" placeholder="输入会员昵称/名字/手机号" clearable @change="searchUnder"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-table tooltipEffect="light" :data="tableList" style="width: 100%" v-loading="loading">
        <el-table-column type="index" width="50" label="序号"></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>
            <component v-else-if="v.component" :is="v.component" :row="scope.row" :showImg="v.showImg"></component>
            <span v-else>{{ scope.row[v.prop] || '--' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <dm-pagination hide-on-single-page 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>
    </div>
    <vue-gic-export-excel :dialogVisible.sync="dialogVisible" :dataArr="tableList" :type="2" :excelUrl="excelUrl" :params="params" :projectName="projectName"></vue-gic-export-excel>
  </section>
</template>
<script>
import { ecmCurrentSendInfos, ecmCurrentSendDetails, exportCurrentSendDetails } from '@/service/api/ecmApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import memberInfo from '@/components/member-info/index.vue';
const typeOptions = [{ value: '', label: '所有类型' }, { value: 'teletext', label: '图文' }, { value: 'text', label: '文本' }, { value: 'image', label: '图片' }, { value: 'card', label: '卡券' }, { value: 'wxa', label: '小程序' }, { value: 'message', label: '短信' }, { value: 'teltask', label: '话务' }, { value: 'integral', label: '积分' }, { value: 'qywx', label: '企微任务' }, { value: 'qfxx', label: '群发任务' }, { value: 'grade', label: '会员卡升级' }, { value: 'teltask-fail', label: '群发失败-话务' }, { value: 'message-fail', label: '群发失败-短信' }]; // eslint-disable-line
export default {
  name: 'ecm-current-list',
  components: {
    'member-info': memberInfo
  },
  props: {
    isComponet: {
      // 是否作为组件使用  扫码营销作为组件引入该页面
      default: false,
      type: Boolean
    }
  },
  computed: {
    buttonLimit() {
      return this.$getButtonLimit(this.buttonCode);
    },
    buttonCode() {
      return this.isComponet ? this.$buttonCode.marketingDownloadSecmLog : this.$buttonCode.marketingDownloadEcmLog;
    }
  },
  data() {
    return {
      dateTime: [Date.now() - 30 * 24 * 60 * 60 * 1000, Date.now()],
      successOptions: [{ value: '', label: '所有状态' }, { value: 1, label: '提交成功' }, { value: 0, label: '提交失败' }], // eslint-disable-line
      listParams: {
        ecmPlanId: this.$route.params.id,
        ecmMarketingTypeRelationIds: '',
        currentPage: 1,
        pageSize: 20,
        success: '',
        beginTime: '',
        endTime: '',
        status: 1
      },
      userMemberInfo: '', // 下面列表搜索
      total: 0,
      loading: false,
      infoHeader: [
        {
          label: '营销方式',
          prop: 'marketingType',
          align: 'left',
          formatter(row) {
            let result = '--';
            typeOptions.map(v => {
              if (v.value === row.marketingType) {
                result = v.label;
              }
            });
            return result;
          }
        },
        { label: '应发数量', prop: 'sendCount', align: 'left' },
        { label: '提交成功', prop: 'successCount', align: 'left' },
        { label: '提交失败', prop: 'failedCount', align: 'left' },
        {
          label: '使用状态',
          prop: 'status',
          align: 'left',
          formatter(row) {
            return row.status ? '<span class="dm-status--primary--flash"></span><span class="vertical-middle">正在使用</span>' : '<span class="dm-status--info">已删除</span>';
          }
        }
      ],
      infoList: [],
      tableList: [],
      tableHeader: [
        {
          label: '回复信息',
          prop: 'title',
          minWidth: '120',
          align: 'left',
          formatter(row) {
            return row.title || '--';
          }
        },
        { label: '会员信息', prop: 'marketingType', minWidth: '120', align: 'left', component: 'member-info', showImg: 0 },
        { label: '手机号码', prop: 'phoneNumber', minWidth: '120', align: 'left' },
        { label: '主门店', prop: 'mainStoreName', minWidth: '120', align: 'left' },
        { label: '专属导购', prop: 'mainClerkName', minWidth: '120', 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: 'errCode',
          minWidth: '120',
          align: 'left',
          formatter(row) {
            return row.errCode == '0' ? '<span class="dm-status--success">提交成功</span>' : '<span class="dm-status--error">提交失败</span>';
          }
        },
        { label: '备注', prop: 'errMsg', minWidth: '120', align: 'left' }
      ],
      projectName: 'marketing', // 当前项目名
      dialogVisible: false,
      excelUrl: '', // 下载数据的地址
      params: {}, // 传递的参数
      effectType: 0
    };
  },
  async created() {
    this.effectType = this.$route.query.effectType;
    await this.ecmCurrentSendInfos();
    this.$nextTick(_ => {
      this.$refs.multipleTable.toggleAllSelection();
    });
  },
  methods: {
    formatDateTimeByType,
    handleSelectionChange(val) {
      this.selectedId = val.map(v => v.ecmMarketingTypeRelationId);
      let list = val
        .map(v => v.ecmMarketingTypeRelationId)
        .filter(v => v)
        .join(',');
      this.listParams.ecmMarketingTypeRelationIds = list;
      this.ecmCurrentSendDetails();
    },
    changeStatus() {
      this.listParams.currentPage = 1;
      this.ecmCurrentSendInfos();
    },
    search() {
      this.listParams.currentPage = 1;
      this.ecmCurrentSendInfos();
      // this.ecmCurrentSendDetails();
    },
    searchUnder() {
      this.listParams.currentPage = 1;
      this.ecmCurrentSendDetails();
    },
    handleSizeChange(val) {
      this.listParams.pageSize = val;
      this.ecmCurrentSendDetails();
    },
    handleCurrentChange(val) {
      this.listParams.currentPage = val;
      this.ecmCurrentSendDetails();
    },
    // 上面列表
    async ecmCurrentSendInfos() {
      this.loading = true;
      this.formatterTimeFunc();
      let res = await ecmCurrentSendInfos({
        ecmPlanId: this.$route.params.id,
        beginTime: this.listParams.beginTime,
        endTime: this.listParams.endTime,
        memberInfo: this.listParams.memberInfo,
        success: this.listParams.success,
        status: this.listParams.status
      });
      this.infoList = res.result || [];
      // this.$nextTick(_ => {
      //   this.$refs.multipleTable.toggleAllSelection();
      // });
      if (this.selectedId && this.selectedId.length > 0) {
        const selectedRows = this.infoList.filter(el => this.selectedId.includes(el.ecmMarketingTypeRelationId));
        this.$nextTick(_ => {
          selectedRows.forEach(el => {
            this.$refs.multipleTable.toggleRowSelection(el);
          });
        });
      }

      let list = this.infoList
        .map(v => v.ecmMarketingTypeRelationId)
        .filter(v => v)
        .join(',');
      this.listParams.ecmMarketingTypeRelationIds = list;
      this.loading = false;
    },
    // 下面列表
    async ecmCurrentSendDetails() {
      this.loading = true;
      this.formatterTimeFunc();
      let params = { ...this.listParams, ...{ memberInfo: this.userMemberInfo } };
      let res = await ecmCurrentSendDetails(params);
      this.tableList = res.result.result || [];
      this.total = res.result.totalCount || 0;
      this.loading = false;
    },
    // 导出
    exportCurrentSendDetails() {
      this.dialogVisible = true;
      this.excelUrl = exportCurrentSendDetails;
      this.formatterTimeFunc();
      this.params = {
        memberInfo: this.listParams.memberInfo,
        success: this.listParams.success,
        ecmPlanId: this.listParams.ecmPlanId,
        ecmPlanName: this.$route.query.name,
        beginTime: this.listParams.beginTime,
        endTime: this.listParams.endTime,
        ecmMarketingTypeRelationIds: this.listParams.ecmMarketingTypeRelationIds,
        requestProject: 'marketing'
      };
    },
    /*-----------辅助方法-------------*/
    formatterTimeFunc() {
      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.senendTimedEndTime = '';
      }
    }
  }
};
</script>
