<template>
  <div class="app-container lobster-chat-aggregate">
    <!-- 渠道筛选 tabs -->
    <el-tabs v-model="activeChannel" @tab-click="onTabClick" type="card">
      <el-tab-pane label="全部" name="" />
      <el-tab-pane v-for="ch in channels" :key="ch.channelType" :name="ch.channelType">
        <span slot="label">{{ ch.displayName }} <el-badge :value="ch.sessionCount" :hidden="!ch.sessionCount" /></span>
      </el-tab-pane>
    </el-tabs>

    <!-- 搜索 -->
    <div class="filter-bar">
      <el-input v-model="keyword" placeholder="搜索用户ID或消息内容" prefix-icon="el-icon-search" clearable
        style="width:300px; margin-right:12px" @clear="loadSessions" @keyup.enter.native="loadSessions" size="small" />
      <el-button type="primary" size="small" icon="el-icon-search" @click="loadSessions">搜索</el-button>
      <el-button size="small" icon="el-icon-refresh" @click="loadSessions">刷新</el-button>
    </div>

    <el-row :gutter="12" style="margin-top:12px">
      <!-- 会话列表 -->
      <el-col :span="8">
        <div class="session-list card-style">
          <div class="list-header">会话列表 ({{ sessions.length }})</div>
          <div v-loading="loading" class="list-body">
            <div v-if="sessions.length === 0 && !loading" class="empty">暂无会话</div>
            <div v-for="s in sessions" :key="s.session_id"
              :class="['session-item', { active: currentSession && currentSession.session_id === s.session_id }]"
              @click="selectSession(s)">
              <div class="session-top">
                <span :class="['channel-tag', s.channel_type || 'QW']">
                  {{ channelLabel(s.channel_type) }}
                </span>
                <span class="time">{{ s.last_msg_time || s.create_time | fmtTime }}</span>
              </div>
              <div class="user-id">{{ s.external_user_id || s.channel_source_id || s.user_id || '-' }}</div>
              <div class="last-msg">{{ s.last_msg || '-' | truncate(40) }}</div>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 消息详情 -->
      <el-col :span="16">
        <div v-if="!currentSession" class="card-style empty-chat">请选择左侧会话查看详情</div>
        <div v-else class="card-style chat-detail">
          <div class="detail-header">
            <span>{{ channelLabel(currentSession.channel_type) }} 会话详情</span>
            <span class="header-info">用户: {{ currentSession.external_user_id || currentSession.channel_source_id || currentSession.user_id }}</span>
            <span class="header-info">Session: {{ currentSession.session_id }}</span>
            <span class="header-status" :class="currentSession.status===1?'online':''">
              {{ currentSession.status===1 ? '在线' : '已结束' }}
            </span>
          </div>
          <div v-loading="msgLoading" class="msg-body">
            <div v-if="messages.length === 0 && !msgLoading" class="empty">暂无消息记录</div>
            <div v-for="m in messages" :key="m.msg_id"
              :class="['msg-item', m.send_type === 1 ? 'from-customer' : 'from-ai']">
              <div class="msg-meta">
                <span class="msg-sender">{{ m.send_type === 1 ? '客户' : 'AI' }}</span>
                <span v-if="m.channel_type" :class="['channel-tag-small', m.channel_type]">{{ m.channel_type }}</span>
                <span class="msg-time">{{ m.create_time | fmtTime }}</span>
              </div>
              <div class="msg-content">{{ m.content }}</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getChatAggregate, getChatMessages } from '@/api/workflow/lobster'

const CHANNEL_LABELS = {
  QW: '企微', WX: '个微', IM: 'IM', WHATSAPP: 'WhatsApp',
  LINE: 'Line', TELEGRAM: 'Telegram', APP_IM: 'APP',
  TMALL: '天猫', JD: '京东', DOUYIN_DM: '抖音私信',
  KUAISHOU_DM: '快手', XIAOHONGSHU_DM: '小红书', DOUYIN_EC: '抖音电商'
}

