<template>
  <div class="app-container chat-page-container">
    <div class="chat-layout-wrapper">
      <!-- 左侧用户列表 -->
      <div class="chat-sidebar-left">
        <div class="search-box">
          <el-input v-model="userSearch" placeholder="搜索" :prefix-icon="Search" clearable />
        </div>
        <div class="user-list">
          <div
            v-for="user in chatUsers"
            :key="user.id"
            :class="['user-item', { active: currentUser?.id === user.id }]"
            @click="selectUser(user)"
          >
            <el-badge :is-dot="user.unread > 0" class="avatar-badge">
              <el-avatar :size="44" :src="user.avatar" />
            </el-badge>
            <div class="user-info">
              <div class="name-time">
                <span class="name">{{ user.name }}</span>
                <span class="time">{{ user.lastTime }}</span>
              </div>
              <div class="last-msg text-ellipsis">{{ user.lastMsg }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间聊天窗口 -->
      <div class="chat-main">
        <div class="chat-header">
          <div class="status-switch">
            <span class="label">坐席上线</span>
            <el-switch v-model="agentOnline" active-color="#13ce66" />
          </div>
          <div class="current-user-name">{{ currentUser?.name || '未选择会话' }}</div>
        </div>

        <div class="chat-messages" ref="messageContainer">
          <div v-for="(msg, index) in messageList" :key="index" :class="['message-row', msg.type === 'mine' ? 'mine' : 'user']">
            <div class="avatar shrink-0">
              <el-avatar :size="36" :src="msg.type === 'mine' ? myAvatar : currentUser?.avatar" />
            </div>
            <div class="message-content">
              <div class="bubble">
                {{ msg.content }}
              </div>
              <div class="time">{{ msg.time }}</div>
            </div>
          </div>
        </div>

        <div class="chat-input-area">
          <div class="toolbar">
            <div class="left-tools">
              <el-icon class="tool-icon"><i-ep-orange /></el-icon>
              <el-icon class="tool-icon"><i-ep-folder /></el-icon>
              <el-icon class="tool-icon plus-icon" @click="showGoodsDialog = true"><i-ep-plus /></el-icon>
            </div>
            <el-button type="primary" size="small" class="end-btn" @click="handleEndSession">结束</el-button>
          </div>
          <el-input
            v-model="inputMsg"
            type="textarea"
            :rows="4"
            placeholder="请输入内容..."
            resize="none"
            class="msg-input"
            @keyup.ctrl.enter="handleSend"
          />
          <div class="input-footer">
            <el-button type="primary" size="default" class="send-btn" @click="handleSend">发送</el-button>
          </div>
        </div>
      </div>

      <!-- 右侧用户信息 -->
      <div class="chat-sidebar-right">
        <template v-if="currentUser">
          <div class="user-profile-header">
            <el-avatar :size="80" :src="currentUser.avatar" class="profile-avatar" />
            <h3 class="profile-name">{{ currentUser.name }}</h3>
            <div class="profile-meta">
              <span>{{ currentUser.location }}</span>
              <span class="divider">|</span>
              <span>{{ currentUser.gender }}</span>
              <span class="divider">|</span>
              <span>{{ currentUser.age }}岁</span>
            </div>
            <el-link type="primary" :underline="false" class="resume-link" @click="goToStudentDetail">在线简历</el-link>
          </div>

          <div class="contact-info">
            <div class="info-item">
              <span class="value">{{ currentUser.phone }}</span>
            </div>
            <div class="info-item">
              <span class="value">{{ currentUser.email }}</span>
            </div>
            <div class="info-item">
              <span class="label">求职类型：</span>
              <span class="value">{{ currentUser.jobType }}</span>
            </div>
            <div class="info-item">
              <span class="label">意向公司：</span>
              <span class="value">{{ currentUser.targetCompany }}</span>
            </div>
          </div>

          <div class="info-sections">
            <div class="section-card">
              <div class="section-title">账户信息</div>
              <div class="section-content">
                <div class="detail-row"><span class="label">客户ID:</span> {{ currentUser.customerId }}</div>
                <div class="detail-row"><span class="label">注册日期:</span> {{ currentUser.regDate }}</div>
                <div class="detail-row"><span class="label">账户状态:</span> <span class="status-tag">{{ currentUser.status }}</span></div>
                <div class="detail-row"><span class="label">参加测评:</span> {{ currentUser.assessmentCount }}</div>
                <div class="detail-row"><span class="label">投递岗位:</span> {{ currentUser.jobApplyCount }}</div>
                <div class="detail-row"><span class="label">成功入职:</span> {{ currentUser.hireCount }}</div>
              </div>
            </div>

            <div class="section-card">
              <div class="section-title">订单信息</div>
              <div class="section-content">
                <div class="detail-row"><span class="label">订单总数:</span> {{ currentUser.orderTotal }}单</div>
                <div class="detail-row"><span class="label">总消费金额:</span> <span class="price">¥{{ currentUser.totalAmount }}</span></div>
              </div>
            </div>

            <div class="section-card">
              <div class="section-title">咨询次数</div>
              <div class="section-content">
                <div class="detail-row"><span class="label">咨询总数:</span> {{ currentUser.consultTotal }}次</div>
                <div class="detail-row"><span class="label">最近一次沟通:</span> {{ currentUser.lastConsultTime }}</div>
              </div>
            </div>
          </div>
        </template>
        <div v-else class="empty-state">
          <el-empty description="请选择会话查看详情" />
        </div>
      </div>
    </div>

    <!-- 发送商品弹窗 -->
    <el-dialog v-model="showGoodsDialog" title="发送商品" width="800px" class="goods-dialog" append-to-body>
      <div class="dialog-search-bar">
        <el-input v-model="goodsSearch" placeholder="搜索" class="search-input">
          <template #append>
            <el-button type="primary">搜索</el-button>
          </template>
        </el-input>
      </div>

      <el-tabs v-model="activeGoodsTab" class="goods-tabs">
        <el-tab-pane label="测评信息" name="assessment" />
        <el-tab-pane label="岗位信息" name="job" />
        <el-tab-pane label="培训信息" name="training" />
        <el-tab-pane label="商品信息" name="goods" />
      </el-tabs>

      <el-table :data="goodsTableData" border stripe class="goods-table">
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="name" label="测评名称" />
        <el-table-column label="主图" width="80" align="center">
          <template #default="scope">
            <el-image :src="scope.row.image" class="table-img">
              <template #error>
                <div class="image-slot"><el-icon><i-ep-picture /></el-icon></div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="岗位级别" width="100" />
        <el-table-column prop="status" label="状态" width="80" />
        <el-table-column prop="deposit" label="定金" width="80" />
        <el-table-column prop="balance" label="尾款" width="80" />
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="scope">
            <el-tag size="small" type="info">{{ scope.row.stock }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleSendGoods(scope.row)">发送</el-button>
            <el-button v-if="scope.row.canAdd" link type="primary" @click="handleAddUser(scope.row)">添加用户</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

const userAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
const myAvatar = 'https://img.js.design/assets/img/6530a6c0850c9502759e0a02.png';

const userSearch = ref('');
const agentOnline = ref(true);
const inputMsg = ref('');
const messageContainer = ref<HTMLElement | null>(null);

// 聊天用户列表
const chatUsers = ref([
  {
    id: 1,
    name: '山川与星辰',
    avatar: 'https://img.js.design/assets/img/652f7596850c9502759a296e.png',
    lastMsg: '好的，感谢您的耐心指导～',
    lastTime: '20分钟前',
    unread: 1,
  },
  {
    id: 2,
    name: '风败雾散',
    avatar: 'https://img.js.design/assets/img/652f75bd850c9502759a2a34.png',
    lastMsg: '你最近使用效果怎么样？',
    lastTime: '18分钟前',
    unread: 0,
  },
  {
    id: 3,
    name: '月下清影',
    avatar: 'https://img.js.design/assets/img/652f75e2850c9502759a2afe.png',
    lastMsg: '我这边帮你核实一下哦～',
    lastTime: '10分钟前',
    unread: 0,
  },
  {
    id: 4,
    name: '南风未起',
    avatar: 'https://img.js.design/assets/img/652f75f7850c9502759a2b53.png',
    lastMsg: '您的退款已经在处理中了',
    lastTime: '12:26',
    unread: 0,
    location: '湖南·长沙',
    gender: '男',
    age: 32,
    phone: '138-1234-5678',
    email: 'xiaog.li@email.com',
    jobType: '全职',
    targetCompany: 'XXXX公司',
    customerId: 'CUST20250114001',
    regDate: '2023-04-15',
    status: '正常',
    assessmentCount: 3,
    jobApplyCount: 2,
    hireCount: 1,
    orderTotal: 1,
    totalAmount: '12,800',
    consultTotal: 2,
    lastConsultTime: '2025-01-12 15:00'
  }
]);

const currentUser = ref<any>(chatUsers.value[3]); // 默认选中南风未起

const messageList = ref([
  {
    type: 'user',
    content: '你好，我刚咨询的岗位有点问题',
    time: '18:27:11',
  },
  {
    type: 'mine',
    content: '您好，非常抱歉让您遇到了问题！请问具体是什么情况呢？',
    time: '18:28:21',
  },
  {
    type: 'user',
    content: '看不到岗位信息，无法进行测评',
    time: '18:28:52',
  },
]);

// 商品弹窗相关
const showGoodsDialog = ref(false);
const goodsSearch = ref('');
const activeGoodsTab = ref('assessment');
const goodsTableData = ref([
  { id: '2131211', name: '审计A', image: '', level: 'A1', status: '上架', deposit: '122', balance: '122', stock: '标签一', canAdd: true },
  { id: '1221221', name: '审计A', image: '', level: 'A1', status: '上架', deposit: '122122', balance: '122122', stock: '标签一', canAdd: false },
  { id: 'YS21222', name: '审计A', image: '', level: 'A1', status: '上架', deposit: '122122', balance: '122122', stock: '标签一', canAdd: false },
  { id: 'YS21232', name: '审计A', image: '', level: 'A1', status: '上架', deposit: '122122', balance: '122122', stock: '标签一', canAdd: false },
  { id: 'YS22242', name: '审计A', image: '', level: 'A1', status: '上架', deposit: '122122', balance: '122122', stock: '标签一', canAdd: false },
]);

const selectUser = (user: any) => {
  currentUser.value = user;
  // 这里可以加载该用户的聊天记录
};

const handleSend = () => {
  if (!inputMsg.value.trim()) return;
  
  const now = new Date();
  const timeStr = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
  
  messageList.value.push({
    type: 'mine',
    content: inputMsg.value,
    time: timeStr,
  });
  
  inputMsg.value = '';
  scrollToBottom();
};

const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};

const handleEndSession = () => {
  ElMessage.success('已结束当前会话');
};

const handleSendGoods = (row: any) => {
  ElMessage.success(`已向用户发送：${row.name}`);
  showGoodsDialog.value = false;
};

const handleAddUser = (row: any) => {
  ElMessage.success(`已将用户添加到：${row.name}`);
};

const goToStudentDetail = () => {
  if (currentUser.value) {
    router.push({ 
      path: '/system/agent/student-detail', 
      query: { userId: currentUser.value.customerId } 
    });
  }
};

onMounted(() => {
  scrollToBottom();
});
</script>

<style scoped lang="scss">
.chat-page-container {
  height: calc(100vh - 84px);
  padding: 10px;
  background-color: #f5f7fa;

  .chat-layout-wrapper {
    display: flex;
    height: 100%;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }

  /* 左侧侧边栏 */
  .chat-sidebar-left {
    width: 280px;
    border-right: 1px solid #f0f0f0;
    display: flex;
    flex-direction: column;

    .search-box {
      padding: 15px;
      :deep(.el-input__wrapper) {
        background-color: #f5f7fa;
        border-radius: 18px;
        box-shadow: none;
      }
    }

    .user-list {
      flex: 1;
      overflow-y: auto;

      .user-item {
        display: flex;
        padding: 12px 15px;
        cursor: pointer;
        transition: all 0.3s;
        border-left: 3px solid transparent;

        &:hover {
          background-color: #f5f7fa;
        }

        &.active {
          background-color: #ecf5ff;
          border-left-color: #409eff;
        }

        .avatar-badge {
          margin-right: 12px;
        }

        .user-info {
          flex: 1;
          overflow: hidden;

          .name-time {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;

            .name {
              font-weight: 500;
              color: #333;
              font-size: 14px;
            }

            .time {
              font-size: 12px;
              color: #999;
            }
          }

          .last-msg {
            font-size: 12px;
            color: #999;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }

  /* 中间主窗口 */
  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #f0f0f0;
    min-width: 400px;

    .chat-header {
      height: 60px;
      padding: 0 20px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .status-switch {
        display: flex;
        align-items: center;
        gap: 8px;
        .label {
          font-size: 12px;
          color: #666;
        }
      }

      .current-user-name {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        font-weight: 600;
        font-size: 16px;
      }
    }

    .chat-messages {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
      background-color: #fff;

      .message-row {
        display: flex;
        gap: 12px;
        margin-bottom: 20px;
        max-width: 85%;

        &.user {
          .bubble {
            background-color: #f4f4f5;
            color: #333;
            border-radius: 4px 16px 16px 16px;
          }
        }

        &.mine {
          margin-left: auto;
          flex-direction: row-reverse;
          .bubble {
            background: linear-gradient(135deg, #40c9ff 0%, #1890ff 100%);
            color: #fff;
            border-radius: 16px 4px 16px 16px;
          }
          .time {
            text-align: right;
          }
        }

        .bubble {
          padding: 10px 15px;
          font-size: 14px;
          line-height: 1.5;
          word-break: break-all;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
        }

        .time {
          font-size: 11px;
          color: #c0c4cc;
          margin-top: 4px;
        }
      }
    }

    .chat-input-area {
      border-top: 1px solid #f0f0f0;
      padding: 10px 20px 15px;

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

        .left-tools {
          display: flex;
          gap: 15px;
          .tool-icon {
            font-size: 20px;
            color: #606266;
            cursor: pointer;
            &:hover {
              color: #409eff;
            }
          }
          .plus-icon {
            font-weight: bold;
          }
        }
      }

      .msg-input {
        :deep(.el-textarea__inner) {
          border: none;
          padding: 0;
          box-shadow: none;
          background: transparent;
          font-size: 14px;
          &:focus {
            box-shadow: none;
          }
        }
      }

      .input-footer {
        display: flex;
        justify-content: flex-end;
        margin-top: 10px;
        .send-btn {
          width: 80px;
        }
      }
    }
  }

  /* 右侧侧边栏 */
  .chat-sidebar-right {
    width: 320px;
    background-color: #fff;
    overflow-y: auto;
    padding: 20px;

    .user-profile-header {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-bottom: 20px;
      border-bottom: 1px dashed #ebeef5;

      .profile-avatar {
        margin-bottom: 15px;
        border: 4px solid #f0f7ff;
      }

      .profile-name {
        margin: 0 0 10px;
        font-size: 18px;
        color: #303133;
      }

      .profile-meta {
        font-size: 13px;
        color: #909399;
        margin-bottom: 10px;
        .divider {
          margin: 0 8px;
        }
      }

      .resume-link {
        font-size: 12px;
      }
    }

    .contact-info {
      padding: 15px 0;
      border-bottom: 1px dashed #ebeef5;

      .info-item {
        margin-bottom: 10px;
        font-size: 14px;
        display: flex;
        justify-content: center;
        .label {
          color: #909399;
        }
        .value {
          color: #303133;
          font-weight: 500;
        }
      }
    }

    .info-sections {
      .section-card {
        margin-top: 20px;

        .section-title {
          font-size: 12px;
          color: #fff;
          background-color: #409eff;
          padding: 2px 10px;
          display: inline-block;
          border-radius: 2px;
          margin-bottom: 12px;
        }

        .section-content {
          .detail-row {
            font-size: 13px;
            color: #333;
            margin-bottom: 8px;
            display: flex;
            .label {
              color: #909399;
              width: 80px;
              flex-shrink: 0;
            }
            .price {
              color: #f56c6c;
              font-weight: bold;
            }
            .status-tag {
              color: #67c23a;
            }
          }
        }
      }
    }
  }
}

.goods-dialog {
  .dialog-search-bar {
    margin-bottom: 20px;
    .search-input {
      width: 400px;
    }
  }
  .goods-tabs {
    margin-bottom: 20px;
  }
  .table-img {
    width: 40px;
    height: 40px;
    border-radius: 4px;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
    .image-slot {
      font-size: 20px;
      color: #909399;
    }
  }
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .chat-sidebar-right {
    display: none;
  }
}

@media (max-width: 768px) {
  .chat-sidebar-left {
    display: none;
  }
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
