<template>
  <section class="dm-wrap" v-loading="loading">
    <div class="page-tip">短信模板审核时间一般为半个工作日，具体以运营商审核为准</div>
    <div class="pb10">
      <el-select class="dm-select" v-model="listParams.type" placeholder="选择营销场景" @change="search">
        <el-option v-for="(v, i) in libTypeOptions" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-date-picker class="w250" v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="search"></el-date-picker>
      <el-input v-model="listParams.content" style="width: 180px" placeholder="输入模板名称/内容" clearable @change="search"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button class="fr" type="primary" v-if="$getButtonLimit($buttonCode.marketingTempAdd)" :limit-code="$buttonCode.marketingTempAdd" @click="addTemp">
        新建短信模板<span>（{{ usedCount }}/{{ allUsableCount }}）</span>
      </el-button>
      <span class="fr pt10 pr20">
        <span class="gray fz13">审核未通过也占用模板数，如需更多模板请联系商家运营</span>
      </span>
    </div>
    <el-row :gutter="20">
      <el-col :span="12" v-for="(v, i) in smsTempList" :key="i">
        <div class="sms-lib-item border1">
          <div class="sms-lib-item_top ellipsis-80" :title="`${v.smsTitle}`">模板名称：{{ v.smsTitle }}</div>
          <!-- （ID:{{ v.gicSmsTemplateId }}） -->
          <div class="sms-lib-item_body">
            <p class="danger-color" v-if="v.auditStatus === 2"><i class="el-icon-warning"></i> {{ v.auditResult }}</p>
            <p>{{ v.smsContent }}</p>
          </div>
          <div class="sms-lib-item_bottom clearfix">
            <div class="fl">
              <span>{{ v.creatorName }}</span>
              <span>创建于 {{ formatDateTimeByType(v.createTime, 'yyyy-MM-dd-HH-mm-ss') }}</span>
            </div>
            <div class="fr">
              <el-button type="text" v-if="$getButtonLimit($buttonCode.marketingTempEdit) && v.auditStatus === 2" :limit-code="$buttonCode.marketingTempEdit" @click="$router.push('/message/temp/edit/' + v.gicSmsTemplateId)">修改</el-button>
              <el-button type="text" v-if="$getButtonLimit($buttonCode.marketingTempDel)" :limit-code="$buttonCode.marketingTempDel" @click="onDeleteData(v)">删除</el-button>
              <!-- <dm-delete @confirm="delData(v)" tips="模板删除后，所有引用此模板的短信都会停止发送，请确认。">
                <el-button type="text">删除</el-button>
              </dm-delete> -->
            </div>
          </div>
          <span class="sms-lib-item-tips_right danger-color-bg" v-if="v.auditStatus === 2">未通过</span>
          <span class="sms-lib-item-tips_right warning-color-bg" v-if="v.auditStatus === 1">审核中</span>
          <span class="sms-lib-item-tips_right success-color-bg" v-if="v.auditStatus === 0">已通过</span>
        </div>
      </el-col>
    </el-row>
    <div class="text-center" v-if="smsTempList.length === 0">
      <img class="block block-center pt100" width="60" height="60" src="../../assets/img/no-data_icon.png" alt="" />
      <el-button class="block block-center mt10" type="text" @click="$router.push('/message/temp/add')">新建短信模板</el-button>
    </div>
    <del-dialog :dialogVisible.sync="dialogVisible" :list="delList" />
    <dm-pagination v-show="smsTempList.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 { formatDateTimeByType } from '@/utils/index.js';
