<template>
  <div class="chat-container">
    <div class="header">
      <div class="toggle-buttons">
        <button :class="['toggle-btn', { active: selectedPlatform === 'whatsapp' }]" @click="selectPlatform('whatsapp')">
          <img src="@/assets/onlineChat/whatsapp-icon.png" alt="" />
          WhatsApp
        </button>
        <button :class="['toggle-btn', { active: selectedPlatform === 'facebook' }]" @click="selectPlatform('facebook')">
          <img src="@/assets/onlineChat/facebook-icon.png" alt="" />
          Facebook
        </button>
      </div>
    </div>

    <!-- 主体内容区 -->
    <div class="main-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <!-- 聊天列表 -->
        <div class="chat-list">
          <a-spin v-if="loading" style="width: 100%; padding: 20px" />
          <template v-else>
            <div
              v-for="chat in filteredChats"
              :key="chat.id"
              :class="['chat-item', { active: selectedChatId === chat.id }]"
              @click="selectChat(chat.id)"
            >
              <a-avatar :src="chat.avatar" />
              <div class="chat-info">
                <div class="chat-header">
                  <span class="name">{{ chat.name }}</span>
                  <span class="time">{{ formatChatTime(chat.lastMessageTime) }}</span>
                </div>
                <div class="last-message">{{ chat.lastMessage }}</div>
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 右侧对话详情 -->
      <div class="chat-detail" v-if="selectedChatId">
        <!-- 对话头部信息 -->
        <div class="chat-header">
          <div class="chat-user-info">
            <a-avatar :src="currentChat.avatar" />
            <span class="user-name">{{ currentChat.name }}</span>
          </div>
        </div>

        <!-- 聊天记录区域 -->
        <div class="chat-messages">
          <div v-for="message in currentChatMessages" :key="message.id" :class="['message', message.type]">
            <a-avatar :src="message.avatar" />
            <div class="message-content">
              <div class="message-info">
                <span class="sender">{{ message.sender }}</span>
                <span class="time">{{ formatChatTime(message.time) }}</span>
              </div>
              <div class="message-text">{{ message.content }}</div>
            </div>
          </div>
        </div>

        <!-- 回复输入框 -->
        <div class="chat-input">
          <a-textarea v-model:value="replyMessage" placeholder="请输入消息..." :auto-size="{ minRows: 2, maxRows: 5 }" />
          <a-button type="primary" @click="sendMessage">发送</a-button>
        </div>
      </div>

      <!-- 未选择对话时的提示 -->
      <div class="no-chat-selected" v-else>
        <MessageOutlined style="font-size: 48px" />
        <p>快来选择联系人进入会话吧</p>
      </div>
    </div>
  </div>
</template>

<script>
  import { DownOutlined, MessageOutlined, SearchOutlined } from '@ant-design/icons-vue';
  import axios from 'axios';
