音视频类型<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="86px" class="search-form">
      <el-form-item label="通话 UUID" prop="uuid">
        <el-input
          v-model="queryParams.uuid"
          placeholder="请输入通话 UUID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="被叫号码" prop="callee">
        <el-input
          v-model="queryParams.callee"
          placeholder="请输入被叫号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item label="工号" prop="opnum">
        <el-input
          v-model="queryParams.opnum"
          placeholder="请输入工号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item label="通话时长">
        <div class="time-range">
          <el-input-number v-model="queryParams.timeLenStart" :min="0" placeholder="最小值" size="small"
                           style="width: 130px"/>
          <span class="range-separator">-</span>
          <el-input-number v-model="queryParams.timeLenEnd" :min="0" placeholder="最大值" size="small"
                           style="width: 130px"/>
        </div>
      </el-form-item>
      <el-form-item label="外呼时间">
        <div class="time-range">
          <el-date-picker v-model="queryParams.startTimeStart" size="small" style="width: 190px"
                          value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="开始"/>
          <span class="range-separator">-</span>
          <el-date-picker v-model="queryParams.startTimeEnd" size="small" style="width: 190px"
                          value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="结束"/>
        </div>
      </el-form-item>
      <el-form-item label="接听时间">
        <div class="time-range">
          <el-date-picker v-model="queryParams.answeredTimeStart" size="small" style="width: 190px"
                          value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="开始"/>
          <span class="range-separator">-</span>
          <el-date-picker v-model="queryParams.answeredTimeEnd" size="small" style="width: 190px"
                          value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="结束"/>
        </div>
      </el-form-item>
      <el-form-item label="挂机时间">
        <div class="time-range">
          <el-date-picker v-model="queryParams.endTimeStart" size="small" style="width: 190px"
                          value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="开始"/>
          <span class="range-separator">-</span>
          <el-date-picker v-model="queryParams.endTimeEnd" size="small" style="width: 190px"
                          value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="结束"/>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['platform:aiSipCall:outboundCdr:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleManualPull"
          v-hasPermi="['platform:aiSipCall:outboundCdr:manualPull']"
        >同步今天数据
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="outboundCdrList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="通话UUID" align="center" prop="uuid" />
      <el-table-column label="音视频类型" align="center" prop="callType">
        <template slot-scope="scope">
          <span v-if="scope.row.callType === 'audio'">音频</span>
          <span v-else-if="scope.row.callType === 'video'">视频</span>
          <span v-else>{{ scope.row.callType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工号" align="center" prop="opnum" />
      <el-table-column label="被叫号码" align="center" prop="callee" />
      <el-table-column label="外呼时间" align="center" prop="startTimeStr" />
      <el-table-column label="接听时间" align="center" prop="answeredTimeStr" />
      <el-table-column label="挂断时间" align="center" prop="endTimeStr" />
      <el-table-column label="通话时长" align="center" prop="timeLenSec" />
      <el-table-column label="纯通时长" align="center" prop="timeLenValidStr" />
      <el-table-column label="挂断原因" align="center" prop="hangupCause" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-video-play"-->
<!--            @click="playVoice(scope.row.recordFilename)"-->
<!--            v-hasPermi="['platform:aiSipCall:phone:downloadVoice']"-->
<!--            v-if="scope.row.recordFilename"-->
<!--            style="color: #409EFF;"-->
<!--          >播放-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-download"-->
<!--            @click="downloadVoice(scope.row.recordFilename)"-->
<!--            v-hasPermi="['platform:aiSipCall:phone:downloadVoice']"-->
<!--            v-if="scope.row.recordFilename"-->
<!--            style="color: #67C23A;"-->
<!--          >下载-->
<!--          </el-button>-->
<!--        </template>-->
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { listOutboundCdr, getOutboundCdr, delOutboundCdr, addOutboundCdr, updateOutboundCdr, exportOutboundCdr,manualPull } from "@/api/aiSipCall/aiSipCallOutboundCdr";

export default {
  name: "OutboundCdr",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // aiSIP手动外呼通话记录表格数据
      outboundCdrList: [],
      // 弹出层标题
      title: "",
      // 当前播放的音频对象
      currentAudio: null,
      // 音频服务器基础 URL
      AUDIO_BASE_URL: 'http://129.28.164.235:8899',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caller: null,
        opnum: null,
        timeLenStart: null,
        timeLenEnd: null,

        startTimeStart: null,
        startTimeEnd: null,
        answeredTimeStart: null,
        answeredTimeEnd: null,
        endTimeStart: this.getTodayStart(),
        endTimeEnd: null,
        callee: null,
        startTime: null,
        answeredTime: null,
        endTime: null,
        uuid: null,
        callType: null,
        timeLen: null,
        timeLenValid: null,
        recordFilename: null,
        chatContent: null,
        hangupCause: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取今天开始时间（yyyy-MM-dd 00:00:00）
    getTodayStart() {
      const now = new Date();
      return now.getFullYear() + '-' +
             String(now.getMonth() + 1).padStart(2, '0') + '-' +
             String(now.getDate()).padStart(2, '0') + ' 00:00:00';
    },
    handleManualPull(){
      manualPull().then(response => {
        if(response.code === 200){
          this.msgSuccess(response.msg);
        }else{
          this.msgError(response.msg);
        }
        this.getList();
      })
    },
    /** 查询aiSIP手动外呼通话记录列表 */
    getList() {
      this.loading = true;
      listOutboundCdr(this.queryParams).then(response => {
        this.outboundCdrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        caller: null,
        opnum: null,
        callee: null,
        startTime: null,
        answeredTime: null,
        endTime: null,
        uuid: null,
        callType: null,
        timeLen: null,
        timeLenValid: null,
        recordFilename: null,
        chatContent: null,
        hangupCause: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.startTimeStart = null;
      this.queryParams.startTimeEnd = null;
      this.queryParams.timeLenStart = null;
      this.queryParams.timeLenEnd = null;
      this.queryParams.answeredTimeStart = null;
      this.queryParams.answeredTimeEnd = null;
      this.queryParams.endTimeStart = this.getTodayStart();
      this.queryParams.endTimeEnd = null;
      this.queryParams.uuid = null;
      this.queryParams.callee = null;
      this.queryParams.opnum = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加aiSIP手动外呼通话记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOutboundCdr(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改aiSIP手动外呼通话记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOutboundCdr(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutboundCdr(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除aiSIP手动外呼通话记录编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delOutboundCdr(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有aiSIP手动外呼通话记录数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportOutboundCdr(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },


    /** 构建完整的音频 URL */
    buildAudioUrl(recordFilename) {
      if (!recordFilename) return '';
      return recordFilename.startsWith('http') ? recordFilename : this.AUDIO_BASE_URL + recordFilename;
    },
    /** 获取文件名 */
    getFileName(url) {
      if (!url) return 'audio.wav';
      return url.split('/').pop() || 'audio.wav';
    },
    /** 播放语音文件 */
    playVoice(recordFilename) {
      // 非空校验
      if (!recordFilename) {
        this.$message.error('录音文件不存在');
        return;
      }

      // 如果已有音频在播放，先完全清理
      if (this.currentAudio) {
        this.currentAudio.pause();
        this.currentAudio.src = '';
        this.currentAudio.onloadedmetadata = null;
        this.currentAudio.onerror = null;
        this.currentAudio.onended = null;
        this.currentAudio = null;
      }

      // 创建新的 Audio 对象
      const audio = new Audio();
      this.currentAudio = audio;

      // 构建音频 URL
      audio.src = this.buildAudioUrl(recordFilename);

      // 设置音频类型为 wav
      audio.type = 'audio/wav';

      audio.onloadedmetadata = () => {
        console.log('音频加载成功，时长:', audio.duration, '秒');
      };

      audio.play().catch(err => {
        // 只在非用户主动切换的情况下显示错误提示
        if (this.currentAudio === audio) {
          this.$message.error('音频播放失败：' + (err.message || '请检查网络或文件格式'));
        }else{
          this.$message.error('音频播放失败：' + err);
        }
      });

      // 播放结束后清理
      audio.onended = () => {
        this.currentAudio = null;
      };

      // 错误处理
      audio.onerror = (err) => {
        // 只在当前音频对象仍然是这个时才显示错误（避免切换时的误报）
        if (this.currentAudio === audio) {
          this.$message.error('无法播放录音：' + (err.message || '未知错误'));
          this.currentAudio = null;
        }else{
          this.$message.error('音频加载失败：' + err);
        }
      };
    },
    /** 下载语音文件 */
    downloadVoice(recordFilename) {
      // 非空校验
      if (!recordFilename) {
        this.$message.error('录音文件不存在');
        return;
      }

      // 构建完整的音频 URL
      const audioUrl = this.buildAudioUrl(recordFilename);

      // 创建临时下载链接
      const link = document.createElement('a');
      link.href = audioUrl;
      link.setAttribute('download', this.getFileName(audioUrl));
      link.target = '_blank'; // 在新窗口打开

      // 添加到 DOM 并触发点击
      document.body.appendChild(link);
      link.click();

      // 清理 DOM
      document.body.removeChild(link);
    },
  }
};
</script>
