<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="任务名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入任务名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <!-- <el-form-item label="机器人" prop="robot">
              <el-select v-model="queryParams.robot" filterable clearable>
                <el-option v-for="item in robotList" :label="item.name + '('+item.num+')'" :value="item.id"/>
              </el-select>
            </el-form-item> -->
            <el-form-item label="任务类型" prop="taskType">
                <el-select v-model="queryParams.taskType" filterable clearable>
                    <el-option v-for="item in taskTypeList" :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
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['system:companyVoiceRobotic:add']"
                >新增
                </el-button>
            </el-col>
            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          type="danger"-->
            <!--          icon="el-icon-delete"-->
            <!--          size="mini"-->
            <!--          :disabled="multiple"-->
            <!--          @click="handleDelete"-->
            <!--          v-hasPermi="['system:companyVoiceRobotic:remove']"-->
            <!--        >删除-->
            <!--        </el-button>-->
            <!--      </el-col>-->
            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          type="warning"-->
            <!--          icon="el-icon-download"-->
            <!--          size="mini"-->
            <!--          @click="handleExport"-->
            <!--          v-hasPermi="['system:companyVoiceRobotic:export']"-->
            <!--        >导出-->
            <!--        </el-button>-->
            <!--      </el-col>-->
            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          type="success"-->
            <!--          icon="el-icon-refresh"-->
            <!--          size="mini"-->
            <!--          @click="updateStatusFun"-->
            <!--          v-hasPermi="['system:companyVoiceRobotic:list']"-->
            <!--        >更新状态-->
            <!--        </el-button>-->
            <!--      </el-col>-->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="roboticList">
            <el-table-column label="ID" align="center" prop="id"/>
            <el-table-column label="任务名称" align="center" prop="name"/>
            <el-table-column label="任务流程" align="center" prop="name">
                <template slot-scope="scope">
                    <el-tag v-for="item in workflowList" v-if="scope.row.companyAiWorkflowId == item.value">{{item.label}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="加微方式" align="center" prop="dialogId">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.addType == 0">平均</el-tag>
                    <el-tag v-if="scope.row.addType == 1">意向</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="添加类型" align="center" prop="isWeCom">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.isWeCom == 1">个微</el-tag>
                    <el-tag v-if="scope.row.isWeCom == 2">企微</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="任务类型" align="center" prop="taskType">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.taskType == 1">普通任务</el-tag>
                    <el-tag v-if="scope.row.taskType == 2">场景任务 - {{scope.row.sceneTypeName}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="生效时间段" align="center" prop="taskType" width="250">
                <template slot-scope="scope">
                    <div v-if="scope.row.taskType == 1">
                        {{scope.row.runtimeRangeStart}} ~ {{scope.row.runtimeRangeEnd}}
                    </div>
                    <div v-if="scope.row.taskType == 2" >
                        <div v-if="!!scope.row.availableStartTime && !!scope.row.availableEndTime ">
                            适用：{{scope.row.availableStartTime}} ~ {{scope.row.availableEndTime}}
                        </div>
                        <div v-if="!!scope.row.runtimeRangeStart && !!scope.row.runtimeRangeEnd">
                            运行：{{scope.row.runtimeRangeStart}} ~ {{scope.row.runtimeRangeEnd}}
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="任务状态" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.taskStatus == 0">未启动</el-tag>
                    <el-tag v-if="scope.row.taskStatus == 1" type="warning">执行中</el-tag>
                    <el-tag v-if="scope.row.taskStatus == 2" type="danger">任务暂停</el-tag>
                    <el-tag v-if="scope.row.taskStatus == 3" type="success">执行完成</el-tag>
                </template>
            </el-table-column>
            <!--      <el-table-column label="外呼状态" align="center">-->
            <!--        <template slot-scope="scope">-->
            <!--          <div v-loading="loadingStatus">-->
            <!--            <p v-if="statusObj.hasOwnProperty(scope.row.taskId)">-->
            <!--              <el-tag v-if="statusObj[scope.row.taskId].runningStatus == 0">未启动</el-tag>-->
            <!--              <el-tag v-if="statusObj[scope.row.taskId].runningStatus == 1">运行中</el-tag>-->
            <!--              <el-tag v-if="statusObj[scope.row.taskId].runningStatus == 2">已暂停</el-tag>-->
            <!--              <el-tag v-if="statusObj[scope.row.taskId].runningStatus == 3">已停止</el-tag>-->
            <!--            </p>-->
            <!--            <p v-if="!statusObj.hasOwnProperty(scope.row.taskId)"><el-tag>空</el-tag></p>-->
            <!--          </div>-->
            <!--        </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"
                        @click="calleesOpen(scope.row.id)"
                        v-hasPermi="['system:companyVoiceRobotic:list']"
                    >客户列表</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        @click="wxOpen(scope.row.id,scope.row.isWeCom)"
                        v-hasPermi="['system:companyVoiceRobotic:list']"
                    >加微管理</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-document"
                        @click="showExecLogs(scope.row)"
                        v-hasPermi="['system:companyVoiceRobotic:list']"
                    >执行日志</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        v-if="scope.row.taskStatus == 0"
                        :loading="actionLoading[scope.row.id + '_taskRun']"
                        @click="taskRunFun(scope.row.id)"
                    >启动任务</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        v-if="scope.row.taskStatus == 1"
                        :loading="actionLoading[scope.row.id + '_pause']"
                        @click="handlePauseTask(scope.row)"
                    >暂停任务</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        v-if="scope.row.taskStatus == 2"
                        :loading="actionLoading[scope.row.id + '_resume']"
                        @click="handleResumeTask(scope.row)"
                    >继续任务</el-button>
                    <!-- <el-button
                      size="mini"
                      type="text"
                      v-if="statusObj.hasOwnProperty(scope.row.taskId) && (statusObj[scope.row.taskId].runningStatus == 0 || statusObj[scope.row.taskId].runningStatus == 3)"
                      @click="startRoboticFun(scope.row.taskId)"
                      v-hasPermi="['system:companyVoiceRobotic:list']"
                    >开启外呼任务</el-button> -->
                    <el-button
                        size="mini"
                        type="text"
                        v-if="statusObj.hasOwnProperty(scope.row.taskId) && (statusObj[scope.row.taskId].runningStatus == 1 || statusObj[scope.row.taskId].runningStatus == 2)"
                        :loading="actionLoading[scope.row.taskId + '_stop']"
                        @click="stopRoboticFun(scope.row.taskId)"
                        v-hasPermi="['system:companyVoiceRobotic:list']"
                    >停止任务</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        v-if="scope.row.taskType == 1 && scope.row.taskStatus == 1"
                        :loading="actionLoading[scope.row.id + '_append']"
                        @click="handleAppendCustomers(scope.row)"
                    >追加客户</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        :loading="actionLoading[scope.row.id + '_delete']"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['system:companyVoiceRobotic:remove']"
                    >删除
                    </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-drawer size="45%" :title="title" :visible.sync="open" width="500px" append-to-body class="task-form-drawer">
            <div class="drawer-content">
                <el-form ref="form" :model="form" :rules="rules" label-width="90px" class="task-form">
                    <div class="form-section" >
                        <div class="section-title">
                            <i class="el-icon-document"></i>
                            <span>任务类型</span>
                        </div>
                        <el-form-item label="任务类型" prop="taskType">
                            <el-select v-model="form.taskType" filterable placeholder="请选择任务类型" @change="taskTypeChange()">
                                <el-option v-for="item in taskTypeList" :key="item.id" :label="item.name" :value="item.id"/>
                            </el-select>
                        </el-form-item>
                    </div>

                    <div class="form-section" v-if="form.taskType === 1" >
                        <div class="section-title">
                            <i class="el-icon-document"></i>
                            <span>基本信息</span>
                        </div>
                        <el-form-item label="任务名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入任务名称" clearable/>
                        </el-form-item>
                        <el-form-item label="拨打客户" prop="userIds">
                            <el-button icon="el-icon-user" @click="openSelect">
                                选择客户
                                <el-tag v-if="form.userIds && form.userIds.length" type="primary" size="small" style="margin-left: 8px;">
                                    {{ form.userIds.length }}
                                </el-tag>
                            </el-button>
                        </el-form-item>
                        <el-form-item label="任务流程" prop="companyAiWorkflowId">
                            <el-select v-model="form.companyAiWorkflowId" filterable placeholder="请选择任务流程" @change="onWorkflowChange">
                                <el-option v-for="item in workflowList" :key="item.value" :label="item.label" :value="item.value"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="运行时间" required>
                            <el-col :span="11">
                                <el-form-item prop="runtimeRangeStart">
                                    <el-time-select
                                        placeholder="任务运行开始时间"
                                        style="width: 100%;"
                                        v-model="form.runtimeRangeStart"
                                        key="runtimeRangeStart"
                                        :picker-options="{
                    start: '07:00',
                    step: '00:30',
                    end: '22:00'
                  }">
                                    </el-time-select>
                                </el-form-item>
                            </el-col>
                            <el-col class="line" :span="2" style="text-align: center">-</el-col>
                            <el-col :span="11">
                                <el-form-item prop="runtimeRangeEnd">
                                    <el-time-select
                                        style="width: 100%;"
                                        placeholder="任务运行结束时间"
                                        v-model="form.runtimeRangeEnd"
                                        key="runtimeRangeEnd"
                                        :picker-options="{
                    start: '07:00',
                    step: '00:30',
                    end: '22:00',
                    minTime: form.runtimeRangeStart
                  }">
                                    </el-time-select>
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                    </div>
                    <!-- 场景任务 -->
                    <div class="form-section" v-if="form.taskType === 2" >
                        <div class="section-title">
                            <i class="el-icon-document"></i>
                            <span>基本信息</span>
                        </div>
                        <el-form-item label="任务名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入任务名称" clearable/>
                        </el-form-item>
                        <el-form-item label="任务流程" prop="companyAiWorkflowId">
                            <el-select v-model="form.companyAiWorkflowId" filterable placeholder="请选择任务流程" @change="onWorkflowChange">
                                <el-option v-for="item in workflowList" :key="item.value" :label="item.label" :value="item.value"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="场景类型" prop="sceneType">
                            <el-select v-model="form.sceneType" filterable placeholder="请选择场景类型">
                                <el-option v-for="opt in sceneList" :key="opt.dictValue" :label="opt.dictLabel" :value="opt.dictValue"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="运行时间" required>
                            <el-col :span="11">
                                <el-form-item prop="runtimeRangeStart">
                                    <el-time-select
                                        placeholder="任务运行开始时间"
                                        style="width: 100%;"
                                        v-model="form.runtimeRangeStart"
                                        key="runtimeRangeStart"
                                        :picker-options="{
                    start: '07:00',
                    step: '00:30',
                    end: '22:00'
                  }">
                                    </el-time-select>
                                </el-form-item>
                            </el-col>
                            <el-col class="line" :span="2" style="text-align: center">-</el-col>
                            <el-col :span="11">
                                <el-form-item prop="runtimeRangeEnd">
                                    <el-time-select
                                        style="width: 100%;"
                                        placeholder="任务运行结束时间"
                                        v-model="form.runtimeRangeEnd"
                                        key="runtimeRangeEnd"
                                        :picker-options="{
                    start: '07:00',
                    step: '00:30',
                    end: '22:00',
                    minTime: form.runtimeRangeStart
                  }">
                                    </el-time-select>
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                        <el-form-item label="适用时间" required>
                            <el-col :span="11">
                                <el-form-item prop="availableStartTime">
                                    <el-time-select
                                        placeholder="场景适用开始时间"
                                        style="width: 100%;"
                                        v-model="form.availableStartTime"
                                        key="availableStartTime"
                                        :picker-options="{
                    start: '00:00',
                    step: '00:30',
                    end: '23:30'
                  }">
                                    </el-time-select>
                                </el-form-item>
                            </el-col>
                            <el-col class="line" :span="2" style="text-align: center">-</el-col>
                            <el-col :span="11">
                                <el-form-item prop="availableEndTime">
                                    <el-time-select
                                        style="width: 100%;"
                                        placeholder="场景适用结束时间"
                                        v-model="form.availableEndTime"
                                        key="availableEndTime"
                                        :picker-options="{
                    start: '00:00',
                    step: '00:30',
                    end: '23:30'
                  }">
                                    </el-time-select>
                                </el-form-item>
                            </el-col>
                        </el-form-item>

                    </div>

                    <div class="form-section" v-if="workflowHasAddWx">
                        <div class="section-title">
                            <i class="el-icon-setting"></i>
                            <span>加微设置</span>
                        </div>
                        <el-form-item label="加微方式" prop="addType">
                            <el-radio-group v-model="form.addType">
                                <el-radio :label="0" border>
                                    <i class="el-icon-pie-chart"></i>
                                    平均分配
                                </el-radio>
                                <el-radio :label="1" border>
                                    <i class="el-icon-star-on"></i>
                                    意向分配
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>

                    <div class="form-section account-section" v-if="workflowHasAddWx">
                        <div class="section-title">
                            <i class="el-icon-user-solid"></i>
                            <span>分配账号</span>
                        </div>
                        <el-form-item label="添加类型" prop="isWeCom">
                            <el-radio-group v-model="form.isWeCom">
                                <el-radio :label="1" border>
                                    <i class="el-icon-pie-chart"></i>
                                    个微
                                </el-radio>
                                <el-radio :label="2" border>
                                    <i class="el-icon-star-on"></i>
                                    企微
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-button type="primary" size="mini" icon="el-icon-plus" @click="addQwUser" plain>添加</el-button>

                        <div class="account-list" v-if="form.qwUser && form.qwUser.length">
                            <div v-for="(item, index) in form.qwUser" :key="index" class="account-item">
                                <el-row :gutter="12">
                                    <el-col :span="form.addType == 1 ? 6 : 0" v-if="form.addType == 1">
                                        <el-select v-model="item.intention" placeholder="意向等级" filterable clearable size="small">
                                            <el-option v-for="opt in levelList" :key="opt.dictValue" :label="opt.dictLabel" :value="opt.dictValue"/>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="form.addType == 1 ? 7 : 10">
                                        <el-button icon="el-icon-user" @click="openQwUserSelect(index)" size="small" style="width: 100%;">
                                            选择账号
                                            <el-tag v-if="item.companyUserId && item.companyUserId.length" type="success" size="mini" style="margin-left: 6px;">
                                                {{ item.companyUserId.length }}
                                            </el-tag>
                                        </el-button>
                                    </el-col>
                                    <!-- <el-col :span="form.addType == 1 ? 9 : 12">
                                      <el-select v-model="item.wxDialogId" placeholder="选择话术" filterable size="small">
                                        <el-option v-for="dialog in wxDialogList" :key="dialog.id" :label="dialog.name" :value="dialog.id"/>
                                      </el-select>
                                    </el-col> -->
                                    <el-col :span="2">
                                        <el-button type="danger" icon="el-icon-delete" circle @click="removeQwUser(index)" size="small"></el-button>
                                    </el-col>
                                </el-row>
                            </div>
                        </div>
                        <el-empty v-else description="暂无分配账号" :image-size="80"></el-empty>
                    </div>
                    <!-- <el-form-item label="模式" prop="mode">
                      <el-select v-model="form.mode">
                        <el-option label="呼叫机器人后挂断" :value="7"/>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="呼叫倍率" prop="multiplier">
                      <el-select v-model="form.multiplier">
                        <el-option :value="1"/>
                        <el-option :value="2"/>
                        <el-option :value="3"/>
                        <el-option :value="4"/>
                        <el-option :value="5"/>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="自动重呼" prop="autoRecall">
                      <el-radio v-model="form.autoRecall" :label="0">否</el-radio>
                      <el-radio v-model="form.autoRecall" :label="1">是</el-radio>
                    </el-form-item>
                    <el-form-item label="重呼次数" prop="recallTimes" v-if="form.autoRecall == 1">
                      <el-select v-model="form.recallTimes">
                        <el-option label="不自动重呼" :value="0"/>
                        <el-option :value="1"/>
                        <el-option :value="2"/>
                        <el-option :value="3"/>
                        <el-option :value="4"/>
                        <el-option :value="5"/>
                      </el-select>
                    </el-form-item> -->
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right">
                    <el-button type="primary" :loading="submitFormLoading" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </div>
        </el-drawer>
        <customer-select @success="selectFun" ref="customer"/>
        <append-customer-select @success="appendSelectFun" ref="appendCustomer" />
        <component
            :is="getCurrentComponent()"
            @success="selectQwUserFun"
            ref="dynamicQwUserSelect"
        />

        <el-drawer title="呼叫客户列表" size="60%" :visible.sync="callees.show" width="800px" append-to-body>
            <div class="callees-drawer-content">
                <el-table border height="500" v-loading="callees.loading" :data="callees.list">
                    <el-table-column label="电话号码" align="center" prop="phone" width="150">
                        <template slot-scope="scope">
                            <span>{{ scope.row.phone }}</span>
                            <el-button
                                v-if="scope.row.userId"
                                type="text"
                                size="mini"
                                v-hasPermi="['crm:customer:queryPhone']"
                                @click="handleQueryPhone(scope.row)"
                            >查看</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="客户名称" align="center" prop="userName"/>
                    <el-table-column label="客户ID" align="center" prop="userId"/>
                    <el-table-column label="客户意向度" align="center">
                        <template slot-scope="scope">
                            <el-tag v-for="item in levelList" v-if="scope.row.intention == item.dictValue" :key="item.dictValue">{{item.dictLabel}}</el-tag>
                            <span v-if="!levelList.some(item => scope.row.intention == item.dictValue)">-</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="呼出次数" align="center" prop="roboticCallOutCount" width="100">
                        <template slot-scope="scope">
                            {{ scope.row.roboticCallOutCount == null ? 0 : scope.row.roboticCallOutCount }}
                        </template>
                    </el-table-column>
                    <el-table-column label="AI标签" align="center" prop="customerId" width="280">
                        <template slot-scope="scope">
                            <div v-if="scope.row.tagList && scope.row.tagList.length" class="ai-tags-container">
                                <div v-for="tag in scope.row.tagList" :key="tag.id" class="ai-tag-item">
                                    <div class="tag-main-content">
                                        <span class="tag-property-name">{{ tag.propertyName }}</span>
                                        <span class="tag-property-value">
                      <span v-if="Array.isArray(tag.propertyValue)">{{ tag.propertyValue.join('、') }}</span>
                      <span v-else>{{ tag.propertyValue }}</span>
                    </span>
                                    </div>
                                    <div v-if="tag.intention || (tag.likeRatio !== null && tag.likeRatio !== undefined)" class="tag-meta-info">
                                        <el-tag v-if="tag.intention" size="mini" effect="plain" class="meta-tag intention-tag">
                                            <i class="el-icon-star-on"></i> {{ getIntentionText(tag.intention) }}
                                        </el-tag>
                                        <el-tag v-if="tag.likeRatio !== null && tag.likeRatio !== undefined" size="mini" type="success" effect="plain" class="meta-tag ratio-tag">
                                            <i class="el-icon-trend-chart"></i> {{ tag.likeRatio }}%
                                        </el-tag>
                                    </div>
                                </div>
                            </div>
                            <span v-else class="no-tags">暂无标签</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否添加客服" align="center" prop="isAdd" width="120">
                        <template slot-scope="scope">
                            <el-tag :type="scope.row.isAdd === 1 ? 'success' : 'info'">
                                {{ scope.row.isAdd === 1 ? '已添加' : '未添加' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="text"
                                @click="openCustomer(scope.row.userId,scope.row.idToString,scope.row.roboticId)"
                            >客户信息详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                    v-show="callees.total>0"
                    :total="callees.total"
                    :page.sync="callees.queryParams.pageNum"
                    :limit.sync="callees.queryParams.pageSize"
                    @pagination="getCalleesList"
                />
            </div>
        </el-drawer>
        <el-drawer title="加个微详情" size="60%" :visible.sync="wx.show" append-to-body>
            <el-table v-loading="wx.loading" :data="wx.list">
                <el-table-column label="意向等级" align="center" prop="intention"/>
                <el-table-column label="微信昵称" align="center" prop="wxNickName"/>
                <el-table-column label="微信号" align="center" prop="wxNo"/>
                <el-table-column label="手机号" align="center" prop="phone"/>
                <el-table-column label="员工名称" align="center" prop="companyUserName"/>
                <el-table-column label="话术" align="center" prop="dialogName"/>
                <el-table-column label="分配数量" align="center" prop="num"/>
                <el-table-column label="添加数量" align="center" prop="addNum"/>
            </el-table>

            <pagination
                v-show="wx.total>0"
                :total="wx.total"
                :page.sync="wx.queryParams.pageNum"
                :limit.sync="wx.queryParams.pageSize"
                @pagination="getWxList"
            />
        </el-drawer>
        <el-drawer title="加企微详情" size="60%" :visible.sync="qw.show" append-to-body>
            <el-table v-loading="qw.loading" :data="qw.list">
                <el-table-column label="意向等级" align="center" prop="intention"/>
                <el-table-column label="企微昵称" align="center" prop="wxNickName"/>
                <el-table-column label="企微id" align="center" prop="wxNo"/>
                <el-table-column label="手机号" align="center" prop="phone"/>
                <el-table-column label="话术" align="center" prop="dialogName"/>
                <el-table-column label="分配数量" align="center" prop="num"/>
                <el-table-column label="添加数量" align="center" prop="addNum"/>
            </el-table>

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

        <!-- 执行日志对话框 -->
        <el-drawer
            title="任务执行日志"
            size="75%"
            :visible.sync="execLogs.show"
            append-to-body
            class="exec-logs-drawer">
            <div class="exec-logs-container" v-loading="execLogs.loading">
                <el-card class="filter-card" shadow="never">
                    <el-form :inline="true" size="small" class="filter-form" style="margin-top: 20px;">
                        <el-form-item label="客户姓名">
                            <el-input
                                v-model="execLogs.customerName"
                                placeholder="请输入客户姓名"
                                clearable
                                @keyup.enter.native="handleSearch"
                                style="width: 180px">
                            </el-input>
                        </el-form-item>

                        <el-form-item label="手机号">
                            <el-input
                                v-model="execLogs.customerPhone"
                                placeholder="请输入手机号"
                                clearable
                                @keyup.enter.native="handleSearch"
                                style="width: 200px">
                            </el-input>
                        </el-form-item>

                        <el-form-item label="加密手机号">
                            <el-input
                                v-model="execLogs.encryptPhone"
                                placeholder="请输入加密手机号"
                                clearable
                                @keyup.enter.native="handleSearch"
                                style="width: 240px">
                            </el-input>
                        </el-form-item>

                        <el-form-item>
                            <span style="margin-right: 8px;">只看待执行外呼任务</span>
                            <el-checkbox v-model="execLogs.onlyCallNode"></el-checkbox>
                        </el-form-item>

                        <div style="margin-right:auto;">
                            <el-button type="primary" icon="el-icon-search" @click="handleSearch">
                                查询
                            </el-button>
                            <el-button icon="el-icon-refresh" @click="handleReset">
                                重置
                            </el-button>
                        </div>
                    </el-form>
                </el-card>

                <div v-if="execLogs.list.length === 0" class="empty-logs">
                    <i class="el-icon-document"></i>
                    <p>暂无执行记录</p>
                </div>

                <div v-else>
                    <!-- 统计信息卡片 -->
                    <el-card class="stats-card" shadow="never">
                        <div class="stats-grid">
                            <div class="stat-item">
                                <i class="el-icon-user" style="color: #1890ff;"></i>
                                <div class="stat-content">
                                    <div class="stat-label">客户总数</div>
                                    <!--                  <div class="stat-value">{{ execLogs.list.length }}</div>-->
                                    <div class="stat-value">{{ execLogs.total }}</div>
                                </div>
                            </div>
                            <div class="stat-item">
                                <i class="el-icon-phone" style="color: #52c41a;"></i>
                                <div class="stat-content">
                                    <div class="stat-label">已打电话</div>
                                    <div class="stat-value">{{ execLogs.stats.callDone }}</div>
                                </div>
                            </div>
                            <div class="stat-item">
                                <i class="el-icon-chat-line-square" style="color: #faad14;"></i>
                                <div class="stat-content">
                                    <div class="stat-label">已加微信</div>
                                    <div class="stat-value">{{ execLogs.stats.addWxDone }}</div>
                                </div>
                            </div>
                            <div class="stat-item">
                                <i class="el-icon-message" style="color: #722ed1;"></i>
                                <div class="stat-content">
                                    <div class="stat-label">已发短信</div>
                                    <div class="stat-value">{{ execLogs.stats.sendMsgDone }}</div>
                                </div>
                            </div>
                        </div>
                    </el-card>

                    <!-- 执行记录列表 -->
                    <div class="logs-list">
                        <el-collapse v-model="execLogs.activeNames" accordion>
                            <el-collapse-item
                                v-for="(record, index) in execLogs.list"
                                :key="index"
                                :name="index">
                                <template slot="title">
                                    <div class="record-header">
                                        <div class="record-left">
                                            <el-avatar :size="48" icon="el-icon-user-solid" :style="{background: getAvatarColor(index)}"></el-avatar>
                                            <div class="customer-detail">
                                                <div class="customer-name-row">
                                                    <span class="customer-name">{{ record.customerName }}</span>
                                                    <el-tag
                                                        :type="getWorkflowStatusType(record.workflowStatus)"
                                                        size="small"
                                                        class="status-tag">
                                                        {{ record.workflowStatusName }}
                                                    </el-tag>
                                                </div>
                                                <div class="customer-meta">
                          <span class="meta-item phone">
                            <i class="el-icon-phone-outline"></i>
                            {{ record.customerPhone }}
                            <el-button
                                v-if="record.customerId"
                                icon="el-icon-search"
                                size="mini"
                                circle
                                style="margin-left: 5px;"
                                v-hasPermi="['crm:customer:queryPhone']"
                                @click.stop="handleQueryPhone(record)"
                            />
                          </span>
                                                    <span class="meta-divider">|</span>
                                                    <span class="meta-item node">
                            <i class="el-icon-s-operation"></i>
                            当前节点：<strong>{{ record.currentNodeTypeName }}</strong>

                                                        <!-- <el-button
                                                          v-if="hasContent(record)"
                                                          size="mini"
                                                          type="primary"
                                                          plain
                                                          icon="el-icon-chat-dot-round"
                                                          style="margin-left: 8px;"
                                                          @click.stop="handleShowContent(record)">
                                                            查看对话内容
                                                        </el-button> -->
                                                        <!-- 外呼未执行标识 -->
                            <el-button
                                v-if="record.waitCallNode"
                                size="mini"
                                type="primary"
                                plain
                                icon="el-icon-phone"
                                style="margin-left: 8px;"
                                @click.stop="handleManualCall(record)">
                                开始人工外呼
                            </el-button>
                          </span>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- <div class="record-right">
                                          <div class="progress-info">
                                            <span class="progress-label">执行进度</span>
                                            <span class="progress-value">{{ getProgress(record) }}%</span>
                                          </div>
                                          <el-progress
                                            :percentage="getProgress(record)"
                                            :color="getProgressColor(record)"
                                            :stroke-width="10"
                                            :show-text="false"></el-progress>
                                        </div> -->
                                    </div>
                                </template>

                                <!-- 节点执行日志 -->
                                <div class="node-logs">
                                    <el-timeline>
                                        <el-timeline-item
                                            v-for="(log, logIndex) in record.nodeLogs"
                                            :key="logIndex"
                                            :timestamp="log.startTime"
                                            :color="getNodeStatusColor(log.statusName)"
                                            placement="top">
                                            <el-card class="node-log-card">
                                                <div class="node-log-header">
                                                    <div class="node-info">
                                                        <i :class="getNodeIcon(log.nodeKey)" class="node-icon"></i>
                                                        <span class="node-name">{{ log.nodeName }}</span>
                                                        <el-button
                                                            v-if="hasContent(log)"
                                                            size="mini"
                                                            type="primary"
                                                            plain
                                                            icon="el-icon-chat-dot-round"
                                                            style="margin-left: 8px;"
                                                            @click.stop="handleShowContent(record,log)">
                                                            查看对话内容
                                                        </el-button>
                                                    </div>
                                                    <el-tag
                                                        :type="getStatusTagType(log.statusName)"
                                                        size="mini">
                                                        {{ log.statusName }}
                                                    </el-tag>
                                                </div>
                                                <div class="node-log-body" v-if="log.errorMsg">
                                                    <div class="error-msg">
                                                        <i class="el-icon-warning"></i>
                                                        {{ log.errorMsg }}
                                                    </div>
                                                </div>
                                                <div class="node-log-footer">
                          <span class="duration" v-if="log.duration">
                            <i class="el-icon-time"></i>
                            耗时: {{ formatDuration(log.duration) }}
                          </span>
                                                </div>

                                            </el-card>
                                        </el-timeline-item>
                                    </el-timeline>
                                </div>
                            </el-collapse-item>
                        </el-collapse>
                    </div>
                    <!-- 分页 -->
                    <div class="pagination-wrapper" style="margin-top: 20px;">
                        <el-pagination
                            background
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="execLogs.total"
                            :page-size="execLogs.pageSize"
                            :current-page.sync="execLogs.pageNum"
                            :page-sizes="[5, 10, 20, 30, 50]"
                            @current-change="handlePageChange"
                            @size-change="handleSizeChange">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </el-drawer>

        <el-drawer size="75%" title="客户详情" :visible.sync="customerDetailShow" append-to-body>
            <customer-details ref="customerDetails" />
        </el-drawer>
        <el-dialog
            :title="manualCallDialog.title"
            :visible.sync="manualCallDialog.visible"
            width="1500px"
            append-to-body
            destroy-on-close
            class="manual-call-dialog"
            @close="handleManualCallDialogClose"
        >
            <call-center-phone-bar
                :key="manualCallDialog.key"
                ref="callCenterPhoneBar"
                :init-phone-number="manualCallDialog.phone"
                :robotic-id="manualCallDialog.roboticId"
                :company-id="manualCallDialog.companyId"
                :company-user-id="manualCallDialog.companyUserId"
                :workflow-instance-id="manualCallDialog.workflowInstanceId"
                :customer-id="manualCallDialog.customerId"
            />
        </el-dialog>

        <el-dialog
            title="对话内容"
            :visible.sync="contentDialog.visible"
            width="900px"
            append-to-body
            class="content-dialog"
        >
            <div class="content-dialog-wrapper">
                <div class="content-dialog-header" >
                    <span>客户姓名：{{ contentDialog.customerName || '-' }}</span>
                    <span>手机号：{{ contentDialog.customerPhone || '-' }}</span>
                </div>

                <div v-if="contentDialog.recordPath" class="content-dialog-audio">
                    <span class="audio-label">录音播放：</span>
                    <audio controls :src="handleRecordPath(contentDialog.recordPath)"></audio>
                </div>

                <div v-if="!contentDialog.content" class="content-empty">
                    暂无对话内容
                </div>

                <div class="chat-container">
                    <div
                        v-for="(msg, index) in parseContentList(contentDialog.content)"
                        :key="index"
                        :class="['chat-item', msg.role === 'user' ? 'chat-right' : 'chat-left']"
                    >
                        <div class="chat-bubble-wrapper">
                            <div class="chat-role">
                                {{ msg.role === 'user' ? '客户' : '客服' }}
                            </div>
                            <div class="chat-bubble">
                                {{ msg.content }}
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    listRobotic,
    getRobotic,
    delRobotic,
    addRobotic,
    updateRobotic,
    exportRobotic,
    calleesList,
    statusList,
    startRobotic,
    stopRobotic,
    companyUserList,
    wxList,
    taskRun,
    // getTypes,
    getSmsTempList,
    // getCIDGroupList,
    getExecRecords,
    getCurrentCompanyId,
    pauseRoboticActive,
    appendCustomers
} from "@/api/company/companyVoiceRobotic";
import draggable from 'vuedraggable'
// import { listAll } from '@/api/company/wxDialog';
import customerSelect from '@/views/crm/components/CustomerSelect.vue';
import appendCustomerSelect from '@/views/crm/components/AppendCustomerSelect.vue';
import qwUserSelect from '@/views/components/QwUserSelect.vue';
import qwUserSelectTwo from '@/views/components/QwUserSelectTwo.vue';
import customerDetails from "@/views/crm/components/customerDetails.vue";
import { queryPhone } from "@/api/crm/customer";
import {getDicts} from "@/api/system/dict/data";
import { optionList, getWorkflowNodeTypeCodes } from '@/api/company/companyWorkflow'
import {wxListQw} from "../../../api/company/companyVoiceRobotic";
import CallCenterPhoneBar from '../../aiSipCall/aiSipCallManualOutbound.vue'
import AiTagPanel from "../../crm/components/AiTagPanel.vue";

export default {
    name: "Robotic",
    components: {AiTagPanel, draggable, customerDetails, customerSelect, appendCustomerSelect, qwUserSelect,qwUserSelectTwo,CallCenterPhoneBar},
    data() {
        return {
            submitFormLoading:false,
            actionLoading: {},
            taskType:1,
            taskTypeList:[{id:1,name:"普通任务"},{id:2,name:"场景任务"}],
            currentCompanyId:null,
            workflowHasAddWx: false,
            // 遮罩层
            loading: true,
            // CIDGroupList:[],
            // 选中数组
            ids: [],
            weekList: [
                {label: "星期一", value: 1},
                {label: "星期二", value: 2},
                {label: "星期三", value: 3},
                {label: "星期四", value: 4},
                {label: "星期五", value: 5},
                {label: "星期六", value: 6},
                {label: "星期日", value: 0},
            ],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            loadingStatus: true,
            // 总条数
            total: 0,
            // 机器人外呼任务表格数据
            roboticList: [],
            userTableList: [],
            workflowList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                taskName: null,
                taskId: null,
                robot: null,
                dialogId: null,
                mode: null,
                multiplier: null,
                autoRecall: null,
                recallTimes: null,
                cidGroupId: null,
                weekDay1: null,
                startTime1: null,
                endTime1: null,
                weekDay2: null,
                startTime2: null,
                endTime2: null,
                createUser: null,
                taskType:null
            },
            // 表单参数
            form: {
                taskType:1
            },
            taskFlowList: [{key: "cellPhone", value: "外呼"}, {key: "qwAddWx", value: "企微加微"}, {key: "sendMsg", value: "发短信"}, {key: "addWx", value: "加微"}],
            taskFlowMap: {cellPhone: "外呼", sendMsg: "发短信", addWx: "加微", qwAddWx: "企微加微"},
            statusObj: {},
            levelList: {},
            robotList: [],
            dialogList: [],
            wxDialogList: [],
            qwUserList: [],
            selectQwUserList: [],
            thisQwUserIndex: 0,
            updateTime: null,
            customer: {
                show: false,
            },
            customerDetailShow: false,
            callees: {
                show: false,
                list: [],
                loading: false,
                total: 0,
                queryParams:{
                    id: null,
                    pageNum: 1,
                    pageSize: 10,
                },
            },
            wx: {
                show: false,
                list: [],
                loading: false,
                total: 0,
                queryParams:{
                    id: null,
                    pageNum: 1,
                    pageSize: 10,
                },
            },
            qw: {
                show: false,
                list: [],
                loading: false,
                total: 0,
                queryParams: {
                    id: null,
                    pageNum: 1,
                    pageSize: 10,
                },
            },
            execLogs: {
                show: false,
                loading: false,
                list: [],
                activeNames: [],
                stats: {
                    callDone: 0,
                    addWxDone: 0,
                    sendMsgDone: 0
                },
                pageNum: 1,
                pageSize: 10,
                total: 0,
                currentTaskId: null,
                customerName: '',
                customerPhone: '',
                encryptPhone: '',
                onlyCallNode: false
            },
            manualCallDialog: {
                visible: false,
                phone: '',
                title: "人工外呼",
                record: null,
                key: 0,
                roboticId: null,
                companyId: null,
                companyUserId: null,
                workflowInstanceId: null,
                customerId: null
            },
            contentDialog: {
                visible: false,
                content: '',
                customerName: '',
                customerPhone: '',
                recordPath: ''
            },
            // 表单校验
            rules: {
                taskType:[
                    { required: true, message: '请选择任务类型', trigger: 'change' },
                ],
                name: [
                    { required: true, message: '请输入任务名称', trigger: 'blur' },
                ],
                companyAiWorkflowId: [
                    { required: true, message: '请选择流程', trigger: 'change' }
                ],
                runtimeRangeStart:[
                    { required: true, message: '请选择任务运行开始时间', trigger: 'change' }
                ],
                runtimeRangeEnd:[
                    { required: true, message: '请选择任务运行结束时间', trigger: 'change' }
                ]
            },
            smsTempList:[],
            sceneList:[]
        };
    },
    created() {
        getCurrentCompanyId().then(res=>{
            this.currentCompanyId = res.companyId;
        }).catch(res=>{
        })
        //getTypes().then(e => {
        //this.robotList = e.robot;
        //this.dialogList = e.dialog;
        //})
        // listAll().then(e => {
        //   this.wxDialogList = e.data;
        // })
        companyUserList().then(e => {
            this.qwUserList = e.data;
        })
        optionList().then(e => {
            this.workflowList = e.data;
        })
        getDicts("customer_intention_level").then(e => {
            this.levelList = e.data;
        })
        getDicts("task_scene_type").then(e => {
            this.sceneList = e.data;
        })
        this.getList();
        this.getSmsTempDropList();

        // getCIDGroupList().then(res=>{
        //   console.log("----------------------")
        //   console.log(res);
        //   this.CIDGroupList = res.data;
        // }).catch(res=>{
        //   console.log("catch_____+++++++")
        //   console.log(res);
        // });
    },
    watch: {
        // 监听添加类型的切换，清空选择器数据
        'form.isWeCom': {
            handler(newVal, oldVal) {
                // 只有当值真正发生变化时才执行清空操作
                if (newVal !== oldVal && oldVal !== undefined) {
                    // 清空 qwUser 数组中的选择数据
                    if (this.form.qwUser && this.form.qwUser.length > 0) {
                        this.form.qwUser.forEach(item => {
                            item.companyUserId = []; // 清空已选择的账号ID
                        });
                    }

                    // 清空选择器列表数据
                    this.selectQwUserList = [];

                    // 重置当前选择索引
                    this.thisQwUserIndex = 0;

                    // 强制更新视图
                    this.$forceUpdate();
                }
            },
            immediate: false
        },
        'execLogs.currentTaskId': {
            handler(newVal, oldVal) {
                // 只有当任务ID真的变化时才重置搜索条件
                if (newVal !== oldVal && oldVal !== undefined) {
                    // 清空搜索条件
                    this.execLogs.customerName = ''
                    this.execLogs.customerPhone = ''
                    this.execLogs.encryptPhone = ''
                    this.execLogs.pageNum = 1
                    this.execLogs.onlyCallNode = false

                    // 可选：重置分页
                    this.execLogs.pageSize = 10

                    // 重新获取执行记录
                    this.getExecLogs()
                }
            },
            immediate: false
        }
    },
    methods: {

        getIntentionText(intention) {
            const intentionMap = {
                high: "高意向",
                medium: "中意向",
                low: "低意向",
                none: "无意向"
            };
            return intentionMap[intention] || intention;
        },

        getSmsTempDropList(){
            getSmsTempList().then(res=>{
                this.smsTempList = res.data;
            }).catch(res=>{
            })
        },
        /** 查询机器人外呼任务列表 */
        getList() {
            this.loading = true;
            listRobotic(this.queryParams).then(response => {
                this.roboticList = response.rows;
                this.roboticList.forEach(e => {
                    if(e.weekDay1){
                        e.weekDay = e.weekDay1.split(",")
                    }
                })
                this.total = response.total;
                this.loading = false;
                this.updateStatusFun();
            });
        },
        updateStatusFun(){
            if(!this.roboticList){
                return;
            }
            this.loadingStatus = true;
            statusList(this.roboticList.map(e => e.taskId).join()).then(e => {
                this.loadingStatus = false;
                this.statusObj = e.data;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                taskName: null,
                taskId: null,
                robot: null,
                dialogId: null,
                mode: 7,
                multiplier: 3,
                autoRecall: 0,
                recallTimes: null,
                cidGroupId: null,
                weekDay1: null,
                startTime1: null,
                addType: 0,
                endTime1: null,
                weekDay2: null,
                startTime2: null,
                endTime2: null,
                createTime: null,
                qwUser: [],
                createUser: null,
                userIds: [],
                userNames: [],
                userTableList: [],
                companyAiWorkflowId: null,
                runtimeRangeStart:null,
                runtimeRangeEnd:null,
                isWeCom: 1,
                taskType:1,
                availableStartTime :null,
                availableEndTime: null
            };
            this.workflowHasAddWx = false;
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            optionList().then(e => {
                this.workflowList = e.data;
            })
            this.open = true;
            this.title = "添加任务";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getRobotic(id).then(response => {
                this.form = response.data;
                if (this.form.companyAiWorkflowId) {
                    this.onWorkflowChange(this.form.companyAiWorkflowId);
                }
                this.open = true;
                this.title = "修改机器人外呼任务";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.weekDay && this.form.weekDay.length > 0) {
                        this.form.weekDay1 = this.form.weekDay.join(",")
                    }

                    if (this.workflowHasAddWx) {
                        if(!this.form.qwUser || this.form.qwUser.length == 0){
                            this.msgError("请添加分配账号");
                            return;
                        }

                        for(let i = 0; i < this.form.qwUser.length; i++) {
                            const account = this.form.qwUser[i];
                            if(!account.companyUserId || account.companyUserId.length == 0) {
                                this.msgError(`第 ${i + 1} 个账号请选择企微`);
                                return;
                            }
                        }
                    }

                    let list = [];
                    if (this.workflowHasAddWx && this.form.qwUser) {
                        this.form.qwUser.forEach(l => {
                            list = list.concat(l.companyUserId.map(e => {return {intention: l.intention, companyUserId: e,wxDialogId: l.wxDialogId,smsTempId:l.smsTempId}}))
                        })
                    }
                    this.form.qwUserList = list;
                    if(this.workflowHasAddWx && (!this.form.qwUserList || this.form.qwUserList.length == 0)){
                        this.msgError("请选者加微方案");
                        return;
                    }
                    this.form.taskFlow = this.taskFlowList.map(e => e.key).join();
                    this.submitFormLoading = true;
                    if (this.form.id != null) {
                        updateRobotic(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            }
                            this.submitFormLoading = false;
                        }).catch(res=>{
                            this.submitFormLoading = false;
                        });
                    } else {
                        addRobotic(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            }
                            this.submitFormLoading = false;
                        }).catch(res=>{
                            this.submitFormLoading = false;
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            const key = row.id + '_delete';
            this.$confirm('是否确认删除机器人外呼任务编号为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.$set(this.actionLoading, key, true);
                return delRobotic(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(function () {
            }).finally(() => {
                this.$set(this.actionLoading, key, false);
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有机器人外呼任务数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return exportRobotic(queryParams);
            }).then(response => {
                this.download(response.msg);
            }).catch(function () {
            });
        },
        openSelect() {
            if(!!this.currentCompanyId){
                this.$refs.customer.setRowsDesignatedCompany(this.form.userTableList || [],this.currentCompanyId);
            }else{
                this.$refs.customer.setRows(this.form.userTableList || []);
            }
        },
        // openQwUserSelect(index) {
        //   this.thisQwUserIndex = index;
        //   this.$nextTick(() => {
        //     this.$refs.qwUserSelect.setRows(this.selectQwUserList[index]);
        //   })
        // },
        selectFun(e) {
            this.form.userIds = e.ids;
            this.form.userNames = e.names;
            this.form.userTableList = e.rows;
            this.$forceUpdate()
        },
        selectQwUserFun(e) {
            this.form.qwUser[this.thisQwUserIndex].companyUserId = e.ids;
            this.selectQwUserList[this.thisQwUserIndex] = e.rows;
            this.$forceUpdate()
        },
        calleesOpen(id){
            this.callees.show = true;
            this.callees.queryParams.id = id;
            this.getCalleesList();
        },
        getCalleesList() {
            this.callees.loading = true;
            calleesList(this.callees.queryParams).then(response => {
                this.callees.list = response.rows;
                this.callees.total = response.total;
                this.callees.loading = false;
            });
        },
        handleQueryPhone(row) {
            const customerId = row.customerId || row.userId;
            if (!customerId) {
                this.$message.warning("客户ID不存在");
                return;
            }
            queryPhone(customerId).then(response => {
                this.$alert(response.mobile, "手机号", {
                    confirmButtonText: "确定"
                });
            });
        },
        wxOpen(id, isWeCom) {
            if (isWeCom === 2) {
                this.qw.show = true;
                this.qw.queryParams.id = id;
                this.getWxListQw();
            } else {
                this.wx.show = true;
                this.wx.queryParams.id = id;
                this.getWxList();
            }
        },
        getWxListQw() {
            this.qw.loading = true;
            wxListQw(this.qw.queryParams).then(response => {
                this.qw.list = response.rows;
                this.qw.total = response.total;
                this.qw.loading = false;
            });
        },
        getWxList() {
            this.wx.loading = true;
            wxList(this.wx.queryParams).then(response => {
                this.wx.list = response.rows;
                this.wx.total = response.total;
                this.wx.loading = false;
            });
        },
        openCustomer(id,calleesId,roboticId) {
            this.customerDetailShow=true;
            this.$nextTick(() => {
                this.$refs.customerDetails.getDetails(id,calleesId,roboticId);
            })
        },
        startRoboticFun(id){
            startRobotic(id).then(e => {
                this.updateStatusFun();
            })
        },
        taskRunFun(id){
            const key = id + '_taskRun';
            this.$set(this.actionLoading, key, true);
            taskRun({id}).then(e => {
                this.getList();
            }).finally(() => {
                this.$set(this.actionLoading, key, false);
            });
        },
        // 暂停任务
        handlePauseTask(row) {
            const key = row.id + '_pause';
            this.$confirm('暂停后，该任务下所有工作流将停止执行，正在进行的节点将完成当前操作后停止。确认暂停？', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.$set(this.actionLoading, key, true);
                return pauseRoboticActive({ taskId: row.id, activeType: 1 });
            }).then(() => {
                this.msgSuccess("暂停成功");
                this.getList();
            }).catch(() => {}).finally(() => {
                this.$set(this.actionLoading, key, false);
            });
        },
        // 继续任务
        handleResumeTask(row) {
            const key = row.id + '_resume';
            this.$confirm('确认继续执行该任务？恢复后工作流将继续运行。', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.$set(this.actionLoading, key, true);
                return pauseRoboticActive({ taskId: row.id, activeType: 2 });
            }).then(() => {
                this.msgSuccess("继续成功");
                this.getList();
            }).catch(() => {}).finally(() => {
                this.$set(this.actionLoading, key, false);
            });
        },
        // 追加客户
        handleAppendCustomers(row) {
            this._appendRow = row;
            const key = row.id + '_append';
            this.$set(this.actionLoading, key, true);
            // 获取当前任务已有的客户ID列表
            calleesList({ id: row.id, pageNum: 1, pageSize: 99999 }).then(res => {
                const existingIds = (res.rows || []).map(item => item.userId).filter(id => id != null);
                this.$refs.appendCustomer.setRowsDesignatedCompany([], this.currentCompanyId);
                this.$nextTick(() => {
                    this.$refs.appendCustomer.setExcludeCustomerIds(existingIds);
                    this.$refs.appendCustomer.setTaskId(row.id);
                });
            }).catch(() => {
                this.$refs.appendCustomer.setRowsDesignatedCompany([], this.currentCompanyId);
            }).finally(() => {
                this.$set(this.actionLoading, key, false);
            });
        },
        // 追加客户选择回调
        appendSelectFun(data) {
            const row = this._appendRow;
            if (!row) return;
            const key = row.id + '_append';
            this.$set(this.actionLoading, key, true);
            appendCustomers({
                taskId: row.id,
                customerIds: data.ids
            }).then(res => {
                if (res.code === 200) {
                    const successCount = res.successCount || 0;
                    const dupNames = res.duplicateCustomerNames || '';
                    const errors = res.errorMessages || [];
                    if (successCount > 0) {
                        this.$message.success(`成功追加 ${successCount} 位客户`);
                    }
                    if (dupNames) {
                        this.$message.warning(`以下客户已存在于任务中，已跳过：${dupNames}`);
                    }
                    if (errors.length > 0) {
                        this.$message.error(errors.join('；'));
                    }
                    if (successCount === 0 && !dupNames && errors.length === 0) {
                        this.$message.info('未追加任何客户');
                    }
                } else {
                    this.$message.error(res.msg || '追加客户失败');
                }
            }).catch(err => {
                this.$message.error('追加客户请求失败');
            }).finally(() => {
                this.$set(this.actionLoading, key, false);
                this._appendRow = null;
            });
        },
        stopRoboticFun(id){
            const key = id + '_stop';
            this.$set(this.actionLoading, key, true);
            stopRobotic(id).then(e => {
                this.updateStatusFun();
            }).finally(() => {
                this.$set(this.actionLoading, key, false);
            });
        },
        addQwUser(){
            this.form.qwUser.push({});
        },
        removeQwUser(index){
            this.form.qwUser.splice(index, 1)
        },
        // 打开执行日志
        async showExecLogs(row) {
            this.execLogs.show = true;
            // this.execLogs.loading = true;
            // this.execLogs.list = [];
            this.execLogs.pageNum = 1;
            this.execLogs.pageSize = 10;
            this.execLogs.currentTaskId = row.id;

            try {
                // const res = await getExecRecords(row.id);
                // this.execLogs.list = res.data || [];
                this.getExecLogs();

                // 计算统计数据
                // this.execLogs.stats = {
                //   callDone: this.execLogs.list.reduce((sum, r) => sum + (r.callPhoneDone || 0), 0),
                //   addWxDone: this.execLogs.list.reduce((sum, r) => sum + (r.addWxDone || 0), 0),
                //   sendMsgDone: this.execLogs.list.reduce((sum, r) => sum + (r.sendMsgDone || 0), 0)
                // };
            } catch (error) {
                console.error('获取执行日志失败:', error);
                this.$message.error('获取执行日志失败');
            } finally {
                this.execLogs.loading = false;
            }
        },
        // 获取工作流状态类型
        getWorkflowStatusType(status) {
            const typeMap = {
                1: '',
                2: 'success',
                3: 'warning',
                4: 'danger'
            };
            return typeMap[status] || 'info';
        },
        // 获取进度
        getProgress(record) {
            if (!record.nodeLogs || record.nodeLogs.length === 0) return 0;
            const total = record.nodeLogs.length;
            const completed = record.nodeLogs.filter(log => log.statusName === '执行成功').length;
            return Math.round((completed / total) * 100);
        },
        // 获取进度条颜色
        getProgressColor(record) {
            const progress = this.getProgress(record);
            if (progress === 100) return '#52c41a';
            if (progress >= 50) return '#1890ff';
            return '#faad14';
        },
        // 获取节点状态颜色
        getNodeStatusColor(statusName) {
            const colorMap = {
                '执行成功': '#52c41a',
                '执行中': '#1890ff',
                '执行失败': '#f5222d',
                '等待执行': '#d9d9d9',
                '执行超时':'#f5222d'
            };
            return colorMap[statusName] || '#d9d9d9';
        },
        // 获取状态标签类型
        getStatusTagType(statusName) {
            const typeMap = {
                '执行成功': 'success',
                '执行中': 'warning',
                '执行失败': 'danger',
                '等待执行': 'info',
                '执行超时':'danger'
            };
            return typeMap[statusName] || 'info';
        },
        // 获取节点图标
        getNodeIcon(nodeKey) {
            const iconMap = {
                'node_start': 'el-icon-video-play',
                'node_addwx': 'el-icon-chat-line-square',
                'node_call': 'el-icon-phone',
                'node_sms': 'el-icon-message',
                'node_end': 'el-icon-circle-check'
            };
            return iconMap[nodeKey] || 'el-icon-document';
        },
        // 格式化时长
        formatDuration(ms) {
            if (!ms) return '-';
            if (ms < 1000) return ms + 'ms';
            const seconds = Math.floor(ms / 1000);
            if (seconds < 60) return seconds + 's';
            const minutes = Math.floor(seconds / 60);
            const remainSeconds = seconds % 60;
            return minutes + 'm' + remainSeconds + 's';
        },
        // 获取当前应该使用的组件
        getCurrentComponent() {
            return this.form.isWeCom === 2 ? 'qwUserSelectTwo' : 'qwUserSelect';
        },

        openQwUserSelect(index) {
            this.thisQwUserIndex = index;
            this.$nextTick(() => {
                // 根据 isWeCom 的值选择对应的组件引用
                const componentRef = this.form.isWeCom === 2 ? this.$refs.dynamicQwUserSelect : this.$refs.dynamicQwUserSelect;
                if (componentRef && typeof componentRef.setRows === 'function') {
                    componentRef.setRows(this.selectQwUserList[index]);
                }
            })
        },
        // 获取头像颜色
        getAvatarColor(index) {
            const colors = ['#1890ff', '#52c41a', '#faad14', '#722ed1', '#eb2f96'];
            return colors[index % colors.length];
        },
        /**
         * 选择任务类型
         */
        taskTypeChange(){
            this.form.runtimeRangeStart=null;
            this.form.runtimeRangeEnd= null;
            this.form.userIds= [];
            this.form.userNames= [];
            this.form.userTableList= [];
            this.form.companyAiWorkflowId = null;
            this.form.name = null;
            this.form.availableStartTime = null;
            this.form.availableEndTime = null;
            this.workflowHasAddWx = false;
            this.$nextTick(() => {
                this.$refs.form.clearValidate();
            })
        },
        onWorkflowChange(workflowId) {
            if (!workflowId) {
                this.workflowHasAddWx = false;
                return;
            }
            getWorkflowNodeTypeCodes(workflowId).then(res => {
                const typeCodes = res.data || [];
                this.workflowHasAddWx = typeCodes.includes('AI_ADD_WX_TASK_NEW') || typeCodes.includes('AI_QW_ADD_WX_TASK');
                if (!this.workflowHasAddWx) {
                    this.form.addType = 0;
                    this.form.isWeCom = 1;
                    this.form.qwUser = [];
                }
            }).catch(() => {
                this.workflowHasAddWx = false;
            });
        },
        async getExecLogs() {
            this.execLogs.loading = true
            // 同时输入手机号与加密手机号时，仅以加密手机号为准
            if (this.execLogs.customerPhone && this.execLogs.encryptPhone) {
                this.execLogs.customerPhone = ''
                this.$message.info('已同时输入手机号与加密手机号，将以加密手机号为查询条件')
            }
            try {
                const res = await getExecRecords({
                    roboticId: this.execLogs.currentTaskId,
                    pageNum: this.execLogs.pageNum,
                    pageSize: this.execLogs.pageSize,
                    customerName: this.execLogs.customerName,
                    customerPhone: this.execLogs.customerPhone,
                    encryptPhone: this.execLogs.encryptPhone,
                    onlyCallNode: this.execLogs.onlyCallNode
                })
                this.execLogs.list = (res.rows || []).map(item => ({
                    ...item,
                    contentList: item.contentList || ''
                }))
                this.execLogs.total = res.total || 0
                // this.execLogs.stats = res.stats || {
                //   callDone: 0,
                //   addWxDone: 0,
                //   sendMsgDone: 0
                // }
                // 前端计算统计数据
                this.execLogs.stats = {
                    callDone: this.execLogs.list.reduce((sum, r) => sum + (Number(r.callPhoneDone) || 0), 0),
                    addWxDone: this.execLogs.list.reduce((sum, r) => sum + (Number(r.addWxDone) || 0), 0),
                    sendMsgDone: this.execLogs.list.reduce((sum, r) => sum + (Number(r.sendMsgDone) || 0), 0)
                }

            } catch (e) {
                this.$message.error("获取执行日志失败")
            } finally {
                this.execLogs.loading = false
            }
        },

        handlePageChange(page) {
            this.execLogs.pageNum = page
            this.getExecLogs()
        },

        handleSizeChange(size) {
            this.execLogs.pageSize = size
            this.execLogs.pageNum = 1
            this.getExecLogs()
        },
        handleSearch() {
            // 查询时回到第一页
            this.execLogs.pageNum = 1
            this.getExecLogs()
        },

        handleReset() {
            this.execLogs.customerName = ''
            this.execLogs.customerPhone = ''
            this.execLogs.encryptPhone = ''
            this.execLogs.pageNum = 1
            this.execLogs.onlyCallNode = false
            this.getExecLogs()
        },
        handleManualCall(record) {
            const phone = record.customerPhone || '';

            if (!phone) {
                this.$message.warning('当前客户没有可外呼的手机号');
                return;
            }

            this.manualCallDialog.record = record;
            this.manualCallDialog.phone = phone;
            this.manualCallDialog.title = `人工外呼 - ${record.customerName || '未知客户'}`;

            const currentTask = this.roboticList.find(
                item => item.id === this.execLogs.currentTaskId
            );
            // 带过去的额外参数
            this.manualCallDialog.roboticId = record.roboticId || null;
            this.manualCallDialog.companyId = (currentTask && currentTask.companyId) || null;
            this.manualCallDialog.companyUserId = (currentTask && currentTask.companyUserId) || null;
            this.manualCallDialog.workflowInstanceId = record.workflowInstanceId || null;
            this.manualCallDialog.customerId = record.customerId || null;
            this.manualCallDialog.key += 1;
            this.manualCallDialog.visible = true;
        },
        handleManualCallDialogClose() {
            this.manualCallDialog.phone = '';
            this.manualCallDialog.record = null;
            this.manualCallDialog.roboticId = null;
            this.manualCallDialog.companyId = null;
            this.manualCallDialog.companyUserId = null;
            this.manualCallDialog.workflowInstanceId = null;
            this.manualCallDialog.customerId = null;
        },
        handleShowContent(record,log) {
            this.contentDialog.customerName = record.customerName || '';
            this.contentDialog.customerPhone = record.customerPhone || '';
            this.contentDialog.content = log.nodeContentList || '';
            this.contentDialog.recordPath = log.nodeRecordPath || '';
            this.contentDialog.visible = true;
        },

        parseContentList(content) {
            if (!content) return []

            try {
                const parsed = typeof content === 'string' ? JSON.parse(content) : content
                if (!Array.isArray(parsed)) return []

                return parsed.filter(item => {
                    // 过滤 system 提示词
                    if (!item) return false
                    if (item.role === 'system') return false

                    // 过滤空内容
                    const text = item.content || ''
                    if (!String(text).trim()) return false

                    return true
                })
            } catch (e) {
                console.error("解析 contentList 失败", e)
                return []
            }
        },
        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);
        },
        hasContent(record) {
            if (!record || !record.nodeContentList) return false

            try {
                const parsed = typeof record.nodeContentList === 'string'
                    ? JSON.parse(record.nodeContentList)
                    : record.nodeContentList

                if (!Array.isArray(parsed)) return false

                // 过滤 system 和空内容
                const validList = parsed.filter(item => {
                    if (!item) return false
                    if (item.role === 'system') return false

                    const text = String(item.content || '').trim()
                    if (!text) return false

                    return true
                })

                return validList.length > 0
            } catch (e) {
                return false
            }
        }
    }
};
</script>
<style>
.callees-drawer-content {
    padding: 16px;
}

