<template>
  <div class="contain">
    <div class="cardList">
      <div class="card" v-for="item in cardContent" :key="item.title">
        <div class="cardTitle">
          <i :class="['iconfont', item.iconName]" style="font-size:20px;" />
          <span>{{ item.title }}</span>
        </div>
        <div class="cardBody">
          {{ item.content }}
        </div>
        <el-button v-if="$getButtonLimit($buttonCode.marketingAddAi)" :limit-code="$buttonCode.marketingAddAi" size="small" type="primary" @click="create(item.scene)">立即新建</el-button>
      </div>
    </div>
    <div class="account">
      <span>
        账户可用余额：<span style="font-size:16px;">{{ (money / 100) | amount }}</span>
      </span>
      <el-button v-if="$getButtonLimit($buttonCode.marketingAiRecharge)" :limit-code="$buttonCode.marketingAiRecharge" type="text" @click="recharge">立即充值</el-button>
    </div>
    <div class="searchWarp">
      <el-form inline="true" class="table-page-search-wrapper" size="small">
        <el-form-item>
          <el-input v-model="form.activityName" clearable placeholder="请输入活动名称" @change="search"> <i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="form.scene" placeholder="全部场景" @change="search" clearable>
            <el-option v-for="item in optionScenes" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="form.activityPlanStatus" placeholder="全部活动状态" @change="search" clearable>
            <el-option v-for="item in optionActive" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker :clearable="false" v-model="form.time" :picker-options="pickerOptions" value-format="timestamp" @change="search" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" style="width:100%" v-loading="loading">
      <el-table-column prop="activityName" label="活动名称" fixed="left" show-overflow-tooltip width="200px" />
      <el-table-column prop="scene" label="活动场景" show-overflow-tooltip width="120px">
        <template slot-scope="{ row }">
          {{ row.scene | sceneFilter }}
        </template>
      </el-table-column>
      <el-table-column prop="aiTemplateName" label="话术名称" show-overflow-tooltip width="180px" />
      <el-table-column prop="seatSum" label="坐席数" show-overflow-tooltip />
      <el-table-column prop="smsFlag" label="挂机短信" show-overflow-tooltip>
        <template slot-scope="{ row }">
          {{ row.smsFlag | yesOrnoFilter }}
        </template>
      </el-table-column>
      <el-table-column prop="recallFlag" label="自动重拨" show-overflow-tooltip>
        <template slot-scope="{ row }">
          {{ row.recallFlag | yesOrnoFilter }}
        </template>
      </el-table-column>
      <el-table-column prop="activityPlanStatus" width="120" label="活动状态" show-overflow-tooltip>
        <template slot-scope="{ row }"> <span :class="statusPoint[row.activityPlanStatus]"></span> {{ row.activityPlanStatus | activePlanStatusFilter }} </template>
      </el-table-column>
      <el-table-column prop="marketingNumber" label="营销人数" show-overflow-tooltip />
      <el-table-column prop="outboundNumber" label="已外呼数" show-overflow-tooltip />
      <el-table-column prop="totalConnectionNumber" label="总接通数" show-overflow-tooltip />
      <el-table-column prop="telephoneConnectionRate" label="接通率" show-overflow-tooltip />
      <el-table-column prop="connectionIntentionRate" label="接通意向率" show-overflow-tooltip width="120" />
      <el-table-column prop="beginDate" label="外呼周期" show-overflow-tooltip width="160">
        <template slot-scope="{ row }">
          <p class="cell-time">
            {{ formatDateTimeByType(row.beginDate, 'yyyy-MM-dd') }}<br />
            {{ formatDateTimeByType(row.endDate, 'yyyy-MM-dd') }}
          </p>
        </template>
      </el-table-column>
      <el-table-column prop="creatorName" label="创建人" show-overflow-tooltip width="120" />
      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip width="160">
        <template slot-scope="{ row }">
          {{ formatDateTimeByType(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="160">
        <template slot-scope="{ row }">
          <dm-dropdown ref="drop" :scope-data="row" :configs="btnArr" @command="onCommand" />
        </template>
      </el-table-column>
    </el-table>
    <dm-pagination v-show="tableData.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="getTableData" :current-page.sync="form.pageNum" :page-sizes="[20, 40, 60, 80]" :page-size.sync="form.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
  </div>
</template>

<script>
import { page, rechargeCenter, stopActivityPlan, startActivityPlan, pageStatistics, aiAccountCheck } from '@/service/api/aiApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import filterAvater from '@/mixins/filterAvater.js';

const maxTimeRange = 365 * 24 * 60 * 60 * 1000; // 12个月
export default {
  mixins: [filterAvater],
  data() {
    return {
      tableData: [],
      formatDateTimeByType,
      loading: false,
      form: {
        activityName: '',
        scene: '',
        activityPlanStatus: '',
        time: [new Date().getTime() - 365 * 24 * 60 * 60 * 1000, new Date().getTime()],
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() < new Date().getTime() - maxTimeRange || time.getTime() > new Date().getTime();
        }
      },
      btnArr: [
        {
          text: '查看',
          props: {
            limitCode: this.$buttonCode.marketingAiInfo
          },
          visible: row => {
            return this.$getButtonLimit(this.$buttonCode.marketingAiInfo);
          },
          handler: row => this.$router.push('/ai/info/' + row.activityId)
        },
        {
          text: '编辑',
          props: {
            limitCode: this.$buttonCode.marketingAiEdit
          },
          visible: row => {
            return row.activityPlanStatus === 1 && this.$getButtonLimit(this.$buttonCode.marketingAiEdit);
          },
          handler: row => this.editPlan(row)
        },
        {
          text: '终止',
          props: {
            limitCode: this.$buttonCode.marketingAiStop
          },
          visible: row => {
            return (row.activityPlanStatus === 1 || row.activityPlanStatus == 2) && this.$getButtonLimit(this.$buttonCode.marketingAiStop);
          },
          handler: row => this.stopTask(row)
        },
        {
          text: '重新开启',
          props: {
            limitCode: this.$buttonCode.marketingAiStart
          },
          visible: row => {
            return row.activityPlanStatus === 5 && this.$getButtonLimit(this.$buttonCode.marketingAiStart);
          },
          handler: row => this.rebootTask(row)
        },
        {
          text: '复制',
          props: {
            limitCode: this.$buttonCode.marketingAiCopy
          },
          visible: () => {
            return this.$getButtonLimit(this.$buttonCode.marketingAiCopy);
          },
          handler: row => {
            this.create('', row.activityId);
          }
        },
        {
          text: '提交日志',
          props: {
            limitCode: this.$buttonCode.marketingAiLog
          },
          visible: row => {
            return row.logFlag === 1 && this.$getButtonLimit(this.$buttonCode.marketingAiLog);
          },
          handler: row =>
            this.$router.push({
              path: '/ai/logs/' + row.activityId,
              query: {
                activityName: row.activityName,
                startTime: row.beginDate,
                endTime: row.endDate
              }
            })
        },
        {
          text: '数据统计',
          props: {
            limitCode: this.$buttonCode.marketingAiStatistics
          },
          visible: row => {
            return row.logFlag === 1 && this.$getButtonLimit(this.$buttonCode.marketingAiStatistics);
          },
          handler: row => {
            this.$router.push({
              path: '/ai/ai-data-report/' + row.activityId,
              query: {
                planId: row.planId
              }
            });
          }
        }
      ],
      cardContent: [
        {
          title: '客户生日',
          scene: 1,
          iconName: 'icon-shengrizunxiang',
          content: '针对生日客户进行营销，提高会员粘性'
        },
        {
          title: '节日活动邀约',
          scene: 2,
          iconName: 'icon-huodongyaoyue',
          content: '节日活动邀约，会员专享权益，提升门店营业额'
        },
        {
          title: '加企微好友',
          scene: 3,
          iconName: 'icon-qiweihaoyou',
          content: '针对未添加企微好友的客户进行营销，添加企微好友'
        },
        {
          title: '客户复购',
          scene: 4,
          iconName: 'icon-kehufugouguanli',
          content: '针对消费过的客户进行营销，提升核心客户数量'
        },
        {
          title: '其它场景',
          scene: 0,
          iconName: 'icon-qitachangjing',
          content: '自定义营销场景'
        }
      ],
      optionScenes: [
        {
          value: 1,
          label: '客户生日'
        },
        {
          value: 2,
          label: '节日活动邀约'
        },
        {
          value: 4,
          label: '客户复购'
        },
        {
          value: 0,
          label: '其它场景'
        }
      ],
      optionActive: [
        {
          value: 1,
          label: '未开始'
        },
        {
          value: 2,
          label: '进行中'
        },
        {
          value: 3,
          label: '已终止'
        },
        {
          value: 4,
          label: '已结束'
        },
        {
          value: 5,
          label: '欠费暂停'
        }
      ],
      money: 0,
      canCreate: 0,
      statusPoint: {
        1: 'dm-status--info',
        2: 'dm-status--primary--flash',
        3: 'dm-status--error',
        4: 'dm-status--info',
        5: 'dm-status--warning'
      }
    };
  },
  created() {
    if (window.location.host != 'gicdev.demogic.com' && !window.location.host.includes('localhost')) {
      this.cardContent.splice(2, 1);
    }
  },
  mounted() {
    this.getTableData();
    this.getRechargeCenter();
    this.getAiAccountCheck();
  },
  activated() {
    if (this.$route.meta.refresh) {
      this.form = {
        activityName: '',
        scene: '',
        activityPlanStatus: '',
        time: [],
        pageNum: 1,
        pageSize: 20
      };
    }
    this.getTableData();
  },
  beforeRouteEnter(to, from, next) {
    const {
      meta: { type, path, refresh }
    } = from;
    if (path !== '/list') {
      to.meta.refresh = true;
    } else {
      if (type === 'add' && refresh) {
        to.meta.refresh = true;
      } else {
        to.meta.refresh = false;
      }
    }
    next();
  },
  filters: {
    activePlanStatusFilter(val) {
      let str = '- -';
      switch (val) {
        case 1:
          str = '未开始';
          break;
        case 2:
          str = '进行中';
          break;
        case 3:
          str = '已终止';
          break;
        case 4:
          str = '已结束';
          break;
        case 5:
          str = '欠费暂停';
          break;
      }
      return str;
    },
    yesOrnoFilter(val) {
      let str = '- -';
      switch (val) {
        case 0:
          str = '否';
          break;
        case 1:
          str = '是';
          break;
      }
      return str;
    },
    // 金额处理 保留2位小数
    // 金额处理 保留2位小数
    amount(value) {
      if (!value) return '0.00';
      if (isNaN(value)) return value;
      return value.toFixed(2);
    }
  },
  methods: {
    create(scene, id) {
      if (!this.canCreate) {
        this.$confirm(`当前账户已无可用余额，请充值后再${id ? '复制' : '创建'}外呼任务`, '提示', {
          confirmButtonText: '去充值',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.recharge();
        });
      } else {
        id ? this.$router.push('/ai/copy/' + id) : this.$router.push('/ai/add/' + scene);
      }
    },

    recharge() {
      window.open(`${window.location.origin}/marketing/#/recharge/do`, '_blank');
    },
    // 获取余额
    async getRechargeCenter() {
      const { result } = await rechargeCenter();
      this.money = result.account.balance;
    },
    search() {
      this.form.pageNum = 1;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.form.pageSize = val;
      this.form.pageNum = 1;
      this.getTableData();
    },
    async getAiAccountCheck() {
      const { result } = await aiAccountCheck();
      console.log(result);
      this.canCreate = result;
    },
    async getTableData() {
      this.loading = true;
      const params = Object.assign({}, this.form);
      if (params.time && params.time.length) {
        params.startTime = formatDateTimeByType(params.time[0], 'yyyy-MM-dd');
        params.endTime = formatDateTimeByType(params.time[1], 'yyyy-MM-dd');
      }
      delete params.time;

      const { result } = await page(params);
      if (!result) return;
      this.tableData = result.list || [];
      const ids = this.tableData.map(item => item.activityId).join(',');
      this.total = result.total;
      this.pageStatistics(ids);
    },
    async pageStatistics(ids) {
      try {
        const { result } = await pageStatistics({ ids });
        if (!result) return;
        let obj = {};
        result.forEach(element => {
          obj[element.activityId] = element;
        });
        this.tableData.forEach(item => {
          if (obj[item.activityId]) {
            const { marketingNumber, outboundNumber, totalConnectionNumber, telephoneConnectionRate, connectionIntentionRate } = obj[item.activityId];
            item.marketingNumber = marketingNumber;
            item.outboundNumber = outboundNumber;
            item.totalConnectionNumber = totalConnectionNumber;
            item.telephoneConnectionRate = telephoneConnectionRate;
            item.connectionIntentionRate = connectionIntentionRate;
          } else {
            item.marketingNumber = '- -';
            item.outboundNumber = '- -';
            item.totalConnectionNumber = '- -';
            item.telephoneConnectionRate = '- -';
            item.connectionIntentionRate = '- -';
          }
        });
        this.tableData = this.tableData.splice(0);
      } finally {
        this.loading = false;
      }
    },
    stopTask(row) {
      this.$confirm('任务终止后未外呼的客户将停止外呼任务，终止后不可重新启用任务，是否继续终止任务？', '提示', {
        confirmButtonText: '终止',
        cancelBUttonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        stopActivityPlan({ planId: row.planId })
          .then(res => {
            this.$message.success('操作成功');
            this.getTableData();
          })
          .finally(_ => {
            this.loading = false;
          });
      });
    },
    rebootTask(row) {
      this.$confirm('重新开启任务后，将会对未外呼的客户进行外呼，是否确定重新开启营销活动？', '提示', {
        confirmButtonText: '确定',
        cancelBUttonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        startActivityPlan({ planId: row.planId })
          .then(res => {
            this.$message.success('操作成功');
            this.getTableData();
          })
          .finally(_ => {
            this.loading = false;
          });
      });
    },
    editPlan(row) {
      this.$router.push('/ai/edit/' + row.activityId);
    }
  }
};
</script>

<style lang="scss" scoped>
.contain {
  margin: 0 20px;
  .cardList {
    display: flex;
    .card {
      width: 20%;
      height: 140px;
      background: #f0f3fd;
      border-radius: 4px;
      padding: 12px 16px;
      box-sizing: border-box;
      margin-right: 12px;
      &:last-child {
        margin-right: 0;
      }
    }
    .cardTitle {
      i {
        font-size: 20px;
        opacity: 0.8;
        color: #2f54eb;
      }
      span {
        font-size: 16px;
        margin-left: 10px;
        font-weight: 500;
        line-height: 22px;
      }
    }
    .cardBody {
      margin: 6px 0 12px 0;
      font-size: 14px;
      line-height: 20px;
      height: 40px;
      color: #606266;
    }
  }
  .account {
    margin: 20px 0;
    span {
      font-weight: 500;
      color: #303133;
      line-height: 20px;
      font-size: 14px;
      margin-right: 10px;
    }
  }
  .searchWarp {
    margin-bottom: 20px;
    .el-form.table-page-search-wrapper {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 10px;
      flex-wrap: wrap;
      .el-form-item {
        margin: 0;
      }
    }
  }
}
</style>
