<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="任务名称" prop="batchId">
        <el-select v-model="queryParams.batchId" placeholder="请选择任务名称" clearable size="small" style="width: 150px">
          <el-option
            v-for="task in aiCallTaskList"
            :key="task.batchId"
            :label="task.batchName"
            :value="task.batchId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户意向" prop="intent">
        <el-select v-model="queryParams.intent" placeholder="请选择客户意向" clearable size="small" style="width: 140px">
          <el-option label="全部" value=""/>
          <el-option label="A" value="A"/>
          <el-option label="B" value="B"/>
          <el-option label="C" value="C"/>
          <el-option label="D" value="D"/>
          <el-option label="E" value="E"/>
          <el-option label="F" value="F"/>
          <el-option label="G" value="G"/>
        </el-select>
      </el-form-item>
      <el-form-item label="外呼号码" prop="telephone">
        <el-input
          v-model="queryParams.telephone"
          placeholder="请输入外呼号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          style="width: 150px"
        />
      </el-form-item>
      <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="通话分钟">
        <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.calloutTimeStart" 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.calloutTimeEnd" 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.callEndTimeStart" 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.callEndTimeEnd" 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="primary"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['company:aiSipCall:phone:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-sync"
          size="mini"
          @click="handleManualPull"
          v-hasPermi="['company:aiSipCall:phone:manualPull']"
        >同步今天数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="aiSipCallList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="外呼任务id" align="center" prop="batchId"/>
      <el-table-column label="外呼任务" align="center" prop="batchName"/>
      <el-table-column label="通话uuid" align="center" prop="uuid"/>
      <el-table-column label="外呼号码" align="center" prop="telephone"/>
      <el-table-column label="外呼状态" align="center" prop="callstatusName"/>
      <el-table-column label="外呼时间" align="center" prop="calloutTimeStr"/>
      <el-table-column label="接通时间" align="center" prop="answeredTimeStr"/>
      <el-table-column label="挂机时间" align="center" prop="callEndTimeStr"/>
      <el-table-column label="通话总时长" align="center" prop="timeLenSec"/>
      <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.wavfile)"
            v-hasPermi="['company:aiSipCall:phone:downloadVoice']"
            v-if="scope.row.wavfile"
            style="color: #409EFF;"
          >播放
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="downloadVoice(scope.row.wavfile)"
            v-hasPermi="['company:aiSipCall:phone:downloadVoice']"
            v-if="scope.row.wavfile"
            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 {
  listAiSipCallPhone,
  addAiSipCallPhone,
  delAiSipCallPhone,
  exportAiSipCallPhone,
  getAiSipCallPhone,
  updateAiSipCallPhone,
  manualPull
} from "@/api/aiSipCall/aiSipCallPhone";
import {listAiSipCallTask} from "../../api/aiSipCall/aiSipCallTask";