export default {
  name: 'LobsterChatAggregate',
  filters: {
    fmtTime(v) { return v ? v.replace('T',' ').substring(0,19) : '-' },
    truncate(v, len) { return v && v.length > len ? v.substring(0,len)+'...' : (v||'-') }
  },
  data() {
    return {
      activeChannel: '',
      keyword: '',
      channels: [],
      sessions: [],
      currentSession: null,
      messages: [],
      loading: false,
      msgLoading: false
    }
  },
  mounted() { this.loadSessions() },
  methods: {
    channelLabel(type) { return CHANNEL_LABELS[type] || type || '未知' },
    loadSessions() {
      this.loading = true
      const params = {}
      if (this.activeChannel) params.channelType = this.activeChannel
      if (this.keyword) params.keyword = this.keyword
      getChatAggregate(params).then(res => {
        this.sessions = (res.data && Array.isArray(res.data)) ? res.data : (res.data && res.data.records || [])
        this.buildChannelTabs()
      }).finally(() => { this.loading = false })
    },
    buildChannelTabs() {
      const map = {}
      this.sessions.forEach(s => {
        const ct = s.channel_type || 'QW'
        if (!map[ct]) map[ct] = { channelType: ct, displayName: this.channelLabel(ct), sessionCount: 0 }
        map[ct].sessionCount++
      })
      this.channels = Object.values(map)
    },
    selectSession(s) {
      this.currentSession = s
      this.messages = []
      this.msgLoading = true
      getChatMessages(s.session_id).then(res => {
        this.messages = res.data || []
      }).finally(() => { this.msgLoading = false })
    },
    onTabClick() { this.loadSessions() }
  }
}
</script>

<style scoped>
.lobster-chat-aggregate { padding:0; }
.filter-bar { margin-bottom:8px; }
.card-style { border:1px solid #ebeef5; border-radius:4px; background:#fff; }
.session-list { height:calc(100vh - 200px); overflow:hidden; display:flex; flex-direction:column; }
.list-header { padding:12px 16px; border-bottom:1px solid #ebeef5; font-weight:600; font-size:14px; background:#fafafa; }
.list-body { flex:1; overflow-y:auto; padding:4px 0; }
.session-item { padding:10px 16px; cursor:pointer; border-bottom:1px solid #f0f2f5; transition:background .2s; }
.session-item:hover { background:#f5f7fa; }
.session-item.active { background:#ecf5ff; border-left:3px solid #409eff; }
.session-top { display:flex; justify-content:space-between; align-items:center; margin-bottom:4px; }
.channel-tag { font-size:11px; padding:1px 6px; border-radius:2px; color:#fff; font-weight:500; }
.channel-tag.QW { background:#07c160; } .channel-tag.WX { background:#2b9939; }
.channel-tag.IM { background:#409eff; } .channel-tag.WHATSAPP { background:#25d366; color:#333; }
.channel-tag.LINE { background:#00b900; } .channel-tag.TELEGRAM { background:#0088cc; }
.channel-tag.TMALL,.channel-tag.JD { background:#ff5000; }
.channel-tag.DOUYIN_DM,.channel-tag.DOUYIN_EC,.channel-tag.KUAISHOU_DM { background:#ff0050; }
.channel-tag.XIAOHONGSHU_DM { background:#fe2c55; }
.time { font-size:11px; color:#999; }
.user-id { font-size:13px; color:#333; margin-bottom:2px; }
.last-msg { font-size:12px; color:#999; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.empty-chat { padding:80px 0; text-align:center; color:#999; height:calc(100vh - 200px); }
.chat-detail { height:calc(100vh - 200px); display:flex; flex-direction:column; }
.detail-header { padding:12px 16px; border-bottom:1px solid #ebeef5; background:#fafafa; display:flex; gap:16px; align-items:center; flex-wrap:wrap; }
.detail-header span { font-size:13px; }
.header-info { color:#666; }
.header-status { font-size:12px; padding:2px 8px; border-radius:10px; background:#f0f0f0; }
.header-status.online { background:#e6f7e6; color:#52c41a; }
.msg-body { flex:1; overflow-y:auto; padding:12px 16px; }
.msg-item { margin-bottom:12px; padding:8px 12px; border-radius:6px; max-width:85%; }
.msg-item.from-customer { background:#f0f2f5; margin-right:auto; }
.msg-item.from-ai { background:#e6f7ff; margin-left:auto; }
.msg-meta { margin-bottom:4px; display:flex; gap:8px; align-items:center; }
.msg-sender { font-size:12px; font-weight:600; color:#666; }
.channel-tag-small { font-size:10px; padding:0 4px; border-radius:2px; background:#eee; color:#888; }
.msg-time { font-size:10px; color:#aaa; margin-left:auto; }
.msg-content { font-size:13px; color:#333; line-height:1.6; word-break:break-word; }
.empty { padding:40px 0; text-align:center; color:#bbb; }
</style>
