<template>
  <div class="data-detail">
    <div v-if="analyseFlag" class="page-tip">活动转化金额每天更新 1 次</div>
    <el-input v-model="search.search" @change="handleCurrentChange(1)" type="text" placeholder="请输入姓名/昵称/手机号/会员卡号" prefix-icon="el-icon-search" clearable class="search-bar"></el-input>
    <el-button class="fr" type="primary" icon="iconfont fz14 icon-cp-xiazai" v-if="$getButtonLimit($buttonCode.marketingAiDetailExport)" :limit-code="$buttonCode.marketingAiDetailExport" @click="exportExcel" size="small" :disabled="!total"> 查询结果导出</el-button>
    <el-table :data="tableData" v-loading="loading" @sort-change="handleSortChange">
      <el-table-column label="基本信息" min-width="200px" show-overflow-tooltip fixed="left" v-if="scene != 5">
        <div slot-scope="{ row }" class="member-info">
          <img class="member-logo" v-if="row.memberImage" :src="row.memberImage" alt="" />
          <svg aria-hidden="true" v-else class="member-logo">
            <use xlink:href="#icon-user-default"></use>
          </svg>
          <div>
            <p class="member-name">
              <template v-if="row.memberNick">
                {{ row.memberNick || '--' }}
              </template>
              <span class="member-subname" v-if="row.memberName">
                {{ row.memberNick ? `(${row.memberName})` : row.memberName }}
              </span>
            </p>
            <p class="member-name" v-if="row.memberMobile">{{ row.memberMobile }}</p>
          </div>
        </div>
      </el-table-column>
      <el-table-column label="手机号码" min-width="146px" prop="memberMobile" show-overflow-tooltip fixed="left" v-else></el-table-column>
      <el-table-column min-width="113px" v-if="scene == 5">
        <template #header>
          新会员
          <el-tooltip placement="top">
            <div slot="content">
              <p>1、是：通过本次活动开卡新会员</p>
              <p>2、否：未开卡注册会员或老会员；</p>
            </div>
            <i class="iconfont icon-QuestionCircleOutlined"></i>
          </el-tooltip>
        </template>
        <div style="line-height: 20px" slot-scope="{ row }">
          {{ row.isNewMember == 1 ? '是' : '否' }}
        </div>
      </el-table-column>
      <el-table-column label="会员卡号" min-width="130px" prop="memberCard" show-overflow-tooltip :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="会员等级" min-width="90px" v-if="scene != 5" prop="memberGradeName" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="服务门店" min-width="190px" prop="mainStoreName" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="通话状态" min-width="80px" prop="aiThirdStatus" show-overflow-tooltip :formatter="(row, col, val) => formatAiStatus(val)"></el-table-column>
      <el-table-column label="通话时长" min-width="80px" prop="aiDurationSec" :formatter="(row, col, val) => (val > 0 ? `${val}s` : '0s')"></el-table-column>
      <el-table-column label="意向标签" min-width="130px" prop="aiLabel" sortable="custom" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column v-if="analyseFlag" label="活动转化金额(实付)" min-width="180px" prop="orderPayAmount" sortable="custom" :formatter="(row, col, val) => (val == null ? '--' : val)"></el-table-column>
      <el-table-column label="外呼时间" min-width="100px" prop="aiTime">
        <div style="line-height: 20px" slot-scope="{ row }">
          <p>{{ formatDateTimeByType(row.aiTime, 'yyyy-MM-dd') || '--' }}</p>
          <p>{{ formatDateTimeByType(row.aiTime, 'HH:mm:ss') || '--' }}</p>
        </div>
      </el-table-column>
      <el-table-column v-if="showSendTime" label="短信发送时间" min-width="110px" prop="smsSendTime" fixed="right">
        <div style="line-height: 20px" slot-scope="{ row }">
          <p>{{ formatDateTimeByType(row.smsSendTime, 'yyyy-MM-dd') || '--' }}</p>
          <p>{{ formatDateTimeByType(row.smsSendTime, 'HH:mm:ss') || '--' }}</p>
        </div>
      </el-table-column>
      <el-table-column min-width="100px">
        <template #header>
          通话记录
          <el-tooltip placement="top">
            <div slot="content">
              录音有效期90天，失效后按钮置灰
            </div>
            <i class="iconfont icon-QuestionCircleOutlined"></i>
          </el-tooltip>
        </template>
        <template slot-scope="{ row }">
          <el-tooltip placement="top">
            <div slot="content">
              查看记录
            </div>
            <el-button size="small" type="text" @click="handleRecord(row)" v-if="row.aiTelRecordText"><i class="iconfont fz14 icon-chakanxiangqing-copy"></i> </el-button>
          </el-tooltip>

          <el-tooltip placement="top">
            <div slot="content">
              {{ row.aiTelRecordText && !row.aiTelRecordUrl ? '录音已过期' : '播放录音' }}
            </div>
            <el-button size="small" type="text" @click="handleListen(row)" v-if="row.aiTelRecordText" :disabled="row.aiTelRecordText && !row.aiTelRecordUrl">
              <i :class="['iconfont fz14', row.isPlay ? 'icon-zanting' : 'icon-kaiqi']"></i>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="通话记录" :visible.sync="recordVisible" width="600px" class="dialog-wrap">
      <div v-html="aiTelRecordText" class="recordContent"></div>
    </el-dialog>
    <vue-gic-export-excel :dialogVisible.sync="dialogVisible" :dataArr="tableData" :type="2" :excelUrl="excelUrl" :params="params" :projectName="projectName"></vue-gic-export-excel>
    <dm-pagination v-if="total > 0" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :total="total" :current-page="search.pageNum" :page-size="search.pageSize" :page-sizes="[20, 40, 60, 80]" layout="total, sizes, prev, pager, next"></dm-pagination>
  </div>