export default {
  name: "aiSipCallPhone",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // aiSIP 外呼任务列表
      aiCallTaskList: [],
      // aiSIP 外呼通话记录表格数据
      aiSipCallList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前播放的音频对象
      currentAudio: null,
      // 音频服务器基础 URL
      AUDIO_BASE_URL: 'http://129.28.164.235:8899',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeLenStart: undefined,
        timeLenEnd: undefined,
        calloutTimeStart: null,
        calloutTimeEnd: null,
        answeredTimeStart: null,
        answeredTimeEnd: null,
        callEndTimeStart: this.getTodayStart(),
        callEndTimeEnd: null,
        batchId: null,
        telephone: null,
        custName: null,
        createtime: null,
        callstatus: null,
        calloutTime: null,
        callcount: null,
        callEndTime: null,
        timeLen: null,
        validTimeLen: null,
        uuid: null,
        connectedTime: null,
        hangupCause: null,
        answeredTime: null,
        dialogue: null,
        wavfile: null,
        recordServerUrl: null,
        bizJson: null,
        dialogueCount: null,
        acdOpnum: null,
        acdQueueTime: null,
        acdWaitTime: null,
        ttsText: null,
        emptyNumberDetectionText: null,
        intent: null,
        asrSeconds: null,
        ttsTimes: null,
        ttsFlowTokens: null,
        inputTokens: null,
        outputTokens: null,
        totalCost: null,
        billingStatus: null,
        callerNumber: null,
        ivrDtmfDigits: null,
        manualAnsweredTime: null,
        manualAnsweredTimeLen: null,
        remoteCallPhoneId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    //获取所有 ai 外呼任务
    listAiSipCallTask({taskType: 1}).then(response => {
      this.aiCallTaskList = response.rows;
    })
    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';
    },
    // 获取当前时间（yyyy-MM-dd HH:mm:ss）
    getCurrentTime() {
      const now = new Date();
      return now.getFullYear() + '-' +
             String(now.getMonth() + 1).padStart(2, '0') + '-' +
             String(now.getDate()).padStart(2, '0') + ' ' +
             String(now.getHours()).padStart(2, '0') + ':' +
             String(now.getMinutes()).padStart(2, '0') + ':' +
             String(now.getSeconds()).padStart(2, '0');
    },
    handleManualPull(){
      manualPull().then(response => {
        if(response.code === 200){
          this.msgSuccess(response.msg);
        }else{
          this.msgError(response.msg);
        }
        this.getList();
      })
    },
    /** 构建完整的音频 URL */
    buildAudioUrl(wavfile) {
      if (!wavfile) return '';
      return wavfile.startsWith('http') ? wavfile : this.AUDIO_BASE_URL + wavfile;
    },
    /** 获取文件名 */
    getFileName(url) {
      if (!url) return 'audio.wav';
      return url.split('/').pop() || 'audio.wav';
    },
    /** 播放语音文件 */
    playVoice(wavfile) {
      // 非空校验
      if (!wavfile) {
        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(wavfile);

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

      audio.onloadedmetadata = () => {
      };

      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(wavfile) {
      // 非空校验
      if (!wavfile) {
        this.$message.error('录音文件不存在');
        return;
      }

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

      // 创建临时下载链接
      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);
    },
    /** 查询 aiSIP 外呼通话记录列表 */
    getList() {
      this.loading = true;
      listAiSipCallPhone(this.queryParams).then(response => {
        this.aiSipCallList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        timeLenStart: null,
        timeLenEnd: null,
        calloutTimeStart: null,
        calloutTimeEnd: null,
        answeredTimeStart: null,
        answeredTimeEnd: null,
        callEndTimeStart: null,
        callEndTimeEnd: null,
        batchId: null,
        telephone: null,
        custName: null,
        createtime: null,
        callstatus: null,
        calloutTime: null,
        callcount: null,
        callEndTime: null,
        timeLen: null,
        validTimeLen: null,
        uuid: null,
        connectedTime: null,
        hangupCause: null,
        answeredTime: null,
        dialogue: null,
        wavfile: null,
        recordServerUrl: null,
        bizJson: null,
        dialogueCount: null,
        acdOpnum: null,
        acdQueueTime: null,
        acdWaitTime: null,
        ttsText: null,
        emptyNumberDetectionText: null,
        intent: null,
        asrSeconds: null,
        ttsTimes: null,
        ttsFlowTokens: null,
        inputTokens: null,
        outputTokens: null,
        totalCost: null,
        billingStatus: 0,
        callerNumber: null,
        ivrDtmfDigits: null,
        manualAnsweredTime: null,
        manualAnsweredTimeLen: null,
        remoteCallPhoneId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.calloutTimeStart = null;
      this.queryParams.calloutTimeEnd = null;
      this.queryParams.timeLenStart = undefined;
      this.queryParams.timeLenEnd = undefined;
      this.queryParams.answeredTimeStart = null;
      this.queryParams.answeredTimeEnd = null;
      this.queryParams.callEndTimeStart = this.getTodayStart();
      this.queryParams.callEndTimeEnd = null;
      this.queryParams.batchId = null;
      this.queryParams.telephone = null;
      this.queryParams.uuid = null;
      this.queryParams.intent = 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
      getAiSipCallPhone(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) {
            updateAiSipCallPhone(this.form).then(() => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAiSipCallPhone(this.form).then(() => {
              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 delAiSipCallPhone(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有 aiSIP外呼通话记录数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportAiSipCallPhone(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
  }
};
</script>
