<template>
  <div class="conversation-list-container">
    <!-- 筛选表单折叠面板 -->
    <el-collapse v-model="activeCollapse" class="filter-collapse" size="small">
      <el-collapse-item name="filter">
        <template #title>
          <div class="collapse-header">
            <span class="collapse-title">筛选条件</span>
            <div class="header-buttons" @click.stop>
              <el-button type="primary" size="small" @click="handleQuery">查询</el-button>
              <el-button size="small" @click="handleReset">重置</el-button>
            </div>
          </div>
        </template>
        <el-form :model="filterForm" inline label-width="80px" size="small">
          <el-form-item label="快捷范围">
            <el-select v-model="filterForm.quickRange" placeholder="请选择" clearable style="width: 150px"
              @change="handleQuickRangeChange">
              <el-option label="今天" value="today"></el-option>
              <el-option label="最近3天" value="last3"></el-option>
              <el-option label="最近7天" value="last7"></el-option>
              <el-option label="最近30天" value="last30"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="开始日期">
            <el-date-picker v-model="filterForm.startDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              clearable class="date-picker" @change="handleManualDateChange" />
          </el-form-item>

          <el-form-item label="结束日期">
            <el-date-picker v-model="filterForm.endDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              clearable class="date-picker" @change="handleManualDateChange" />
          </el-form-item>

          <el-form-item label="用户">
            <el-select v-model="filterForm.userKey" placeholder="请选择用户" clearable filterable remote
              :remote-method="handleUserSearch" :loading="userLoading" style="width: 200px">
              <el-option v-for="user in userList" :key="user.userKey" :label="user.userName"
                :value="user.userKey"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="消息类型">
            <el-select v-model="filterForm.messageType" placeholder="请选择消息类型" clearable style="width: 150px">
              <el-option label="公有" :value="1"></el-option>
              <el-option label="私有" :value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="部门">
            <el-select v-model="filterForm.department" placeholder="请选择部门" clearable style="width: 150px">
              <el-option v-for="dept in departmentList" :key="dept" :label="dept" :value="dept"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>

    <!-- 会话记录列表 -->
    <el-scrollbar :style="{ height: scrollbarHeight }" @scroll="handleScroll">
      <div v-loading="loading" class="descriptions-container">
        <div v-for="(item, index) in conversationList" :key="index" class="descriptions-item">
          <el-text type="info" size="small">
            {{ formatDateTime(item.recordTime) }} | {{ item.userName }} | {{ item.department }} |
            <el-icon v-if="item.messageType === 1"><OfficeBuilding /></el-icon>
            <el-icon v-else><User /></el-icon>
             |
             <el-icon v-if="item.sendMethod === 'text'"><EditPen /></el-icon>
            <el-icon v-else><Microphone /></el-icon>
            {{ item.speakingTime ? item.speakingTime + 's' : '' }}
          </el-text>
          
          <br />
          <el-text size="small">{{ item.conversationContent }}</el-text>
        </div>

        <!-- 加载更多提示 -->
        <div v-if="loadingMore" class="loading-more">
          <el-icon class="is-loading">
            <Loading />
          </el-icon>
          <span>正在加载中...</span>
        </div>
        <div v-else-if="!hasMoreData" class="no-more-data">
          <span>已加载全部数据</span>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'
import { formatPhoneNumber, formatDateTime, formatTimestamp } from '../utils/formatters'
import { Loading, OfficeBuilding, User, EditPen, Microphone } from '@element-plus/icons-vue'

// 加载状态
const loading = ref(false)
const userLoading = ref(false)

// 折叠面板状态
const activeCollapse = ref(['filter'])

// 计算滚动容器高度
const scrollbarHeight = computed(() => {
  return activeCollapse.value.includes('filter') ? 'calc(100vh - 350px)' : 'calc(100vh - 160px)'
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20) // 固定分页大小为20条/页
const total = ref(0)
const loadingMore = ref(false)
const hasMoreData = ref(true)

// 空状态文本
const emptyText = computed(() => loading.value ? '加载中...' : '暂无数据')

// 筛选表单数据
const filterForm = reactive({
  quickRange: 'last7',
  startDate: '',
  endDate: '',
  userKey: '',
  messageType: '',
  department: ''
})

const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const addDays = (date, days) => {
  const d = new Date(date)
  d.setDate(d.getDate() + days)
  return d
}

const applyQuickRange = (range) => {
  const today = new Date()
  const end = formatDate(today)
  let start = end

  if (range === 'today') start = end
  if (range === 'last3') start = formatDate(addDays(today, -2))
  if (range === 'last7') start = formatDate(addDays(today, -6))
  if (range === 'last30') start = formatDate(addDays(today, -29))

  filterForm.startDate = start
  filterForm.endDate = end
}

const handleQuickRangeChange = (value) => {
  if (!value) return
  applyQuickRange(value)
}

const handleManualDateChange = () => {
  // 手动修改开始/结束日期时，取消快捷范围选中态
  filterForm.quickRange = ''
}

// 会话记录列表
const conversationList = ref([])

// 用户列表（用于筛选）
const userList = ref([])

// 部门列表（用于筛选）
const departmentList = ref([])

// 查询会话记录
const handleQuery = () => {
  currentPage.value = 1
  fetchConversations()
}

// 重置筛选条件
const handleReset = () => {
  // 重置表单
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })

  // 默认最近7天
  filterForm.quickRange = 'last7'
  applyQuickRange('last7')

  currentPage.value = 1
  fetchConversations()
}