import { LoadLibList, delTempService } from '@/service/api/messageApi.js';
import delDialog from './delDialog.vue';
export default {
  name: 'sms-lib',
  data() {
    return {
      formatDateTimeByType,
      loading: false,
      smsTempList: [],
      libTypeOptions: [
        { value: '', label: '全部模板类型' },
        { value: 0, label: '普通短信模板' },
        { value: 1, label: '营销短信模板' }
      ], // eslint-disable-line
      listParams: {
        type: '',
        content: '',
        currentPage: 1,
        pageSize: 20,
        startTime: '',
        endTime: ''
      },
      total: 0,
      allUsableCount: 0,
      usedCount: 0,
      dateTime: [],
      delObj: {
        isCandele: false,
        list: [
          {
            id: 1,
            busiType: 1,
            busiName: '',
            busiObjId: '1',
            busiObjName: '过年短信模板',
            busiObjRelationId: '1',
            busiObjRelationName: 'ai智能营销',
            busiObjRelationCreaterId: '1',
            busiObjRelationCreater: 'afeng',
            busiObjRelationUrl: 'www.bai.com',
            status: 1,
            createTime: 1655872198000,
            updateTime: 1655872202000
          }
        ]
      },
      dialogVisible: false,
      delList: []
    };
  },
  created() {
    this.LoadLibList();
  },
  components: {
    delDialog
  },
  methods: {
    onDeleteData(v) {
      // this.dialogVisible = true;
      // this.delList = this.delObj.list;
      this.$confirm('确认删除该模板？删除后，所有引用此模板的短信都会停止发送。', '提示', {
        confirmButtonText: '确认',
        cancelBUttonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delData(v);
        })
        .catch(() => {});
    },
    search() {
      this.listParams.currentPage = 1;
      this.LoadLibList();
    },
    handleSizeChange(val) {
      this.listParams.pageSize = val;
      this.LoadLibList();
    },
    handleCurrentChange(val) {
      this.listParams.currentPage = val;
      this.LoadLibList();
    },
    async LoadLibList() {
      this.loading = true;
      if (this.dateTime) {
        this.listParams.startTime = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd');
        this.listParams.endTime = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd');
      } else {
        this.listParams.startTime = this.listParams.endTime = '';
      }
      try {
        let res = await LoadLibList(this.listParams);
        if (res.errorCode === 0 && res.result) {
          this.smsTempList = res.result.result || [];
          this.allUsableCount = res.result.params.allUsableCount || 0;
          this.usedCount = res.result.params.usedCount || 0;
          this.total = res.result.totalCount;
        } else {
          this.smsTempList = [];
          this.total = 0;
        }
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },
    addTemp() {
      if (this.usedCount >= this.allUsableCount) {
        this.$alert(
          `<div>
        <i class="el-icon-warning warning-color fz30 vertical-middle mr20"></i>
        <p class="inline-block vertical-middle w300">已超过可用短信模板数量，请删除不用短信模板释放数量或直接与GIC运营联系。</p>
        </div>`,
          '提示',
          {
            dangerouslyUseHTMLString: true,
            showCancelButton: true,
            showConfirmButton: false,
            cancelButtonText: '关 闭'
          }
        );
      } else {
        this.$router.push('/message/temp/add');
      }
    },
    delData({ gicSmsTemplateId }) {
      delTempService({ gicSmsTemplateId }).then(res => {
        if (res.errorCode === 0) {
          this.$tips({ type: 'success', message: '删除成功!' });
          this.LoadLibList();
        } else {
          this.$tips({ type: 'error', message: '删除失败!' });
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
.sms-lib-item {
  position: relative;
  margin: 10px 0;
  overflow: hidden;
  &_top {
    height: 50px;
    line-height: 50px;
    margin: 0 15px;
  }
  &_body {
    height: 70px;
    overflow-y: auto;
    line-height: 1.5;
    margin: 0 15px;
    padding: 10px;
    background: #f5f8fa;
    font-size: 13px;
  }
  &_bottom {
    margin: 0 15px;
    height: 50px;
    line-height: 50px;
  }
  &-tips_right {
    position: absolute;
    right: 0;
    top: 0;
    padding: 5px 10px;
    color: #fff;
  }
}
</style>
