<template>
  <div class="merchant-chat-list">
    <div class="page-header">
      <h2>客户消息列表</h2>
      <el-button type="primary" @click="loadChatList" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <div class="chat-list-container" v-loading="loading">
      <el-table :data="chatList" style="width: 100%" empty-text="暂无客户消息">
        <el-table-column prop="userId" label="用户ID" width="100" />
        
        <el-table-column prop="lastMessageContent" label="最后消息" min-width="300">
          <template #default="{ row }">
            <span v-if="row.lastMessageContent">{{ row.lastMessageContent }}</span>
            <span v-else style="color: #909399">暂无消息</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="merchantUnreadCount" label="未读" width="80">
          <template #default="{ row }">
            <el-badge 
              v-if="row.merchantUnreadCount > 0" 
              :value="row.merchantUnreadCount" 
              type="danger" 
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="lastMessageTime" label="时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.lastMessageTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" @click="goToChat(row)">
              进入聊天
            </el-button>
            <el-button type="text" @click="copyLink(row)">
              复制链接
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import axios from 'axios'

// 会话记录类型
interface Conversation {
  conversationId: number
  userId: number
  merchantId: number
  lastMessageId?: number
  lastMessageContent?: string
  lastMessageTime?: string
  userUnreadCount: number
  merchantUnreadCount: number
  status: string
}

// 类型定义
interface UserInfo {
  accountId: number
  accountName: string
  accountPassword?: string
  accountPhone?: string | null
  accountType?: string
  accountImg?: string | null
  accountGender?: string
  accountTag?: string | null
  salary?: number | null
  isDeleted?: number
  deletedAt?: string | null
  createdAt?: string
  updatedAt?: string
}

// StorageManager 工具类
class StorageManager {
  static getUserInfo(): UserInfo | null {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        return JSON.parse(userInfoStr)
      } catch {
        return null
      }
    }
    return null
  }

  static setUserInfo(userInfo: UserInfo): void {
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  }

  static clearUserInfo(): void {
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')
  }

  static getToken(): string | null {
    return localStorage.getItem('token')
  }
}

const getAccountId = (): number | null => {
  const userInfo = StorageManager.getUserInfo()
  return userInfo ? userInfo.accountId : null
}

// 响应式数据
const merchantId = ref<number | null>(getAccountId()) // 修复：使用ref包装
const chatList = ref<Conversation[]>([])
const loading = ref(false)

// API基础URL
const API_BASE_URL = 'http://localhost:8080'

// 生命周期
onMounted(() => {
  if (merchantId.value) {
    loadChatList()
  } else {
    ElMessage.error('未找到商家信息，请重新登录')
  }
})

// 加载聊天列表
const loadChatList = async () => {
  if (!merchantId.value) {
    ElMessage.error('商家ID不存在')
    return
  }

  loading.value = true
  try {
    const response = await axios.get(`${API_BASE_URL}/api/chat/merchant-conversations`, {
      params: { merchantId: merchantId.value }
    })
    
    if (response.data.code === 200) {
      chatList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.msg || '加载失败')
    }
  } catch (error) {
    console.error('加载聊天列表失败:', error)
    ElMessage.error('加载聊天列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 生成聊天链接
const getChatLink = (row: Conversation): string => {
  return `/chat?userId=${row.userId}&merchantId=${row.merchantId}&currentUserId=${row.merchantId}&type=merchant`
}

// 跳转到聊天页面
const goToChat = (row: Conversation) => {
  const chatLink = getChatLink(row)
  // 使用 router 导航或 window.open
  window.open(chatLink, '_blank')
}

// 复制链接
const copyLink = async (row: Conversation) => {
  const chatLink = `${window.location.origin}${getChatLink(row)}`
  try {
    await navigator.clipboard.writeText(chatLink)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const input = document.createElement('input')
    input.value = chatLink
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    ElMessage.success('链接已复制')
  }
}

// 格式化时间
const formatTime = (time: string | null | undefined): string => {
  if (!time) return '-'
  
  try {
    const date = new Date(time)
    const now = new Date()
    const diffTime = now.getTime() - date.getTime()
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
    
    if (diffDays === 0) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    } else if (diffDays === 1) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    } else if (diffDays < 7) {
      return diffDays + '天前'
    } else {
      return date.toLocaleDateString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  } catch (error) {
    console.error('时间格式化错误:', error)
    return '-'
  }
}
</script>

<style scoped lang="scss">
.merchant-chat-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  
  h2 {
    margin: 0;
    color: #303133;
    font-size: 20px;
  }
}

.chat-list-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

:deep(.el-table) {
  .el-badge {
    vertical-align: middle;
  }
}
</style>