.flow-parent{
    display: flex;
    flex-wrap: nowrap;
}
.flow-child{
    position: relative;
    width: 150px;
    cursor: move;
}
.flow-child:last-child i{
    display: none;
}
.flow-child:last-child::after{
    display: none;
}
.flow-child i{
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    position: absolute;
    font-weight: bold;
}
.flow-child::after{
    content: "";
    border-top: 1px solid #000;
    height: 1px;
    width: 50px;
    right: 26px;
    top: 50%;
    transform: translateY(-50%);
    position: absolute;
}
.sortable-ghost{
    /* background: #FFF !important; */
    background: rgb(217, 236, 255) !important;
}

/* 执行日志样式 */
.exec-logs-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: calc(100vh - 60px);
}

.exec-logs-container ::v-deep .el-card {
    border: none;
    box-shadow: none;
}

.empty-logs {
    text-align: center;
    padding: 80px 20px;
    color: #909399;
}

.empty-logs i {
    font-size: 64px;
    margin-bottom: 16px;
    color: #dcdfe6;
}

.empty-logs p {
    font-size: 16px;
}

/* 统计卡片 */
.stats-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: none;
}

.stats-card ::v-deep .el-card__body {
    padding: 20px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}

.stat-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background: #f9fafb;
    border-radius: 6px;
}

