<template>
  <div class="app-container">
    <el-card shadow="never" class="mb16 filter-card">
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small">
      <el-form-item label="租户名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入租户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入员工名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户号码" prop="customerPhone">
        <el-input
          v-model="queryParams.customerPhone"
          placeholder="请输入客户号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <inline-tenant-selector @change="handleQuery" />
      <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-card>

    <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="['admin:callRecord:list']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-document"
          size="mini"
          @click="showQualityTab = true"
        >质检记录</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-bar-chart"
          size="mini"
          @click="showStatistics = true"
        >通话统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="callRecordList" border size="small" style="width:100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="租户名称" align="center" prop="companyName" min-width="120" />
      <el-table-column label="员工名称" align="center" prop="userName" min-width="90" />
      <el-table-column label="客户号码" align="center" prop="customerPhone" min-width="110" />
      <el-table-column label="通话时长" align="center" prop="callTime" min-width="90">
        <template slot-scope="scope">
          {{ formatDuration(scope.row.callTime) }}
        </template>
      </el-table-column>
      <el-table-column label="通话费用" align="center" prop="cost" min-width="90" />
      <el-table-column label="通话时间" align="center" prop="callTimeStr" min-width="150" />
      <el-table-column label="是否有录音" align="center" prop="hasAudio" min-width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.voiceUrl" type="success">有</el-tag>
          <el-tag v-else type="error">无</el-tag>
        </template>
      </el-table-column>
      <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-search"
            plain
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            v-if="scope.row.voiceUrl"
            size="mini"
            type="text"
            icon="el-icon-headphones"
            plain
            @click="handlePlayAudio(scope.row)"
          >播放录音</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            plain
            @click="handleQuality(scope.row)"
            v-hasPermi="['admin:callRecord:addQuality']"
          >质检</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"
    />

    <!-- 详情弹窗 -->
    <el-dialog title="通话记录详情" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-form :model="viewForm" label-width="100px">
        <el-form-item label="租户名称">
          <span>{{ viewForm.companyName }}</span>
        </el-form-item>
        <el-form-item label="员工名称">
          <span>{{ viewForm.userName }}</span>
        </el-form-item>
        <el-form-item label="客户号码">
          <span>{{ viewForm.customerPhone }}</span>
        </el-form-item>
        <el-form-item label="通话时长">
          <span>{{ formatDuration(viewForm.callTime) }}</span>
        </el-form-item>
        <el-form-item label="通话费用">
          <span>{{ viewForm.cost }}</span>
        </el-form-item>
        <el-form-item label="通话时间">
          <span>{{ viewForm.callTimeStr }}</span>
        </el-form-item>
        <el-form-item label="录音播放">
          <audio v-if="viewForm.voiceUrl" :src="viewForm.voiceUrl" controls />
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 质检弹窗 -->
    <el-dialog title="通话质检" :visible.sync="qualityOpen" width="600px" append-to-body>
      <el-form ref="qualityForm" :model="qualityForm" :rules="qualityRules" label-width="100px">
        <el-form-item label="质检结果" prop="qualityResult">
          <el-select v-model="qualityForm.qualityResult" placeholder="请选择质检结果">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
            <el-option label="待审核" value="待审核" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="qualityForm.riskLevel" placeholder="请选择风险等级">
            <el-option label="低" value="低" />
            <el-option label="中" value="中" />
            <el-option label="高" value="高" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题类型" prop="problemType">
          <el-input v-model="qualityForm.problemType" placeholder="请输入问题类型" />
        </el-form-item>
        <el-form-item label="是否报备" prop="isReported">
          <el-radio-group v-model="qualityForm.isReported">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="质检备注" prop="remark">
          <el-textarea v-model="qualityForm.remark" placeholder="请输入质检备注" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitQualityForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 质检记录弹窗 -->
    <el-dialog title="质检记录" :visible.sync="showQualityTab" width="800px" append-to-body>
      <el-table :data="qualityList" border>
        <el-table-column label="租户名称" align="center" prop="companyName" />
        <el-table-column label="员工名称" align="center" prop="userName" />
        <el-table-column label="客户号码" align="center" prop="customerPhone" />
        <el-table-column label="质检结果" align="center" prop="qualityResult">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.qualityResult == '合格'" type="success">合格</el-tag>
            <el-tag v-else-if="scope.row.qualityResult == '不合格'" type="error">不合格</el-tag>
            <el-tag v-else type="warning">待审核</el-tag>
          </template>
        </el-table-column>
      <el-table-column label="报备状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isReported == 1" type="success">已报备</el-tag>
          <el-tag v-else type="info">未报备</el-tag>
        </template>
      </el-table-column>
        <el-table-column label="风险等级" align="center" prop="riskLevel" />
        <el-table-column label="质检时间" align="center" prop="qualityTime" />
        <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-edit"
              plain
              @click="handleEditQuality(scope.row)"
              v-hasPermi="['admin:callRecord:editQuality']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              plain
              @click="handleDeleteQuality(scope.row)"
              v-hasPermi="['admin:callRecord:removeQuality']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 统计弹窗 -->
    <el-dialog title="通话统计" :visible.sync="showStatistics" width="600px" append-to-body>
      <el-card>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="stat-item">
              <span class="stat-value">{{ statistics.totalCount }}</span>
              <span class="stat-label">通话总数</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="stat-item">
              <span class="stat-value">{{ statistics.totalDuration }}</span>
              <span class="stat-label">总通话时长</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="stat-item">
              <span class="stat-value">{{ statistics.totalCost }}</span>
              <span class="stat-label">总通话费用</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="stat-item">
              <span class="stat-value">{{ statistics.qualityCount }}</span>
              <span class="stat-label">已质检数</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import { listAllCallRecords, getCallRecordInfo, addQualityRecord, listQualityRecords, updateQualityRecord, deleteQualityRecord, reportQuality, getCallStatistics, exportCallRecord } from '@/api/admin/callRecord'