// 滚动处理
const handleScroll = ({ scrollTop, scrollHeight, clientHeight }) => {
  // 当滚动到底部100px以内时加载下一页
  if (scrollHeight - scrollTop - clientHeight < 100 && !loadingMore.value && hasMoreData.value) {
    loadNextPage()
  }
}

// 加载下一页数据
const loadNextPage = () => {
  if (loadingMore.value || !hasMoreData.value) return

  loadingMore.value = true
  currentPage.value++
  fetchConversations(true) // 传入true表示加载更多
}

// 远程搜索用户
const handleUserSearch = (query) => {
  if (query) {
    userLoading.value = true
    // 过滤用户列表
    setTimeout(() => {
      const allUsers = originalUserList.value
      userList.value = allUsers.filter(user =>
        user.userName.toLowerCase().includes(query.toLowerCase())
      )
      userLoading.value = false
    }, 200)
  } else {
    userList.value = [...originalUserList.value]
  }
}

// 原始用户列表（用于搜索过滤）
const originalUserList = ref([])

// 获取会话记录
const fetchConversations = async (isLoadMore = false) => {
  if (isLoadMore) {
    loadingMore.value = true
  } else {
    loading.value = true
    conversationList.value = [] // 非加载更多时清空列表
    hasMoreData.value = true // 重置加载状态
    currentPage.value = 1 // 重置当前页
  }

  try {
    // 构建请求参数
    const params = {
      startTime: filterForm.startDate ? `${filterForm.startDate}T00:00:00` : null,
      endTime: filterForm.endDate ? `${filterForm.endDate}T23:59:59.999` : null,
      userKey: filterForm.userKey,
      messageType: filterForm.messageType ? Number(filterForm.messageType) : null,
      department: filterForm.department,
      page: currentPage.value,
      pageSize: pageSize.value
    }

    // 调用API获取会话记录
    const data = await request.post('/Admin/QueryConversations', JSON.stringify(params))

    // 检查返回数据格式，确保是数组
    const rawData = Array.isArray(data) ? data : data.data || []

    // 按时间排序（最新的记录在前面）
    const sortedData = rawData.sort((a, b) => {
      return b.recordTimeUTCStamp - a.recordTimeUTCStamp
    })

    // 如果是加载更多，则追加数据，否则替换数据
    if (isLoadMore) {
      conversationList.value = [...conversationList.value, ...sortedData]
    } else {
      conversationList.value = sortedData
    }

    total.value = conversationList.value.length

    // 判断是否已加载全部数据
    if (sortedData.length < pageSize.value) {
      hasMoreData.value = false
    }
  } catch (error) {
    ElMessage.error('获取会话记录失败：' + error.message)
    if (!isLoadMore) {
      conversationList.value = []
      total.value = 0
    }
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 获取用户列表（用于筛选）
const fetchUsers = async () => {
  try {
    // 调用API获取用户列表
    const data = await request.get('/Admin/QueryUsers')

    // 检查返回数据格式，确保是数组
    const rawData = Array.isArray(data) ? data : data.data || []

    // 转换数据格式，只取userName和userKey
    const users = rawData.map(item => ({
      userKey: item.userKey,
      userName: item.userName
    }))

    userList.value = users
    originalUserList.value = [...users]

    // 提取部门列表
    const depts = [...new Set(rawData.map(user => user.department))]
    departmentList.value = depts.filter(dept => dept)
  } catch (error) {
    ElMessage.error('获取用户列表失败：' + error.message)
    userList.value = []
    originalUserList.value = []
    departmentList.value = []
  }
}

// 页面初始化
onMounted(() => {
  // 默认最近7天
  applyQuickRange('last7')
  fetchUsers()
  fetchConversations()
})
</script>

<style scoped>
.conversation-list-container {
  padding: 20px 0;
  height: calc(100% - 64px);
  display: flex;
  flex-direction: column;
}

/* 折叠面板样式 */
.filter-collapse {
  margin-bottom: 20px;
}

.filter-collapse :deep(.el-collapse-item__header) {
  height: auto;
  padding: 12px 16px;
  line-height: normal;
}

.collapse-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 20px;
}

.collapse-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.header-buttons {
  display: flex;
  gap: 8px;
}

.header-buttons .el-button {
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 手机号样式 */
.phone-number {
  cursor: pointer;
  color: #409eff;
  text-decoration: underline;
}

.phone-number:hover {
  color: #66b1ff;
}

/* 加载更多样式 */
.loading-more,
.no-more-data {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
  color: #909399;
  font-size: 14px;
}

.loading-more .el-icon {
  margin-right: 8px;
}

/* Descriptions容器样式 */
.descriptions-container {
  width: 100%;
}

/* 每个Descriptions项的样式 */
.descriptions-item {
  margin-bottom: 2px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 会话内容样式 */
.conversation-content {
  margin-top: 0px;
}

/* 响应式样式 */
@media (max-width: 767px) {
  .conversation-list-container {
    padding: 6px 0;
  }

  .el-form {
    display: flex;
    flex-direction: column;
    align-items: stretch;
  }

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

  .el-date-picker,
  .el-select {
    width: 100% !important;
  }

  /* 响应式调整Descriptions列数 */
  .el-descriptions {
    :deep(.el-descriptions__table) {
      width: 100%;
    }

    :deep(.el-descriptions__cell) {
      width: 50%;
    }
  }
}
</style>