.stat-item i {
    font-size: 32px;
}

.stat-content {
    flex: 1;
}

.stat-label {
    font-size: 13px;
    color: #909399;
    margin-bottom: 4px;
}

.stat-value {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
}

/* 日志列表 */
.logs-list {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    border: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
.el-collapse-item__header{
    height: auto !important;
}
/* 记录头部 */
.record-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 20px 16px;
    gap: 32px;
}

.record-left {
    display: flex;
    align-items: center;
    gap: 16px;
    flex: 1;
    min-width: 0;
}

.customer-detail {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.customer-name-row {
    display: flex;
    align-items: center;
    gap: 12px;
}

.customer-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    line-height: 1.4;
}

.status-tag {
    flex-shrink: 0;
}

.customer-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 13px;
    color: #606266;
    line-height: 1.4;
}

.meta-item {
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.meta-item i {
    font-size: 14px;
    color: #909399;
}

.meta-item.node strong {
    color: #1890ff;
    font-weight: 600;
}

.meta-divider {
    color: #dcdfe6;
}

.record-right {
    width: 200px;
    flex-shrink: 0;
}

.progress-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.progress-label {
    font-size: 13px;
    color: #909399;
}

.progress-value {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

/* 节点日志 */
.node-logs {
    padding: 20px;
    background: #fafafa;
    border-radius: 6px;
}

.node-log-card {
    margin-bottom: 0;
}

.node-log-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.node-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.node-icon {
    font-size: 18px;
    color: #1890ff;
}

.node-name {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
}

.node-log-body {
    margin: 12px 0;
}

.error-msg {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background: #fff2e8;
    border-left: 3px solid #faad14;
    border-radius: 4px;
    font-size: 13px;
    color: #d46b08;
}

.error-msg i {
    font-size: 16px;
}

.node-log-footer {
    display: flex;
    align-items: center;
    gap: 16px;
    font-size: 13px;
    color: #909399;
}

.duration {
    display: flex;
    align-items: center;
    gap: 4px;
}

.duration i {
    font-size: 14px;
}

/* 任务表单样式 */
.task-form-drawer ::v-deep .el-drawer__body {
    padding: 0;
}

.drawer-content {
    padding: 16px;
    background: #f5f7fa;
    min-height: 100%;
}

.task-form {
    max-width: 750px;
    margin: 0 auto;
}

.form-section {
    background: #fff;
    border-radius: 8px;
    padding: 16px 20px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f2f5;
}

.section-title i {
    font-size: 16px;
    color: #1890ff;
}

.task-form ::v-deep .el-form-item {
    margin-bottom: 16px;
}

.task-form ::v-deep .el-form-item:last-child {
    margin-bottom: 0;
}

.task-form ::v-deep .el-input,
.task-form ::v-deep .el-select {
    width: 100%;
}

.task-form ::v-deep .el-radio-group {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
}

.task-form ::v-deep .el-radio.is-bordered {
    margin: 0;
    padding: 10px 16px;
    height: auto;
}

.task-form ::v-deep .el-radio.is-bordered i {
    margin-right: 6px;
    font-size: 16px;
}

.account-list {
    margin-top: 12px;
}

.account-item {
    margin-bottom: 10px;
    padding: 12px;
    background: #f9fafb;
    border-radius: 6px;
    border: 1px solid #e8e8e8;
}

.account-item:hover {
    border-color: #1890ff;
    background: #f0f9ff;
}

.account-item ::v-deep .el-select {
    width: 100%;
}
.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;
}

.content-dialog-header {
    margin-top: -12px;
    margin-bottom: 24px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: center;
    gap: 20px;
    font-size: 14px;
    color: #606266;
}

.content-dialog-audio {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    padding: 10px 12px;
    background: #f5f7fa;
    border-radius: 4px;
}

.content-dialog-audio .audio-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
}

