<template>
  <section class="dm-wrap" v-loading="recordLoading">
    <div class="page-tip">送达人数、计费条数会在提交完成后 5 分钟更新，点击详情可查看实时数据。</div>
    <div class="clearfix pb22">
      <el-date-picker class="w250" v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="refresh"></el-date-picker>
      <el-select class="dm-select" v-model="listParams.sendStatus" placeholder="选择发送状态" @change="refresh">
        <el-option v-for="item in sendStatusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <dm-activity-select class="vertical-middle w150 mr5" width="150" :actId.sync="listParams.marketingActivityId" onlySelect @actUpdate="refresh"></dm-activity-select>
      <el-checkbox class="vertical-middle" v-if="$store.state.marketing.isShowSelf" v-model="listParams.showSelfFlag" :true-label="1" :false-label="0" label="仅看本人" border @change="refresh" />
      <el-input v-model="listParams.search" class="w200" placeholder="输入模板名称/ID/内容" clearable @change="refresh"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button class="fr" type="primary" v-if="$getButtonLimit($buttonCode.marketingMessageAdd)" :limit-code="$buttonCode.marketingMessageAdd" @click="$router.push('/message/record/add')">新建群发</el-button>
      <span v-if="quantity != -1" class="fr" style="color:#909399;padding:9px 30px 0 0;display:flex;align-items:center">
        预估剩余条数
        <span style="color:#303133;font-weight:700;margin:0 6px"> {{ quantity }} </span>条
        <el-tooltip content="据当前账户余额估算，仅供参考，请以实际发送条数为准。" placement="top">
          <i class="iconfont icon-tishi" style="color:#909399;margin-left:6px" />
        </el-tooltip>
      </span>
    </div>
    <el-table tooltipEffect="light" :data="messageList" style="width: 100%">
      <el-table-column :min-width="100" align="left" label="发送时间" prop="sendTime">
        <template slot-scope="scope">
          <p class="cell-time">
            {{ formatDateTimeByType(scope.row.sendTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}<br /><span>{{ formatDateTimeByType(scope.row.sendTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column v-for="(v, i) in recordHeader" :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" :fixed="v.fixed" :render-header="onRenderHeader"></el-table-column>
      <el-table-column label="状态" prop="sendStatus" align="left" width="140px">
        <template slot-scope="scope">
          <span v-if="scope.row.sendStatus === 5"><span class="dm-status--primary--flash"></span>执行中</span>
          <span v-else-if="filterStatus(scope.row.sendStatus)" :class="'dm-status--' + filterStatus(scope.row.sendStatus).type">
            {{ filterStatus(scope.row.sendStatus).label }}
            <el-tooltip v-if="scope.row.sendStatus == 2 && scope.row.failReason" :content="scope.row.failReason" placement="top">
              <i class="el-icon-question" style="color:#c0c4cc;cursor:pointer;margin-left:3px;font-size:14px"></i>
            </el-tooltip>
          </span>
          <time-counts v-if="scope.row.sendStatus == 0" :key="scope.row.smsId" class="primary-color fz12" :defaultVal="scope.row.sendTime" :autoStart="true"></time-counts>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="140px" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="$router.push('/message/record/detail/' + scope.row.smsId)">详情</el-button>
          <dm-delete v-if="$getButtonLimit($buttonCode.marketingMessageDisable) && (scope.row.sendStatus == 4 || scope.row.sendStatus == 0) && scope.row.canEdit !== false" @confirm="invalidData(scope.row)" tips="是否禁用该发送记录?">
            <el-button type="text" :limit-code="$buttonCode.marketingMessageDisable">禁用</el-button>
          </dm-delete>
        </template>
      </el-table-column>
    </el-table>
    <dm-pagination v-show="messageList.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 { LoadMessageList, invalidsmsRecord } from '@/service/api/messageApi.js';
import { getSign } from '@/service/api/commonApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import timeCounts from '@/components/timeCount/index.vue';
import tableMethods from '@/mixins/tableMethods.js';
import tip from '@/components/tip';
export default {
  name: 'sms-record',
  components: {
    timeCounts,
    tip
  },
  mixins: [tableMethods],
  data() {
    return {
      sendStatusOptions: [{ value: '', label: '所有状态', type: '' }, { value: 0, label: '定时执行', type: 'warning' }, { value: 1, label: '已执行', type: 'success' }, { value: 2, label: '执行失败', type: 'error' }, { value: 5, label: '执行中', type: 'primary--flash' }, { value: -1, label: '已失效', type: 'error' }], // eslint-disable-line
      recordLoading: false,
      messageList: [],
      recordHeader: [
        // {
        //   label: '发送时间',
        //   prop: 'sendTime',
        //   minWidth: '160',
        //   align: 'left',
        //   fixed: 'left',
        //   formatter(row) {
        //     const date = formatDateTimeByType(row.sendTime, 'yyyy-MM-dd-HH-mm-ss', true);
        //     return date.y + '\n' + date.h;
        //   }
        // },
        {
          label: '模板名称',
          prop: 'templateName',
          minWidth: '140',
          align: 'left',
          fixed: 'left',
          formatter: row => {
            // <p class="fz13 gray">(ID:{row.templateId})</p>
            return (
              <div>
                <span>{row.templateName}</span>
              </div>
            );
          }
        },
        { label: '创建人', prop: 'creatorName', width: '100', tooltip: true, align: 'left' },
        {
          label: '模板内容',
          prop: 'templateContent',
          minWidth: '150',
          tooltip: false,
          align: 'left',
          formatter: (row, column, cellValue, index) => {
            if (row.templateContent && row.templateContent.length > 10) {
              return (
                <el-popover placement="top-start" width="200" trigger="hover" content={row.templateContent}>
                  <div class="ellipsis" slot="reference">
                    {row.templateContent}
                  </div>
                </el-popover>
              );
            } else {
              return <span>{row.templateContent}</span>;
            }
          }
        },
        { label: '计划人数', prop: 'sendCount', width: '100', align: 'left' },
        { label: { name: '送达人数', tipText: '提交成功的人数' }, prop: 'sendSuccess', width: '100', align: 'left' },
        { label: '计费条数', prop: 'countNum', width: '100', align: 'left' }
      ],
      listParams: {
        sendStatus: '',
        marketingActivityId: '',
        sendBeginTime: '',
        sendEndTime: '',
        search: '',
        currentPage: 1,
        pageSize: 20,
        showSelfFlag: ''
      },
      dateTime: ['', ''],
      total: 0,
      quantity: 0
    };
  },
  created() {
    this.getTableList();
    this.getQuantity();
    document.addEventListener('scroll', () => {
      console.log('--->scroll');
      // console.log(document.body.scrollHeight);
      // console.log(window.screen.height);
      // console.log(document.body.scrollTop);
    });
  },
  methods: {
    formatDateTimeByType,
    async getTableList() {
      try {
        this.recordLoading = true;
        if (this.dateTime) {
          this.listParams.sendBeginTime = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd');
          this.listParams.sendEndTime = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd');
        } else {
          this.listParams.sendBeginTime = this.listParams.sendEndTime = '';
        }
        let res = await LoadMessageList(this.listParams);
        if (res.errorCode === 0 && res.result) {
          this.messageList = res.result.result || [];
          this.total = res.result.totalCount;
        } else {
          this.messageList = [];
          this.total = 0;
        }
        this.recordLoading = false;
      } catch (err) {
        this.recordLoading = false;
      }
    },
    invalidData(row) {
      invalidsmsRecord({ smsId: row.smsId })
        .then(res => {
          this.$tips({ type: 'success', message: '禁用成功!' });
          this.getTableList();
        })
        .catch(err => {
          this.$tips({ type: 'error', message: '禁用失败!' });
        });
    },
    filterStatus(val) {
      let result = null;
      this.sendStatusOptions.forEach(v => {
        if (val === v.value) result = v;
      });
      return result;
    },
    // 获取剩余条数
    getQuantity() {
      getSign().then(res => {
        this.quantity = res.result.quantity || 0;
      });
    },
    onRenderHeader(h, { column: { label } }) {
      return h('span', [h('span', label.name || label), h(label.name && tip, { props: { text: label.tipText } })]);
    }
  }
};
</script>
