<template>
  <section class="dm-wrap">
      <div class="clearfix pb22">
        <el-date-picker class="w250" v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="LoadMessageList"></el-date-picker>
        <el-select class="dm-select" v-model="listParams.sendStatus" placeholder="选择发送状态" @change="LoadMessageList">
            <el-option v-for="item in sendStatusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-select class="dm-select" v-model="listParams.sceneSettingId" placeholder="选择营销场景" @change="LoadMessageList">
            <el-option v-for="item in sceneSettingIdOptions" :key="item.sceneSettingId" :label="item.sceneName" :value="item.sceneSettingId"></el-option>
        </el-select>
        <el-input v-model="listParams.search" class="w200" placeholder="输入模板名称/ID/内容" clearable @change="LoadMessageList"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
        <el-button class="fr" type="primary" @click="$router.push('/message/record/add')">新建群发</el-button>
      </div>
      <el-table tooltipEffect="light" :data="messageList" style="width: 100%" v-loading="recordLoading">
            <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"></el-table-column>
            <el-table-column label="状态" prop="sendStatus" fixed="right" align="left" width="140px">
                <template slot-scope="scope" >
                  <el-tag size="small" :type="filterStatus(scope.row.sendStatus).type">{{filterStatus(scope.row.sendStatus).label}}</el-tag>
                  <div v-if="scope.row.sendStatus == 0">
                    <time-counts class="danger-color fz12" :defaultVal="scope.row.sendTime" :autoStart="true"></time-counts>
                  </div>
                </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>
                    <el-button type="text" v-if="scope.row.sendStatus == 4 || scope.row.sendStatus == 0" @click="invalidData(scope.row)">禁用</el-button>
                </template>
            </el-table-column>
      </el-table>
      <el-pagination v-show="messageList.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total"></el-pagination>
  </section>
</template>
<script>
import {LoadMessageList,invalidsmsRecord} from '@/service/api/messageApi.js';
import {sceneSettingList} from '@/service/api/wechatApi.js';
import {formateDateTimeByType} from '@/utils/index.js'
import  timeCounts from '@/components/timeCount/index.vue'

export default {
    name: 'sms-record',
    components:{
      timeCounts
    },
    data () {
        let _vm = this;
        return {
            sendStatusOptions:[
              {value:'',label:'全部',type:''},
              {value:0,label:'定时执行',type:'success'},
              {value:1,label:'执行完毕',type:'success'},
              {value:2,label:'执行失败',type:'danger'},
              {value:3,label:'无可用模板',type:'warning'},
              {value:4,label:'定时执行',type:'info'},
              {value:5,label:'执行中',type:'success'},
              {value:-1,label:'已失效',type:'danger'}],
            sceneSettingIdOptions:[],
            searchWord:'',
            recordLoading:false,
            messageList:[],
            recordHeader:[
                {label:'发送时间',prop:'sendTime',width:'160',align:'left',formatter:function(row){
                  return formateDateTimeByType(row.sendTime,'yyyy-MM-dd-HH-mm-ss');
                }},
                {label:'模板名称',prop:'templateName',minWidth:'140',align:'left',formatter:function(row){
                  var d =  `${row.templateName}\r\n\n(ID:${row.templateId})`
                  return d;
                }},
                {label:'发送人',prop:'sendName',width:'100', tooltip:true,align:'left'},
                {label:'模板内容',prop:'templateContent',minWidth:'150', tooltip:false,align:'left',
                  formatter:function(row, column, cellValue, index){
                    return (<el-popover placement="top-start"  width="200" trigger="hover" content={row.templateContent}>
                          <div class="ellipsis" slot="reference">{row.templateContent}</div>
                        </el-popover>)
                  }
                },
                {label:'计划人数',prop:'sendCount',width:'100',align:'left'},
                {label:'送达人数',prop:'sendSuccess',width:'100',align:'left'},
                {label:'计费条数',prop:'countNum',width:'100',align:'left'}
            ],
            listParams:{
                sendStatus:'',	//否	number	发送状态（0：待发送，1：已发送，2：已失效）
                sceneSettingId:-1,	//否	String	营销场景ID (全部:null)
                sendBeginTime:'',
                sendEndTime:'',
                search:'',	//否	String	输入发送人搜索
                currentPage:1,	//是	Number	当前页面
                pageSize:20 //是	Number	每页显示条数
            },
            dateTime:['',''],
            total:0,
        }
    },
    created() {
      this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'短信营销',path:'/message'},{name:'短信群发',path:''}]);
      this.LoadMessageList();
      this.sceneSettingList();
    },
    methods: {
      handleSizeChange(val) {
          this.listParams.pageSize = val;
          this.LoadMessageList();
      },
      handleCurrentChange(val) {
          this.listParams.currentPage = val;
          this.LoadMessageList();
      },
      async LoadMessageList() {
        try {
          this.recordLoading = true;
          if (this.dateTime) {
            this.listParams.sendBeginTime = formateDateTimeByType(this.dateTime[0],'yyyy-MM-dd');
            this.listParams.sendEndTime = formateDateTimeByType(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) {
        this.$confirm('是否禁用该发送记录?', '提示', {
          confirmButtonText: '确定',
          cancelBUttonText: '取消',
          type: 'warning'
        }).then(() => {
            invalidsmsRecord({smsId:row.smsId}).then(res => {
                this.$tips({type: 'success',message: '禁用成功!'});
                this.sendRecordList();
            }).catch(err => {
                this.$tips({type: 'error',message: '禁用失败!'});
            })
        }).catch(() => {
            this.$tips({type: 'info',message: '已取消禁用'});
        });
      },
      async sceneSettingList() {
        let res = await sceneSettingList();
        this.sceneSettingIdOptions = res.result;
        this.sceneSettingIdOptions.unshift({sceneSettingId:-1,sceneName:"全部"});
      },
      filterStatus(val) {
        let result = {label:'执行错误',type:'warning'};
        this.sendStatusOptions.forEach(v => {
          if (val === v.value) {
            result = v
          }
        })
        return result;
      }
    },
}
</script>