.content-dialog-audio audio {
    flex: 1;
    max-width: 400px;
    height: 32px;
}

/* AI标签样式优化 */
.ai-tags-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 4px 0;
    max-height: 270px;
    overflow-y: auto;
    overflow-x: hidden;
    scroll-behavior: smooth;
}

.ai-tags-container::-webkit-scrollbar {
    width: 6px;
}

.ai-tags-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.ai-tags-container::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
    transition: background 0.3s ease;
}

.ai-tags-container::-webkit-scrollbar-thumb:hover {
    background: #909399;
}

.ai-tag-item {
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 10px 12px;
    transition: all 0.3s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
    flex-shrink: 0;
}

.ai-tag-item:hover {
    border-color: #c0c4cc;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transform: translateY(-1px);
}

.tag-main-content {
    display: flex;
    align-items: baseline;
    gap: 8px;
    margin-bottom: 6px;
}

.tag-property-name {
    font-size: 13px;
    color: #909399;
    font-weight: 500;
    white-space: nowrap;
    flex-shrink: 0;
}

.tag-property-value {
    font-size: 13px;
    color: #303133;
    font-weight: 600;
    flex: 1;
    word-break: break-all;
}

.tag-meta-info {
    display: flex;
    align-items: center;
    gap: 6px;
    padding-top: 6px;
    border-top: 1px dashed #e4e7ed;
}

.meta-tag {
    font-size: 12px;
    padding: 0 8px;
    height: 22px;
    line-height: 20px;
    border-radius: 4px;
    font-weight: 500;
}

.meta-tag i {
    margin-right: 3px;
    font-size: 12px;
}

.intention-tag {
    background: linear-gradient(135deg, #fff1f0 0%, #ffffff 100%);
    border-color: #ffa39e;
    color: #cf1322;
}

.ratio-tag {
    background: linear-gradient(135deg, #f6ffed 0%, #ffffff 100%);
    border-color: #b7eb8f;
    color: #389e0d;
}

.no-tags {
    color: #c0c4cc;
    font-size: 13px;
    font-style: italic;
}
</style>
