<template>
  <div class="app-container ai-sip-call-phone">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="86px"
      class="search-form"
    >
      <el-form-item label="销售公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择销售公司"
          clearable
          filterable
          size="small"
          class="filter-control"
          @change="handleQuery"
        >
          <el-option
            v-for="company in companyList"
            :key="company.companyId"
            :label="company.companyName"
            :value="company.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务名称" prop="batchId">
        <el-select
          v-model="queryParams.batchId"
          placeholder="请选择任务名称"
          clearable
          filterable
          size="small"
          class="filter-control"
        >
          <el-option
            v-for="task in aiCallTaskList"
            :key="task.remoteBatchId"
            :label="task.batchName"
            :value="task.remoteBatchId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="加密号码" prop="telephone">
        <el-input
          v-model="queryParams.telephone"
          placeholder="请输入加密号码"
          clearable
          size="small"
          class="filter-control"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="外呼状态" prop="callstatus">
        <el-select
          v-model="queryParams.callstatus"
          placeholder="外呼状态"
          clearable
          filterable
          size="small"
          class="filter-control filter-control--status"
        >
          <el-option
            v-for="item in callStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行类型" prop="executeType">
        <el-select
          v-model="queryParams.executeType"
          placeholder="执行类型"
          clearable
          size="small"
          class="filter-control filter-control--status"
        >
          <el-option label="销售端企微sop" value="0" />
          <el-option label="总后台客服sop" value="1" />
          <el-option label="总后台app提醒看板" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="通话分钟">
        <div class="time-range">
          <el-input-number
            v-model="queryParams.timeLenStart"
            :min="0"
            placeholder="最小值"
            size="small"
            controls-position="right"
            class="minute-input"
          />
          <span class="range-separator">至</span>
          <el-input-number
            v-model="queryParams.timeLenEnd"
            :min="0"
            placeholder="最大值"
            size="small"
            controls-position="right"
            class="minute-input"
          />
        </div>
      </el-form-item>
      <el-form-item label="外呼时间">
        <el-date-picker
          v-model="calloutTimeRange"
          type="datetimerange"
          size="small"
          class="callout-time-picker"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="['00:00:00', '23:59:59']"
          :picker-options="calloutPickerOptions"
          @change="handleCalloutTimeChange"
        />
      </el-form-item>
      <el-form-item class="search-actions">
        <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 toolbar-row">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:aiSipCall:phone:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      border
      stripe
      v-loading="loading"
      :data="aiSipCallList"
      class="phone-table"
      :header-cell-style="headerCellStyle"
    >
      <el-table-column label="销售公司" align="center" prop="companyName" min-width="120" show-overflow-tooltip />
      <el-table-column label="任务名称" align="center" prop="batchName" min-width="140" show-overflow-tooltip />
      <el-table-column label="线路名称" align="center" prop="gatewayName" min-width="110" show-overflow-tooltip />
      <el-table-column label="执行类型" align="center" prop="executeType" min-width="150">
        <template slot-scope="scope">
          <el-tag
            v-if="executeTypeMeta(scope.row.executeType)"
            size="mini"
            effect="plain"
            :type="executeTypeMeta(scope.row.executeType).type"
          >{{ executeTypeMeta(scope.row.executeType).label }}</el-tag>
          <span v-else>{{ scope.row.executeType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员昵称" align="center" prop="fsUserNickName" min-width="110" show-overflow-tooltip />
      <el-table-column label="外部联系人" align="center" prop="externalUserName" min-width="110" show-overflow-tooltip />
      <el-table-column label="外呼号码" align="center" prop="telephone" min-width="120" show-overflow-tooltip />
      <el-table-column label="外呼状态" align="center" prop="callstatusName" min-width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag
            size="mini"
            effect="plain"
            :type="callStatusTagType(scope.row)"
          >{{ scope.row.callstatusName || '-' }}</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="客户意向" align="center" prop="intent" min-width="100" show-overflow-tooltip />-->
      <el-table-column label="外呼时间" align="center" prop="calloutTimeStr" min-width="160" />
<!--      <el-table-column label="接通时间" align="center" prop="answeredTimeStr" min-width="160" />-->
<!--      <el-table-column label="挂机时间" align="center" prop="callEndTimeStr" min-width="160" />-->
<!--      <el-table-column label="创建时间" align="center" prop="createtimeStr" min-width="160" />-->
      <el-table-column label="总时长" align="center" prop="timeLenSec" width="90" />
      <el-table-column label="挂机原因" align="center" prop="hangupCause" min-width="110" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="168" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div v-if="scope.row.wavfile" class="op-actions">
            <button
              type="button"
              class="op-chip op-chip--play"
              v-hasPermi="['his:aiSipCall:phone:downloadVoice']"
              @click="openPlayDialog(scope.row)"
            >
              <i class="el-icon-video-play"></i>
              <span>播放</span>
            </button>
            <button
              type="button"
              class="op-chip op-chip--download"
              v-hasPermi="['his:aiSipCall:phone:downloadVoice']"
              :disabled="downloadLoading && downloadTarget === scope.row.wavfile"
              @click="downloadVoice(scope.row)"
            >
              <i :class="downloadLoading && downloadTarget === scope.row.wavfile ? 'el-icon-loading' : 'el-icon-download'"></i>
              <span>下载</span>
            </button>
          </div>
          <span v-else class="op-empty">—</span>
        </template>
      </el-table-column>
    </el-table>

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

    <sip-recording-play-dialog
      ref="playDialog"
      :visible.sync="playDialogVisible"
      :title="playDialogTitle"
      :subtitle="playMeta.subtitle"
      :audio-url="playAudioUrl"
      :audio-loading="audioLoading"
      :messages="visibleChatMessages"
      :total-count="chatMessages.length"
      :page-size="chatPageSize"
      :has-more="hasMoreChat"
      :can-collapse="canCollapseChat"
      @close="closePlayDialog"
      @load-more="loadMoreChat"
      @collapse="collapseChat"
    />
  </div>
</template>

<script>
import { listAiSipCallPhone, exportAiSipCallPhone } from "@/api/aiSipCall/aiSipCallPhone";
import { listAiSipCallTask } from "../../api/aiSipCall/aiSipCallTask";
import { listCompany } from "../../api/company/company";
import sipRecordingPlayback from "./mixins/sipRecordingPlayback";
import SipRecordingPlayDialog from "./components/SipRecordingPlayDialog";

export default {
  name: "aiSipCallPhone",
  components: { SipRecordingPlayDialog },
  mixins: [sipRecordingPlayback],
  data() {
    const todayStart = this.getTodayStart();
    const todayEnd = this.getTodayEnd();
    return {
      loading: true,
      exportLoading: false,
      showSearch: true,
      total: 0,
      aiCallTaskList: [],
      aiSipCallList: [],
      companyList: [],
      calloutTimeRange: [todayStart, todayEnd],
      headerCellStyle: {
        background: '#f7f9fc',
        color: '#303133',
        fontWeight: 600
      },
      calloutPickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const start = new Date();
              start.setHours(0, 0, 0, 0);
              const end = new Date();
              end.setHours(23, 59, 59, 999);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近3天',
            onClick(picker) {
              const end = new Date();
              end.setHours(23, 59, 59, 999);
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
              start.setHours(0, 0, 0, 0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近7天',
            onClick(picker) {
              const end = new Date();
              end.setHours(23, 59, 59, 999);
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              start.setHours(0, 0, 0, 0);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeLenStart: undefined,
        timeLenEnd: undefined,
        calloutTimeStart: todayStart,
        calloutTimeEnd: todayEnd,
        batchId: null,
        telephone: null,
        callstatus: null,
        executeType: null,
        status: 0,
        companyId: null
      },
      callStatusOptions: [
        { value: 0, label: '未拨打' },
        { value: 1, label: '已进入呼叫队列' },
        { value: 2, label: '正在拨号' },
        { value: 3, label: '未接通（如果关闭空号检测）' },
        { value: 4, label: '已接通' },
        { value: 5, label: '通话中断' },
        { value: 6, label: '成功转人工或 AI' },
        { value: 7, label: '线路故障' },
        { value: 30, label: '未接通' },
        { value: 31, label: '客户正在通话中' },
        { value: 32, label: '关机' },
        { value: 33, label: '空号' },
        { value: 34, label: '无人接听' },
        { value: 35, label: '停机' },
        { value: 36, label: '网络忙' },
        { value: 37, label: '语音助手' },
        { value: 38, label: '暂时无法接通' },
        { value: 39, label: '呼叫限制' }
      ]
    };
  },
  created() {
    listAiSipCallTask({ taskType: 1, status: 0, pageNum: 1, pageSize: 100 }).then(response => {
      this.aiCallTaskList = response.rows;
    });
    listCompany().then(response => {
      this.companyList = response.rows;
      this.queryParams.companyId = undefined;
      this.getList();
    });
  },
  methods: {
    getTodayStart() {
      const now = new Date();
      return now.getFullYear() + '-' +
             String(now.getMonth() + 1).padStart(2, '0') + '-' +
             String(now.getDate()).padStart(2, '0') + ' 00:00:00';
    },
    getTodayEnd() {
      const now = new Date();
      return now.getFullYear() + '-' +
        String(now.getMonth() + 1).padStart(2, '0') + '-' +
        String(now.getDate()).padStart(2, '0') + ' 23:59:59';
    },
    syncCalloutTimeToQuery() {
      if (this.calloutTimeRange && this.calloutTimeRange.length === 2) {
        this.queryParams.calloutTimeStart = this.calloutTimeRange[0];
        this.queryParams.calloutTimeEnd = this.calloutTimeRange[1];
      } else {
        this.queryParams.calloutTimeStart = null;
        this.queryParams.calloutTimeEnd = null;
      }
    },
    handleCalloutTimeChange() {
      this.syncCalloutTimeToQuery();
    },
    executeTypeMeta(type) {
      const map = {
        '0': { label: '销售端企微sop', type: '' },
        '1': { label: '总后台客服sop', type: 'success' },
        '2': { label: '总后台app提醒看板', type: 'warning' }
      };
      return map[type] || null;
    },
    callStatusTagType(row) {
      const status = row.callstatus;
      if (status === 4 || status === 6) return 'success';
      if (status === 2 || status === 1) return '';
      if (status === 5 || status === 7) return 'danger';
      if (status >= 30) return 'info';
      if (status === 0 || status === 3) return 'warning';
      return 'info';
    },
    getList() {
      this.loading = true;
      this.syncCalloutTimeToQuery();
      const queryParams = { ...this.queryParams };
      if (!queryParams.companyId) {
        delete queryParams.companyId;
      }
      listAiSipCallPhone(queryParams).then(response => {
        this.aiSipCallList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      const todayStart = this.getTodayStart();
      const todayEnd = this.getTodayEnd();
      this.calloutTimeRange = [todayStart, todayEnd];
      this.queryParams.calloutTimeStart = todayStart;
      this.queryParams.calloutTimeEnd = todayEnd;
      this.queryParams.timeLenStart = undefined;
      this.queryParams.timeLenEnd = undefined;
      this.queryParams.batchId = null;
      this.queryParams.telephone = null;
      this.queryParams.callstatus = null;
      this.queryParams.executeType = null;
      this.queryParams.companyId = null;
      this.handleQuery();
    },
    handleExport() {
      this.syncCalloutTimeToQuery();
      const queryParams = { ...this.queryParams };
      delete queryParams.pageNum;
      delete queryParams.pageSize;
      if (!queryParams.companyId) {
        delete queryParams.companyId;
      }
      this.$confirm('是否确认导出所有 aiSIP外呼通话记录数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportAiSipCallPhone(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
      });
    }
  }
};
</script>

<style scoped>
.ai-sip-call-phone .search-form {
  margin-bottom: 12px;
  padding: 14px 16px 4px;
  background: #fafbfc;
  border: 1px solid #eef0f3;
  border-radius: 8px;
}

.ai-sip-call-phone .filter-control {
  width: 160px;
}

.ai-sip-call-phone .filter-control--status {
  width: 180px;
}

.ai-sip-call-phone .time-range {
  display: inline-flex;
  align-items: center;
}

.ai-sip-call-phone .minute-input {
  width: 120px;
}

.ai-sip-call-phone .range-separator {
  margin: 0 8px;
  color: #909399;
  font-size: 12px;
}

.ai-sip-call-phone .callout-time-picker {
  width: 360px;
}

.ai-sip-call-phone .search-actions {
  margin-left: 4px;
}

.ai-sip-call-phone .toolbar-row {
  margin-top: 4px;
}

.ai-sip-call-phone .phone-table {
  border-radius: 6px;
  overflow: hidden;
}

.ai-sip-call-phone .op-actions {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.ai-sip-call-phone .op-chip {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  height: 28px;
  padding: 0 10px;
  border: 1px solid transparent;
  border-radius: 14px;
  font-size: 12px;
  line-height: 1;
  cursor: pointer;
  transition: all 0.2s ease;
  outline: none;
  background: transparent;
}

.ai-sip-call-phone .op-chip i {
  font-size: 13px;
}

.ai-sip-call-phone .op-chip--play {
  color: #2f6fed;
  background: #edf4ff;
  border-color: #d6e6ff;
}

.ai-sip-call-phone .op-chip--play:hover {
  color: #fff;
  background: #409eff;
  border-color: #409eff;
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.28);
}

.ai-sip-call-phone .op-chip--download {
  color: #2f9b57;
  background: #eefaf2;
  border-color: #d4f0de;
}

.ai-sip-call-phone .op-chip--download:hover {
  color: #fff;
  background: #67c23a;
  border-color: #67c23a;
  box-shadow: 0 4px 10px rgba(103, 194, 58, 0.28);
}

.ai-sip-call-phone .op-chip:disabled,
.ai-sip-call-phone .op-chip:disabled:hover {
  color: #a8abb2;
  background: #f4f4f5;
  border-color: #e9e9eb;
  box-shadow: none;
  cursor: not-allowed;
}

.ai-sip-call-phone .op-empty {
  color: #c0c4cc;
  font-size: 12px;
}
</style>