import InlineTenantSelector from "@/components/InlineTenantSelector"

export default {
  name: 'CallRecordAdmin',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通话记录列表
      callRecordList: [],
      // 质检记录列表
      qualityList: [],
      // 选中的记录
      ids: [],
      // 统计数据
      statistics: {
        totalCount: 0,
        totalDuration: 0,
        totalCost: 0,
        qualityCount: 0
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        userName: null,
        customerPhone: null
      },
      // 详情弹窗
      viewOpen: false,
      viewForm: {},
      // 质检弹窗
      qualityOpen: false,
      qualityForm: {
        callLogId: null,
        qualityResult: '',
        riskLevel: '',
        problemType: '',
        isReported: 0,
        remark: ''
      },
      qualityRules: {
        qualityResult: [{ required: true, message: '请选择质检结果', trigger: 'blur' }]
      },
      // 质检记录弹窗
      showQualityTab: false,
      // 统计弹窗
      showStatistics: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      listAllCallRecords(this.queryParams).then(response => {
        this.callRecordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 查看详情 */
    handleView(row) {
      getCallRecordInfo(row.logId).then(response => {
        this.viewForm = response.data
        this.viewOpen = true
      })
    },
    /** 播放录音 */
    handlePlayAudio(row) {
      getCallRecordInfo(row.logId).then(response => {
        this.viewForm = response.data
        this.viewOpen = true
      })
    },
    /** 质检 */
    handleQuality(row) {
      this.qualityForm = {
        callLogId: row.logId,
        qualityResult: '',
        riskLevel: '',
        problemType: '',
        isReported: 0,
        remark: ''
      }
      this.qualityOpen = true
    },
    /** 提交质检 */
    submitQualityForm() {
      this.$refs['qualityForm'].validate(valid => {
        if (valid) {
          addQualityRecord(this.qualityForm).then(response => {
            this.$message.success('质检成功')
            this.qualityOpen = false
            this.getList()
          })
        }
      })
    },
    /** 编辑质检 */
    handleEditQuality(row) {
      this.qualityForm = {
        id: row.id,
        callLogId: row.callLogId,
        qualityResult: row.qualityResult,
        riskLevel: row.riskLevel,
        problemType: row.problemType,
        isReported: row.isReported,
        remark: row.remark
      }
      this.qualityOpen = true
    },
    /** 删除质检 */
    handleDeleteQuality(row) {
      this.$confirm('确定删除质检记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQualityRecord(row.id).then(response => {
          this.$message.success('删除成功')
          this.loadQualityList()
        })
      })
    },
    /** 加载质检列表 */
    loadQualityList() {
      listQualityRecords({}).then(response => {
        this.qualityList = response.rows
      })
    },
    /** 查看质检记录 */
    showQualityTabDialog() {
      this.loadQualityList()
      this.showQualityTab = true
    },
    /** 查看统计 */
    showStatisticsDialog() {
      getCallStatistics().then(response => {
        this.statistics = response.data
        this.showStatistics = true
      })
    },
    /** 报备质检 */
    handleReport() {
      if (this.ids.length === 0) {
        this.$message.warning('请选择要报备的通话记录')
        return
      }
      reportQuality(this.ids).then(response => {
        this.$message.success('报备成功')
        this.getList()
      })
    },
    /** 格式化时长 */
    formatDuration(seconds) {
      if (!seconds) return '0秒'
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = seconds % 60
      if (hours > 0) {
        return `${hours}小时${minutes}分${secs}秒`
      } else if (minutes > 0) {
        return `${minutes}分${secs}秒`
      } else {
        return `${secs}秒`
      }
    },
    /** 导出按鈕操作 */
    handleExport() {
      this.exportLoading = true
      exportCallRecord(this.queryParams).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => { this.exportLoading = false })
    },
    /** 选择变化 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logId)
    }
  }
}
</script>

<style scoped>
.stat-item {
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}
.stat-label {
  display: block;
  margin-top: 5px;
  font-size: 14px;
  color: #666;
}
</style>

<style scoped>
.mb8 { margin-bottom: 8px; }
.mb16 { margin-bottom: 16px; }
.filter-card { padding-bottom: 0; }
</style>