import { getAction } from '/@/api/manage/manage';

  export default {
    components: {
      DownOutlined,
      SearchOutlined,
      MessageOutlined,
    },
    data() {
      return {
        selectedPlatform: 'whatsapp', // 默认选中WhatsApp
        showAccountDropdown: false,
        currentAccount: {
          id: 1,
          avatar: '@/assets/onlineChat/whatsapp-icon.png',
          name: 'Adweb AI',
        },
        accounts: [
          {
            id: 1,
            avatar: '@/assets/onlineChat/whatsapp-icon.png',
            name: 'Adweb AI',
          },
          {
            id: 2,
            avatar: '@/assets/onlineChat/whatsapp-icon.png',
            name: 'Adweb AI 2',
          },
        ],
        searchKeyword: '',
        currentTab: 'all',
        selectedChatId: null,
        chats: [],
        messages: {
          1: [
            {
              id: 1,
              type: 'received',
              sender: 'John Doe',
              avatar: '/path/to/avatar1.jpg',
              content: 'Hello, how are you?',
              time: '10:30',
            },
            {
              id: 2,
              type: 'sent',
              sender: 'Me',
              avatar: '/path/to/my-avatar.jpg',
              content: "I'm good, thanks!",
              time: '10:31',
            },
          ],
          2: [
            // messages for chat 2
          ],
        },
        replyMessage: '',
        loading: false,
      };
    },
    computed: {
      filteredChats() {
        return this.chats.filter((chat) => chat.name.toLowerCase().includes(this.searchKeyword.toLowerCase()));
      },
      currentChatMessages() {
        return this.messages[this.selectedChatId] || [];
      },
      currentChat() {
        return this.chats.find((chat) => chat.id === this.selectedChatId) || {};
      },
    },
    created() {
      this.fetchChats();
    },
    methods: {
      selectPlatform(platform) {
        this.selectedPlatform = platform;
        this.fetchChats();
      },
      selectChat(chatId) {
        this.selectedChatId = chatId;
      },
      switchAccount(account) {
        this.currentAccount = account;
        this.showAccountDropdown = false;
      },
      sendMessage() {
        if (!this.replyMessage.trim()) return;

        const newMessage = {
          id: Date.now(),
          type: 'sent',
          sender: 'Me',
          avatar: this.currentAccount.avatar,
          content: this.replyMessage,
          time: new Date().toISOString(),
        };

        if (!this.messages[this.selectedChatId]) {
          this.messages[this.selectedChatId] = [];
        }
        this.messages[this.selectedChatId].push(newMessage);
        this.replyMessage = '';
      },
      async fetchChats() {
        this.loading = true;
        try {
          const siteCode = localStorage.getItem('siteCode');
          const response = await getAction('/marketing/facebook/chat/list', {siteCode:siteCode });
          console.log(response);
          this.chats = response.result.map(chat => ({
            ...chat,
            lastMessageTime: chat.lastMessageTime // 假设接口返回的是有效时间字符串
          }));
        } catch (error) {
          console.error('获取消息列表失败:', error);
        } finally {
          this.loading = false;
        }
      },
      formatChatTime(isoTime) {
        const date = new Date(isoTime);
        const now = new Date();
        const diffInSeconds = Math.floor((now - date) / 1000);
        
        // 当天时间格式
        const timeOptions = { hour: 'numeric', minute: '2-digit', hour12: true };
        
        // 1分钟内显示"刚刚"
        if (diffInSeconds < 60) {
          return '刚刚';
        }
        
        // 今天
        if (date.toDateString() === now.toDateString()) {
          return date.toLocaleTimeString('zh-CN', timeOptions).replace('上午', 'AM').replace('下午', 'PM');
        }
        
        // 昨天
        const yesterday = new Date(now);
        yesterday.setDate(now.getDate() - 1);
        if (date.toDateString() === yesterday.toDateString()) {
          return `昨天 ${date.toLocaleTimeString('zh-CN', timeOptions)}`;
        }
        
        // 本周内显示星期几
        const diffDays = Math.floor(diffInSeconds / 86400);
        if (diffDays < 7) {
          const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
          return `${weekdays[date.getDay()]} ${date.toLocaleTimeString('zh-CN', timeOptions)}`;
        }
        
        // 不同年份显示完整日期
        if (date.getFullYear() !== now.getFullYear()) {
          return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.toLocaleTimeString('zh-CN', timeOptions)}`;
        }
        
        // 默认格式：月/日 时间
        return `${date.getMonth() + 1}/${date.getDate()} ${date.toLocaleTimeString('zh-CN', timeOptions)}`;
      }
    },
  };
</script>

<style scoped>
  .chat-container {
    padding: 20px;
  }

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

  .toggle-buttons {
    display: flex;
    gap: 10px;
  }

  .toggle-btn {
    padding: 8px 16px;
    border: 1px solid #dcdfe6;
    background-color: #fff;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .toggle-btn:hover {
    background-color: #f5f7fa;
  }

  .toggle-btn.active {
    background-color: #409eff;
    color: #fff;
    border-color: #409eff;
  }

  /* 图标样式 */
  .icon-whatsapp,
  .icon-whatsapp-business,
  .icon-facebook {
    display: inline-block;
    width: 20px;
    height: 20px;
    background-size: contain;
    background-repeat: no-repeat;
  }

  .social-management-btn {
    padding: 8px 16px;
    border: 1px solid #dcdfe6;
    background-color: #fff;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .social-management-btn:hover {
    background-color: #f5f7fa;
  }

  .main-content {
    display: flex;
    height: calc(100vh - 220px);
    margin-top: 20px;
    background: #fff;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
  }

  .left-panel {
    width: 300px;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;
  }

  .current-account {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    position: relative;
  }

  .current-account .avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
  }

  .chat-list {
    flex: 1;
    overflow-y: auto;
  }

  .chat-item {
    display: flex;
    padding: 12px 16px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .chat-item:hover {
    background-color: #f5f7fa;
  }

  .chat-item.active {
    background-color: #ecf5ff;
  }

  .chat-info {
    margin-left: 12px;
    flex: 1;
  }

  .chat-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
  }

  .chat-header .time {
    font-size: 12px;
    color: #909399;
  }

  .last-message {
    font-size: 13px;
    color: #606266;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .chat-detail {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .chat-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
  }

  .chat-user-info {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .user-name {
    font-size: 16px;
    font-weight: 500;
  }

  .chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
  }

  .chat-input {
    padding: 16px 20px;
    border-top: 1px solid #e4e7ed;
    display: flex;
    gap: 12px;
    align-items: flex-end;
  }

  .chat-input .ant-textarea-wrapper {
    flex: 1;
  }

  .chat-input .ant-btn {
    height: 40px;
    padding: 0 24px;
  }

  .message {
    display: flex;
    margin-bottom: 20px;
  }

  .message.sent {
    flex-direction: row-reverse;
  }

  .message-content {
    margin: 0 12px;
    max-width: 60%;
  }

  .message.sent .message-content {
    text-align: right;
  }

  .message-info {
    margin-bottom: 4px;
  }

  .message-text {
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .message.sent .message-text {
    background: #409eff;
    color: white;
  }

  .no-chat-selected {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
  }

  .no-chat-selected .anticon {
    font-size: 48px;
    margin-bottom: 16px;
    color: #bfbfbf;
  }

  /* 调整一些样式以匹配 Ant Design 风格 */
  .search-box .ant-input-affix-wrapper {
    border-radius: 4px;
  }

  .chat-item .ant-avatar {
    width: 40px;
    height: 40px;
  }

  .dropdown-icon {
    font-size: 12px;
    color: #909399;
    transition: transform 0.3s;
  }

  .dropdown-icon.is-open {
    transform: rotate(180deg);
  }

  .account-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 10;
  }

  .account-option {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    cursor: pointer;
  }

  .account-option:hover {
    background-color: #f5f7fa;
  }
</style>