</template>

<script>
import { formatDateTimeByType } from '@/utils/index.js';
import { getCustomDetail, exportAiCustomDetail } from '@/service/api/aiApi.js';
const music = new Audio();
export default {
  name: 'AiDataDetail',
  data() {
    return {
      formatDateTimeByType,
      showSendTime: false,
      analyseFlag: false,
      aiTelRecordText: '',
      recordVisible: false,
      search: {
        activityId: '',
        search: '', // 姓名、昵称 、手机号、会员卡号
        pageNum: 1,
        pageSize: 20,
        orderBy: ''
      },
      scene: '',
      tableData: [],
      total: 0,
      loading: false,
      dialogVisible: false,
      excelUrl: '', // 下载数据的地址
      params: {} // 传递的参数
    };
  },
  created() {
    this.search.activityId = this.$route.params.id;
    this.showSendTime = this.$route.query.flag == 1;
    this.analyseFlag = this.$route.query.analyseFlag == 1;
    this.scene = this.$route.query.scene;
    this.getData();
    console.log('mounted3');
  },
  mounted() {
    music.addEventListener('ended', () => {
      music.currentTime = 0;
      this.tableData.forEach(item => {
        item.isPlay = false;
      });
      this.tableData = this.tableData.splice(0);
    });
  },
  methods: {
    exportExcel() {
      this.params = {
        search: this.search.search,
        analyseFlag: this.analyseFlag ? 1 : 0,
        smsFlag: this.showSendTime ? 1 : 0,
        activityId: this.search.activityId,
        orderBy: this.search.orderBy
      };
      this.dialogVisible = true;
      this.excelUrl = exportAiCustomDetail;
    },
    handleRecord(row) {
      this.recordVisible = true;
      this.aiTelRecordText = row.aiTelRecordText;
    },
    handleListen(row) {
      this.tableData
        .filter(item => item.id != row.id)
        .forEach(item => {
          item.isPlay = false;
        });
      let bool = row.isPlay;
      bool = !bool;
      music.src = row.aiTelRecordUrl;
      if (bool) {
        music
          .play()
          .then(_ => {
            row.isPlay = !row.isPlay;
            this.tableData = this.tableData.splice(0);
          })
          .catch(err => {
            this.$message.warning('录音链接已失效，有效期90天');
          });
      } else {
        music.pause();
        row.isPlay = !row.isPlay;
        this.tableData = this.tableData.splice(0);
      }
    },
    handleSortChange(data) {
      const { prop, order } = data;
      console.log(order);
      if (order == 'descending') {
        this.search.orderBy = prop + ' desc';
      } else if (order === 'ascending') {
        this.search.orderBy = prop + ' asc';
      } else {
        this.search.orderBy = undefined;
      }
      this.search.pageNum = 1;
      this.getData();
    },
    getData() {
      this.loading = true;
      getCustomDetail(this.search)
        .then(res => {
          const { result, totalCount } = res.result || {};
          this.total = totalCount;
          this.tableData = result;

          this.tableData.forEach((item, index) => {
            item.isPlay = false;
            item.id = index;
            // if (index % 2) {
            //   item.aiTelRecordUrl = 'https://byrobot-prod.oss-cn-hangzhou.aliyuncs.com/RobotPhoneCommunicate/20220725/20220725TFuFsG8136020144q.mp3';
            // } else {
            //   item.aiTelRecordUrl = 'https://byrobot-prod.oss-cn-hangzhou.aliyuncs.com/RobotPhoneCommunicate/20220725/20220725TFuFsG8136020144.mp3';
            // }
            // item.aiTelRecordUrl = null;
            // item.aiTelRecordText = 'AI:你出行了吗<br><br用户:喂<br><br>AI:好的，这边不打扰了<br><br用户:嗯<br><br>AI:抱歉，暂时没听清您的问题<br><br您刚刚说什么来着?<br><brAI:你出行了吗<br><br用户:喂<br><br>AI:好的，这边不打扰了<br>用户:嗯<br><br>';
          });

          // this.tableData = [
          //   {
          //     smsSendTime: 1647852104000, //短信发送时间
          //     aiStatus: 2, //AI状态1已提交2已删除3已接通4线路问题5被叫问题
          //     aiThirdStatus: 5, //第三方：已完成通话状态    0:已接听,1:拒接,2:无法接通,3:外呼失败,4:空号,5:关机,6:占线,7:停机,8:未接,9:主叫欠费,10:呼损,11:黑名单,12:天盾拦截,22:线路盲区,23呼出拦截,25:无可用线路(可选线路为空、线路超频等)
          //     aiTime: 1647852101000, //外呼时间
          //     aiDuration: 2, //'时长分钟(计费)
          //     aiDurationSec: 66, //时长秒
          //     aiLabel: 'A级(有明确意向)', //ai回调会员标签
          //     orderPayAmount: 0, //订单实付总金额
          //     memberImage: '', //会员头像
          //     memberName: '', //会员姓名
          //     memberNick: '', //会员Nick
          //     memberMobile: '18368612362', //会员手机号
          //     memberCard: '', //会员卡号
          //     memberGradeName: '', //等级名称
          //     mainStoreName: '', //主门店名称
          //     mainStoreCode: '',
          //     aiTelRecordText: 'AI:你出行了吗<br><br用户:喂<br><br>AI:好的，这边不打扰了<br><br用户:嗯<br><br>AI:抱歉，暂时没听清您的问题<br><br您刚刚说什么来着?<br><brAI:你出行了吗<br><br用户:喂<br><br>AI:好的，这边不打扰了<br>用户:嗯<br><br>',
          //     aiTelRecordUrl: 'https://byrobot-prod.oss-cn-hangzhou.aliyuncs.com/RobotPhoneCommunicate/20220725/20220725TFuFsG8136020144.mp3', //用户通话录音链接
          //     isNewMember: '0 //是否是本次开卡的新会员 0-否 1-是'
          //   }
          // ];
        })
        .finally(() => (this.loading = false));
    },
    handleCurrentChange(pageNum) {
      this.search.pageNum = pageNum;
      this.getData();
    },
    handleSizeChange(pageSize) {
      this.search.pageSize = pageSize;
      this.handleCurrentChange(1);
    },
    formatAiStatus(state) {
      // "aiThirdStatus":5, //第三方：已完成通话状态    0:已接听,1:拒接,2:无法接通,3:外呼失败,4:空号,5:关机,6:占线,7:停机,8:未接,9:主叫欠费,10:呼损,11:黑名单,12:天盾拦截,22:线路盲区,23呼出拦截,25:无可用线路(可选线路为空、线路超频等)
      const status = {
        0: '已接听',
        1: '拒接',
        2: '无法接通',
        3: '外呼失败',
        4: '空号',
        5: '关机',
        6: '占线',
        7: '停机',
        8: '未接',
        9: '主叫欠费',
        10: '呼损',
        11: '黑名单',
        12: '天盾拦截',
        22: '线路盲区',
        23: '呼出拦截',
        25: '无可用线路' //(可选线路为空、线路超频等)
      };
      return status[state] || '--';
    }
  }
};
</script>

<style lang="scss" scoped>
.data-detail {
  padding: 5px 20px 20px 20px;
  .search-bar {
    margin-bottom: 20px;
    width: 290px;
  }
  .recordContent {
    max-height: 700px;
    overflow-y: auto;
  }
  .member-info {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .member-logo {
      flex-shrink: 0;
      margin-right: 10px;
      width: 40px;
      height: 40px;
      border-radius: 40px;
      overflow: hidden;
    }
    .member-name {
      font-size: 14px;
      font-weight: 400;
      color: #303133;
      line-height: 20px;
      .member-subname {
        color: #909399;
      }
    }
  }
}
</style>
