<template>
    <div class="app-container">
        <el-row :gutter="24" class="baseInfo">
            <!-- 总记录 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>外呼记录总数</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number total">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.recordCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 成功数 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>外呼成功总数</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number success">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.successRecordCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 今日发送 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>今日外呼</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number today">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.todayCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 今日成功 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>今日成功</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number today-success">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.todaySuccessCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 总接通数 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>总接通数</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number total">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.connectionCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 总未接通数 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>总未接通数</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number total">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.unansweredCallsCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 今日接通 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>今日接通</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number today">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.todayConnectionCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 今日未接通 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>今日未接通</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number today">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.todayUnansweredCallsCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="96px">
            <el-form-item prop="roboticId">
                <el-select
                    v-model="queryParams.roboticId"
                    filterable
                    clearable
                    placeholder="请选择任务"
                    @change="handleQuery"
                    class="task-select"
                >
                    <i slot="prefix" class="el-icon-s-operation"/>

                    <el-option label="所有任务" :value="null"/>
                    <el-option
                        v-for="item in roboticList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <!--            <el-form-item>-->
            <!--                <el-button type="cyan" 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
                    v-hasPermi="['company:addwxlog:list']"
                    type="warning"
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                >导出
                </el-button>
            </el-col>
            <right-toolbar :show-search.sync="showSearch" @queryTable="handleQuery"/>
        </el-row>

        <el-table v-loading="loading" :data="companySendMsgList">
            <!--      <el-table-column label="记录 ID" align="center" prop="logId" width="90" />-->
            <el-table-column label="任务 ID" align="center" prop="roboticId" width="150"/>
            <el-table-column label="任务名称" align="center" prop="roboticName" width="250"/>
            <el-table-column label="总数量" align="center" prop="totalRecordCount" width="150"/>
            <el-table-column label="外呼成功数量" align="center" prop="successCount" width="150"/>
            <el-table-column label="外呼失败数量" align="center" prop="failCount" width="150"/>
            <el-table-column label="外呼中数量" align="center" prop="runningCount" width="150"/>
            <!--      <el-table-column label="销售名称" align="center" prop="companyUserName" width="180" />-->
            <!--      <el-table-column label="花费金额" align="center" prop="cost" />-->
            <!--      <el-table-column label="手机号" align="center" prop="phone" />-->
            <!--      <el-table-column label="短信模版名称" align="center" prop="smsTempName" />-->
            <!--      <el-table-column label="内容长度" align="center" prop="contentLen" />-->
            <!--      <el-table-column label="公司" align="center" prop="companyName" />-->
            <!--      <el-table-column label="添加时间" align="center" prop="addTime" />-->

            <!--      <el-table-column label="状态" align="center" prop="status" width="100">-->
            <!--        <template slot-scope="scope">-->
            <!--          <el-tag :type="getStatusType(scope.row.status)">-->
            <!--            {{ getStatusLabel(scope.row.status) }}-->
            <!--          </el-tag>-->
            <!--        </template>-->
            <!--      </el-table-column>-->
            <!--      <el-table-column label="执行时间" align="center" prop="runTime" width="180">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{ parseTime(scope.row.runTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed ="right">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="handleViewDetail(scope.row)"
                    >
                        查看详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog
            :title="detailTitle"
            :visible.sync="detailDialogVisible"
            width="90%"
            append-to-body
            @close="handleDetailClose"
        >
            <!-- 筛选条件 -->
            <el-form
                :model="detailQueryParams"
                ref="detailQueryForm"
                :inline="true"
                size="small"
                label-width="100px"
                class="detail-query-form"
            >
                <!--                <el-form-item label="调用时间">-->
                <!--                    <el-date-picker-->
                <!--                        v-model="detailTimeRange"-->
                <!--                        type="daterange"-->
                <!--                        range-separator="至"-->
                <!--                        start-placeholder="开始日期"-->
                <!--                        end-placeholder="结束日期"-->
                <!--                        value-format="yyyy-MM-dd"-->
                <!--                        clearable-->
                <!--                    />-->
                <!--                </el-form-item>-->

                <el-form-item label="手机号">
                    <el-input
                        v-model="detailQueryParams.phone"
                        placeholder="请输入手机号"
                        clearable
                        @keyup.enter.native="handleDetailQuery"
                    />
                </el-form-item>

                <el-form-item label="是否接通">
                    <el-select
                        v-model="detailQueryParams.isConnected"
                        placeholder="请选择"
                        clearable
                        @change="handleDetailQuery"
                    >
                        <el-option label="是" :value="1" />
                        <el-option label="否" :value="0" />
                    </el-select>
                </el-form-item>

                <el-form-item label="客户类型">
                    <el-select
                        v-model="detailQueryParams.intention"
                        placeholder="请选择"
                        clearable
                        @change="handleDetailQuery"
                    >
                        <el-option
                            v-for="dict in intentionOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="通话时长(秒)">
                    <div class="call-time-range">
                        <el-input
                            v-model="detailQueryParams.minCallTime"
                            placeholder="最小时长"
                            clearable
                            @keyup.enter.native="handleDetailQuery"
                        />
                        <span class="range-separator">至</span>
                        <el-input
                            v-model="detailQueryParams.maxCallTime"
                            placeholder="最大时长"
                            clearable
                            @keyup.enter.native="handleDetailQuery"
                        />
                    </div>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleDetailQuery">
                        查询
                    </el-button>
                    <el-button icon="el-icon-refresh" @click="resetDetailQuery">
                        重置
                    </el-button>
                    <el-button
                        v-hasPermi="['company:callphonelog:exportPhone']"
                        type="warning"
                        icon="el-icon-download"
                        :loading="detailExportLoading"
                        @click="handleDetailExport"
                    >
                        导出
                    </el-button>
                </el-form-item>
            </el-form>

            <el-table
                v-loading="detailLoading"
                :data="detailList"
                border
                style="width: 100%"
            >
                <el-table-column label="日志ID" align="center" prop="logId" width="70" />
                <el-table-column label="任务名称" align="center" prop="roboticName" min-width="80" show-overflow-tooltip />
                <el-table-column label="运行时间" align="center" prop="runTime" width="160" />
                <el-table-column label="外呼状态" align="center" prop="status" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status === 1" type="warning">执行中</el-tag>
                        <el-tag v-else-if="scope.row.status === 2" type="success">成功</el-tag>
                        <el-tag v-else-if="scope.row.status === 3" type="danger">失败</el-tag>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否接通" align="center" prop="isConnected" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.callTime > 0" type="success">是</el-tag>
                        <el-tag v-else type="danger">否</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="客户号码" align="center" prop="callerNum" width="180">
                    <template slot-scope="scope">
                        <span>{{ scope.row.callerNum || '--' }}</span>
                        <el-button
                            v-if="scope.row.callerNum || scope.row.customerId"
                            v-hasPermi="['crm:customer:queryPhone']"
                            type="text"
                            size="mini"
                            icon="el-icon-view"
                            @click="handleQueryPhone(scope.row)"
                        >查看</el-button>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="话术号码" align="center" prop="calleeNum" width="120" /> -->
                <el-table-column label="客户类型" align="center" prop="intention" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.intention" v-for="dict in intentionOptions" :key="dict.dictValue" v-show="scope.row.intention == dict.dictValue" size="mini">{{ dict.dictLabel }}</el-tag>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column label="时长(秒)" align="center" prop="callTime" width="80" />
                <!-- <el-table-column label="金额" align="center" prop="cost" width="70" /> -->
                <el-table-column label="公司名称" align="center" prop="companyName" min-width="100" show-overflow-tooltip />
                <el-table-column label="销售名称" align="center" prop="companyUserName" min-width="80" show-overflow-tooltip />
                <el-table-column label="录音" align="center" show-overflow-tooltip width="350">
                    <template slot-scope="scope">
                        <audio v-if="scope.row.recordPath" controls :src="handleRecordPath(scope.row.recordPath)"></audio>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
              <el-table-column label="敏感词检测" align="center" prop="isWarning" width="100">
                <template slot-scope="scope">
                  <el-tag
                    v-if="scope.row.isWarning === 1"
                    type="danger"
                    class="warning-tag-clickable"
                    @click="handleViewChat(scope.row)"
                  >
                    <el-tooltip content="点击查看聊天记录" placement="top">
                      <span><i class="el-icon-warning" />异常</span>
                    </el-tooltip>
                  </el-tag>
                  <el-tag v-else type="success">正常</el-tag>
                </template>
              </el-table-column>
                <el-table-column label="对话内容" align="center" width="90">
                    <template slot-scope="scope">
                        <el-button
                            v-if="scope.row.contentList"
                            size="mini"
                            type="text"
                            @click="handleViewChat(scope.row)"
                        >
                            查看对话
                        </el-button>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <pagination
                v-show="detailTotal > 0"
                :total="detailTotal"
                :page.sync="detailQueryParams.pageNum"
                :limit.sync="detailQueryParams.pageSize"
                @pagination="getDetailList"
            />

            <div slot="footer" class="dialog-footer">
                <el-button @click="detailDialogVisible = false">关 闭</el-button>
            </div>
        </el-dialog>

        <!-- 聊天记录对话弹窗 -->
        <el-dialog
            title="通话详情"
            :visible.sync="chatDialogVisible"
            width="720px"
            append-to-body
            custom-class="chat-dialog"
            @close="handleChatClose"
        >
            <!-- 统计条 -->
            <div class="chat-summary" v-if="chatList.length > 0">
                <div class="chat-summary-item">
                    <span class="chat-summary-label">总条数：</span>
                    <span class="chat-summary-value">{{ chatList.length }}</span>
                </div>
                <div class="chat-summary-item">
                    <span class="chat-summary-label">机器人：</span>
                    <span class="chat-summary-value blue">{{ chatStats.agentCount }}</span>
                </div>
                <div class="chat-summary-item">
                    <span class="chat-summary-label">用户：</span>
                    <span class="chat-summary-value green">{{ chatStats.userCount }}</span>
                </div>
                <div class="chat-summary-item">
                    <span class="chat-summary-label">敏感词命中（条数）：</span>
                    <span class="chat-summary-value red">{{ chatStats.sensitiveCount }}</span>
                </div>
            </div>

            <div class="chat-container" v-if="chatList.length > 0">
                <div
                    v-for="(item, index) in chatList"
                    :key="index"
                    class="chat-item"
                    :class="item.role === 'agent' ? 'chat-item-right' : 'chat-item-left'"
                >
                    <div class="chat-avatar">
                        <div
                            class="chat-avatar-circle"
                            :class="item.role === 'agent' ? 'avatar-agent' : 'avatar-user'"
                        >
                            <i :class="item.role === 'agent' ? 'el-icon-headset' : 'el-icon-user-solid'" />
                        </div>
                    </div>
                    <div class="chat-content-wrap">
                        <div class="chat-role-line">
                            <span class="chat-role">{{ item.role === 'agent' ? '机器人' : '用户' }}</span>
                            <span class="chat-index">#{{ index + 1 }}</span>
                        </div>
                        <div class="chat-bubble" v-html="item.content"></div>
                    </div>
                </div>
            </div>
            <el-empty v-else description="暂无通话内容" />
            <div slot="footer" class="dialog-footer">
                <span class="chat-footer-tip">标红内容为命中的敏感词</span>
                <el-button @click="chatDialogVisible = false">关 闭</el-button>
            </div>
        </el-dialog>

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

<script>
import {listCallphone, listCallPhoneByRoboticId, delSendmsg, getCallPhoneLogCount, exportCallphone, exportDetailPhone, queryCallphoneLogPhone, groupList} from '@/api/company/callphone'
import { queryPhone } from '@/api/crm/customer'
import {listAll as roboticListAll} from '@/api/company/companyVoiceRobotic'
import {listAll as accountListAll} from '@/api/company/companyAccount'
import CountTo from 'vue-count-to'

export default {
    name: 'WxClientStatistics',
    components: {CountTo},
    data() {
        return {
            loading: false,
            showSearch: true,
            total: 0,
            companySendMsgList: [],
            roboticList: [],
            accountList: [],
            count: {},
            totalRecordCount: 0,
            successRecordCount: 0,
            detailDialogVisible: false,
            detailLoading: false,
            detailExportLoading: false,
            detailList: [],
            detailTitle: "查看详情",
            detailTimeRange: [],
            detailTotal: 0,
            intentionOptions: [],
            chatDialogVisible: false,
            chatList: [],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                roboticId: null,
                wxAccountId: null,
                customerIdId: null,
                status: null,
                time: []
            },
            detailQueryParams: {
                pageNum: 1,
                pageSize: 10,
                roboticId: null,
                phone: null,
                isConnected: null,
                intention: null,
                minCallTime: null,
                maxCallTime: null,
                beginRunTime: null,
                endRunTime: null
            },
            loadingCount: false
        }
    },
    created() {
        this.initOptions()
        this.handleQuery()
        this.getCount()
        this.getDicts('customer_intention_level').then(response => {
            this.intentionOptions = response.data
        })
    },
    computed: {
        chatStats() {
            const stats = { agentCount: 0, userCount: 0, sensitiveCount: 0 }
            const list = this.chatList || []
            list.forEach(item => {
                if (item.role === 'agent') stats.agentCount++
                else stats.userCount++
                const content = item.content || ''
                const matches = content.match(/<span[^>]*class="sensitive-word"[^>]*>/g)
                if (matches) stats.sensitiveCount += matches.length
            })
            return stats
        }
    },
    methods: {
        initOptions() {
            roboticListAll().then((res) => {
                this.roboticList = res.data || []
            })
            accountListAll().then((res) => {
                this.accountList = res.data || []
            })
        },
        getQueryData() {
            const params = JSON.parse(JSON.stringify(this.queryParams))
            if (params.time && params.time.length === 2) {
                params.beginTime = params.time[0]
                params.endTime = params.time[1]
            }
            delete params.time
            return params
        },
        getList() {
            this.loading = true
            groupList(this.getQueryData())
                .then((response) => {
                    this.companySendMsgList = response.rows || []
                    this.total = response.total || 0
                    this.successRecordCount = response.successRecordCount || 0
                    this.totalRecordCount = response.totalRecordCount || 0
                })
                .finally(() => {
                    this.loading = false
                })
        },
        // statis() {
        //   addWxStatistics(this.getQueryData()).then((res) => {
        //     this.count = res || {}
        //   })
        // },
        getStatusLabel(value) {
            if (value === 1) return '执行中'
            if (value === 2) return '成功'
            if (value === 3) return '失败'
            return '-'
        },
        getStatusType(value) {
            if (value === 1) return 'warning'
            if (value === 2) return 'success'
            if (value === 3) return 'danger'
            return 'info'
        },
        handleQuery() {
            this.queryParams.pageNum = 1
            // this.statis()
            this.getList()
        },
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        handleExport() {
            const queryParams = this.getQueryData()
            this.$confirm('是否确认导出查询出的短链课程看课记录数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.exportLoading = true;
                return exportCallphone(queryParams)
            }).then((response) => {
                this.download(response.msg)
                this.exportLoading = false;
            }).catch(() => {
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.logId || this.ids;
            this.$confirm('是否确认删除编号为 "' + ids + '" 的加微信日志数据项？', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delSendmsg(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(function () {
            });
        },
        /** 点击查看详情 */
        handleViewDetail(row) {
            this.detailTitle = `查看详情 - ${row.roboticName || ""}`;
            this.detailDialogVisible = true;

            this.detailQueryParams.pageNum = 1;
            this.detailQueryParams.pageSize = 10;
            this.detailQueryParams.callerId = row.callerId;
            this.detailQueryParams.roboticId = row.roboticId;
            this.detailQueryParams.phone = null;
            this.detailQueryParams.isConnected = null;
            this.detailQueryParams.intention = null;
            this.detailQueryParams.minCallTime = null;
            this.detailQueryParams.maxCallTime = null;
            this.detailQueryParams.beginRunTime = null;
            this.detailQueryParams.endRunTime = null;
            this.detailTimeRange = [];

            this.getDetailList();
        },

        /** 查询详情分页列表 */
        getDetailList() {
            this.detailLoading = true;
            listCallPhoneByRoboticId(this.detailQueryParams).then(response => {

                this.detailList = response.rows || [];
                this.detailTotal = response.total || 0;
                this.detailLoading = false;
            }).catch(() => {
                this.detailLoading = false;
            });
        },
        handleDetailQuery() {
            this.detailQueryParams.pageNum = 1;

            if (this.detailTimeRange && this.detailTimeRange.length === 2) {
                this.detailQueryParams.beginRunTime = this.detailTimeRange[0];
                this.detailQueryParams.endRunTime = this.detailTimeRange[1];
            } else {
                this.detailQueryParams.beginRunTime = null;
                this.detailQueryParams.endRunTime = null;
            }

            this.detailQueryParams.minCallTime = this.parseCallTime(this.detailQueryParams.minCallTime);
            this.detailQueryParams.maxCallTime = this.parseCallTime(this.detailQueryParams.maxCallTime);

            this.getDetailList();
        },
        resetDetailQuery() {
            this.detailTimeRange = [];
            this.detailQueryParams.pageNum = 1;
            this.detailQueryParams.pageSize = 10;
            this.detailQueryParams.phone = null;
            this.detailQueryParams.isConnected = null;
            this.detailQueryParams.intention = null;
            this.detailQueryParams.minCallTime = null;
            this.detailQueryParams.maxCallTime = null;
            this.detailQueryParams.beginRunTime = null;
            this.detailQueryParams.endRunTime = null;
            this.getDetailList();
        },
        getDetailExportParams() {
            const params = JSON.parse(JSON.stringify(this.detailQueryParams));
            delete params.pageNum;
            delete params.pageSize;
            params.minCallTime = this.parseCallTime(params.minCallTime);
            params.maxCallTime = this.parseCallTime(params.maxCallTime);
            return params;
        },
        /** 查看解密手机号（与 CRM 客户详情一致） */
        handleQueryPhone(row) {
            const customerId = row.customerId;
            if (customerId) {
                queryPhone(customerId).then(response => {
                    this.$alert(response.mobile, '手机号', {
                        confirmButtonText: '确定'
                    });
                });
                return;
            }
            if (row.logId) {
                queryCallphoneLogPhone(row.logId).then(response => {
                    this.$alert(response.mobile, '手机号', {
                        confirmButtonText: '确定'
                    });
                });
                return;
            }
            this.$message.warning('无法查看手机号');
        },
        handleDetailExport() {
            this.$confirm('是否确认导出当前筛选条件下的外呼记录（含解密手机号）？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.detailExportLoading = true;
                return exportDetailPhone(this.getDetailExportParams());
            }).then((response) => {
                this.download(response.msg);
            }).finally(() => {
                this.detailExportLoading = false;
            }).catch(() => {});
        },
        /** 获取统计数据 */
        getCount() {
            this.loadingCount = true;
            getCallPhoneLogCount().then(res => {
                this.count = res.data || {};
                this.loadingCount = false;
            }).catch(() => {
                this.loadingCount = false;
            });
        },
        handleDetailClose() {
            this.detailList = [];
            this.detailTotal = 0;
            this.detailTimeRange = [];
            this.detailQueryParams = {
                pageNum: 1,
                pageSize: 10,
                callerId: null,
                roboticId: null,
                phone: null,
                isConnected: null,
                intention: null,
                minCallTime: null,
                maxCallTime: null,
                beginRunTime: null,
                endRunTime: null
            };
        },
        handleRecordPath(url) {
            if (!url) return '';
            let fullUrl = '';
            if (url.startsWith('http')) {
                fullUrl = url;
            } else {
                fullUrl = 'http://129.28.164.235:8899/recordings/files?filename=' + url;
            }
            return process.env.VUE_APP_BASE_API + '/common/proxy/recording?url=' + encodeURIComponent(fullUrl);
        },
        parseCallTime(val) {
            if (val === null || val === undefined || val === '') return null;
            var num = Number(val);
            if (isNaN(num) || num < 0) return null;
            return num;
        },
        handleShowContent(row) {
            // 兑现为统一到聊天详情弹窗（保留名称以防外部引用）
            this.handleViewChat(row);
        },
        parseContentList(content) {
            if (!content) return [];
            try {
                const parsed = typeof content === 'string' ? JSON.parse(content) : content;
                if (!Array.isArray(parsed)) return [];
                return parsed.filter(item => {
                    if (!item) return false;
                    if (this.isSystemChatRole(item.role)) return false;
                    const text = item.content || '';
                    if (!String(text).trim()) return false;
                    return true;
                }).map(item => ({
                    ...item,
                    role: this.normalizeChatRole(item.role || item.speaker || item.from)
                }));
            } catch (e) {
                console.error('解析 contentList 失败', e);
                return [];
            }
        },
        isSystemChatRole(role) {
            return String(role || '').toLowerCase() === 'system';
        },
        normalizeChatRole(role) {
            const r = String(role || '').toLowerCase();
            if (r === 'agent' || r === 'robot' || r === 'ai' || r === 'bot' || r === 'assistant') {
                return 'agent';
            }
            if (r === 'user' || r === 'customer' || r === 'client' || r === 'human') {
                return 'user';
            }
            return 'user';
        },
        /** 查看聊天记录 */
        handleViewChat(row) {
            const raw = row.contentList;
            let list = [];
            if (raw) {
                try {
                    list = typeof raw === 'string' ? JSON.parse(raw) : raw;
                } catch (e) {
                    list = [];
                }
            }
            const filtered = (Array.isArray(list) ? list : []).filter(item => {
                if (!item) return false;
                if (this.isSystemChatRole(item.role)) return false;
                const text = item.content || '';
                return !!String(text).trim();
            }).map(item => ({
                ...item,
                role: this.normalizeChatRole(item.role || item.speaker || item.from)
            }));
            this.chatList = filtered;
            this.chatDialogVisible = true;
        },
        handleChatClose() {
            this.chatList = [];
        },
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.baseInfo {
    margin-bottom: 30px;
}

.content {
    .card-panel-num {
        display: inline-block;
        font-size: 30px;
    }

    &-time {
        font-size: 14px;
    }
}

.task-select .el-input__inner {
    background-color: #ecf5ff;
    border: 1px solid #409EFF;
    border-radius: 20px;
    height: 36px;
    padding-left: 15px;
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.1);
    transition: all 0.2s;
}

.task-select .el-input__inner:hover {
    border-color: #66b1ff;
}

.task-select .el-input.is-focus .el-input__inner {
    border-color: #409EFF;
    box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
    background-color: #ffffff;
}

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

.call-time-range .el-input {
    width: 100px;
}

.range-separator {
    margin: 0 6px;
    color: #909399;
}

/* 卡片整体 */
.stat-card {
    border-radius: 10px;
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-3px);
}

/* 标题 */
.card-header {
    font-size: 14px;
    color: #666;
}

/* 内容区域 */
.content {
    height: 60px;
    display: flex;
    align-items: center;
}

/* 数字基础样式 */
.card-number {
    font-size: 28px;
    font-weight: bold;
}

/* 🎨 颜色区分 */
.card-number.total {
    color: #409EFF; /* 蓝色 */
}

.card-number.success {
    color: #67C23A; /* 绿色 */
}

.card-number.today {
    color: #E6A23C; /* 橙色 */
}

.card-number.today-success {
    color: #F56C6C; /* 红色 */
}

.content-dialog-wrapper {
    padding: 0 10px;
}

.content-empty {
    text-align: center;
    color: #909399;
    padding: 40px 0;
}

.chat-container {
    max-height: 600px;
    overflow-y: auto;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 8px;
}

.chat-item {
    display: flex;
    margin-bottom: 14px;
}

.chat-left {
    justify-content: flex-start;
}

.chat-right {
    justify-content: flex-end;
}

.chat-bubble-wrapper {
    max-width: 75%;
}

.chat-role {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
}

.chat-left .chat-role {
    text-align: left;
}

.chat-right .chat-role {
    text-align: right;
}

.chat-bubble {
    padding: 10px 14px;
    border-radius: 12px;
    font-size: 14px;
    line-height: 1.6;
    word-break: break-word;
    white-space: pre-wrap;
}

.chat-left .chat-bubble {
    background: #fff;
    border: 1px solid #ebeef5;
    color: #303133;
}

.chat-right .chat-bubble {
    background: #409eff;
    color: #fff;
}

/* 警告标签可点击 */
.warning-tag-clickable {
    cursor: pointer;
    transition: all 0.2s;
}

.warning-tag-clickable:hover {
    opacity: 0.85;
    transform: scale(1.05);
}
</style>

<style lang="scss">
/* 聊天弹窗（全局样式，以便 v-html 渲染的敏感词样式生效） */
.chat-dialog {
    /* 锁定弹窗不超出视口，避免外层 wrapper 产生滚动条 */
    margin-top: 5vh !important;
    margin-bottom: 5vh !important;
    max-height: 90vh;
    display: flex;
    flex-direction: column;

    .el-dialog__header {
        flex-shrink: 0;
    }

    .el-dialog__body {
        padding: 0;
        background-color: #f5f7fa;
        max-height: calc(90vh - 54px - 60px);
        overflow-y: auto;
        flex: 1;
    }

    .el-dialog__footer {
        flex-shrink: 0;

        .dialog-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chat-footer-tip {
            font-size: 12px;
            color: #909399;
        }
    }

    /* 统计条 */
    .chat-summary {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 24px;
        padding: 12px 20px;
        background-color: #fff;
        border-bottom: 1px solid #ebeef5;
        position: sticky;
        top: 0;
        z-index: 2;

        .chat-summary-item {
            font-size: 13px;
            color: #606266;
        }
        .chat-summary-label {
            color: #909399;
        }
        .chat-summary-value {
            font-weight: 600;
            color: #303133;

            &.blue { color: #409EFF; }
            &.green { color: #67C23A; }
            &.red { color: #f56c6c; }
        }
    }

    .chat-container {
        display: flex;
        flex-direction: column;
        padding: 16px 20px 8px;
    }

    .chat-item {
        display: flex;
        margin-bottom: 14px;
        align-items: flex-start;
    }

    /* 用户在左 */
    .chat-item-left {
        justify-content: flex-start;

        .chat-avatar { margin-right: 10px; }
        .chat-content-wrap { align-items: flex-start; }
        .chat-role-line { justify-content: flex-start; }
        .chat-bubble {
            background-color: #ffffff;
            color: #303133;
            border: 1px solid #ebeef5;
            border-radius: 2px 8px 8px 8px;
        }
        .chat-role { color: #67C23A; }
    }

    /* 销售在右 */
    .chat-item-right {
        flex-direction: row-reverse;
        justify-content: flex-start;

        .chat-avatar { margin-left: 10px; }
        .chat-content-wrap { align-items: flex-end; }
        .chat-role-line {
            justify-content: flex-end;
            flex-direction: row-reverse;
        }
        .chat-bubble {
            background-color: #ecf5ff;
            color: #303133;
            border: 1px solid #d9ecff;
            border-radius: 8px 2px 8px 8px;
        }
        .chat-role { color: #409EFF; }
    }

    /* 头像 */
    .chat-avatar-circle {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 18px;
        flex-shrink: 0;

        &.avatar-agent { background-color: #409EFF; }
        &.avatar-user { background-color: #67C23A; }
    }

    .chat-content-wrap {
        display: flex;
        flex-direction: column;
        max-width: 70%;
    }

    .chat-role-line {
        display: flex;
        align-items: center;
        margin-bottom: 4px;
        gap: 8px;
    }

    .chat-role {
        font-size: 12px;
        font-weight: 500;
    }

    .chat-index {
        font-size: 12px;
        color: #c0c4cc;
    }

    .chat-bubble {
        padding: 8px 12px;
        font-size: 14px;
        line-height: 1.6;
        word-break: break-word;
        max-width: 100%;

        .sensitive-word {
            color: #f56c6c !important;
            font-weight: 600;
            background-color: rgba(245, 108, 108, 0.12);
            padding: 0 3px;
            border-radius: 2px;
        }
    }
}
</style>
