<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>消息查询</span>
        </div>
      </template>

      <!-- Filter Section -->
      <div class="filter-container">
        <el-form :model="queryParams" label-width="90px">
          <el-row :gutter="16">
            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="发送者">
                <el-select
                  v-model="senderType"
                  style="width: 100%"
                  @change="onSenderTypeChange"
                >
                  <el-option label="全部" value="ALL" />
                  <el-option label="用户" value="USER" />
                  <el-option label="应用" value="APP" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col v-if="senderType === 'USER'" :xs="24" :sm="12" :md="16">
              <el-form-item label="发送用户">
                <el-select
                  v-model="queryParams.sender_user_ids"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="输入手机号/姓名搜索"
                  :remote-method="searchSenderUserOptions"
                  :loading="senderUserLoading"
                  style="width: 100%"
                >
                  <el-option
                    v-for="u in senderUserOptions"
                    :key="u.id"
                    :label="userOptionLabel(u)"
                    :value="u.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col v-else-if="senderType === 'APP'" :xs="24" :sm="12" :md="16">
              <el-form-item label="发送应用">
                <el-select
                  v-model="queryParams.sender_app_ids"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="输入应用名/app_id 搜索"
                  :remote-method="searchAppOptions"
                  :loading="appLoading"
                  style="width: 100%"
                >
                  <el-option
                    v-for="a in appOptions"
                    :key="a.id"
                    :label="appOptionLabel(a)"
                    :value="a.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="接收者">
                <el-select
                  v-model="queryParams.receiver_user_ids"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="输入手机号/姓名搜索"
                  :remote-method="searchReceiverUserOptions"
                  :loading="receiverUserLoading"
                  style="width: 100%"
                >
                  <el-option
                    v-for="u in receiverUserOptions"
                    :key="u.id"
                    :label="userOptionLabel(u)"
                    :value="u.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="关键词">
                <el-input
                  v-model="queryParams.keyword"
                  placeholder="标题或内容包含"
                  clearable
                  @keyup.enter="handleSearch"
                />
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="消息类型">
                <el-select
                  v-model="queryParams.msg_type"
                  placeholder="全部"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="私信 MESSAGE" value="MESSAGE" />
                  <el-option label="应用通知 NOTIFICATION" value="NOTIFICATION" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="内容类型">
                <el-select
                  v-model="queryParams.content_type"
                  placeholder="全部"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="文本 TEXT" value="TEXT" />
                  <el-option label="图片 IMAGE" value="IMAGE" />
                  <el-option label="视频 VIDEO" value="VIDEO" />
                  <el-option label="文件 FILE" value="FILE" />
                  <el-option label="申请通知 USER_NOTIFICATION" value="USER_NOTIFICATION" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="已读状态">
                <el-select
                  v-model="readState"
                  placeholder="全部"
                  clearable
                  style="width: 100%"
                  @change="onReadStateChange"
                >
                  <el-option label="已读" value="read" />
                  <el-option label="未读" value="unread" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="16">
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24" style="text-align: right">
              <el-button type="primary" :loading="loading" @click="handleSearch">
                <el-icon><Search /></el-icon>
                <span>查询</span>
              </el-button>
              <el-button @click="resetQuery">
                <el-icon><Refresh /></el-icon>
                <span>重置</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- Table Section -->
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="类型" width="110">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'NOTIFICATION' ? 'warning' : ''" effect="plain">
              {{ scope.row.type === 'NOTIFICATION' ? '应用通知' : '私信' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="内容类型" width="120">
          <template #default="scope">
            <el-tag effect="plain" type="info">{{ contentTypeLabel(scope.row.content_type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="160" show-overflow-tooltip />
        <el-table-column label="内容预览" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ contentPreview(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发送者" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ senderLabel(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="接收者" min-width="170" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ receiverLabel(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="归属应用" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.app_id">
              {{ scope.row.app_name || scope.row.app_app_id || `APP-${scope.row.app_id}` }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="已读" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.is_read ? 'success' : 'danger'" effect="plain">
              {{ scope.row.is_read ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发送时间" width="170">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="详情" width="80" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="showDetails(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Details Dialog -->
    <el-dialog v-model="detailsVisible" title="消息详情" width="640px" align-center>
      <el-descriptions :column="1" border v-if="currentMessage">
        <el-descriptions-item label="消息 ID">{{ currentMessage.id }}</el-descriptions-item>
        <el-descriptions-item label="类型">
          {{ currentMessage.type === 'NOTIFICATION' ? '应用通知' : '私信' }}
        </el-descriptions-item>
        <el-descriptions-item label="内容类型">{{ contentTypeLabel(currentMessage.content_type) }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ currentMessage.title }}</el-descriptions-item>
        <el-descriptions-item label="内容">
          <div class="detail-content">{{ currentMessage.content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="跳转链接" v-if="currentMessage.action_url">
          <span style="word-break: break-all">{{ currentMessage.action_url }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="按钮文案" v-if="currentMessage.action_text">
          {{ currentMessage.action_text }}
        </el-descriptions-item>
        <el-descriptions-item label="发送者">{{ senderLabel(currentMessage) }}</el-descriptions-item>
        <el-descriptions-item label="接收者">{{ receiverLabel(currentMessage) }}</el-descriptions-item>
        <el-descriptions-item label="归属应用">
          <span v-if="currentMessage.app_id">
            {{ currentMessage.app_name || '-' }}
            <span v-if="currentMessage.app_app_id"> ({{ currentMessage.app_app_id }})</span>
          </span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="已读">
          <el-tag :type="currentMessage.is_read ? 'success' : 'danger'" effect="plain">
            {{ currentMessage.is_read ? '已读' : '未读' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发送时间">{{ formatDate(currentMessage.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="阅读时间" v-if="currentMessage.read_at">
          {{ formatDate(currentMessage.read_at) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailsVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import {
  searchAdminMessages,
  searchApps,
  type AdminMessageItem,
  type AdminMessageQueryParams,
  type AdminAppOption,
  type MessageType,
  type ContentType,
} from '../../../api/admin_messages'
import { searchUsers, type User as UserOption } from '../../../api/users'

const loading = ref(false)
const tableData = ref<AdminMessageItem[]>([])
const dateRange = ref<[string, string] | null>(null)

type SenderType = 'ALL' | 'USER' | 'APP'
const senderType = ref<SenderType>('ALL')
const readState = ref<'read' | 'unread' | ''>('')

interface QueryState {
  keyword: string
  sender_user_ids: number[]
  sender_app_ids: number[]
  receiver_user_ids: number[]
  msg_type?: MessageType
  content_type?: ContentType
  is_read?: boolean
}

const queryParams = reactive<QueryState>({
  keyword: '',
  sender_user_ids: [],
  sender_app_ids: [],
  receiver_user_ids: [],
  msg_type: undefined,
  content_type: undefined,
  is_read: undefined,
})

const pagination = reactive({
  current: 1,
  size: 20,
  total: 0,
})

const detailsVisible = ref(false)
const currentMessage = ref<AdminMessageItem | null>(null)

const senderUserOptions = ref<UserOption[]>([])
const senderUserLoading = ref(false)
const receiverUserOptions = ref<UserOption[]>([])
const receiverUserLoading = ref(false)
const appOptions = ref<AdminAppOption[]>([])
const appLoading = ref(false)

const onSenderTypeChange = (val: SenderType) => {
  if (val !== 'USER') queryParams.sender_user_ids = []
  if (val !== 'APP') queryParams.sender_app_ids = []
}

const onReadStateChange = (val: 'read' | 'unread' | '') => {
  if (val === 'read') queryParams.is_read = true
  else if (val === 'unread') queryParams.is_read = false
  else queryParams.is_read = undefined
}

const userOptionLabel = (u: UserOption) => {
  const name = u.name || u.english_name || ''
  return name ? `${name} (${u.mobile})` : u.mobile
}

const appOptionLabel = (a: AdminAppOption) => {
  if (a.app_name && a.app_id) return `${a.app_name} (${a.app_id})`
  return a.app_name || a.app_id
}

const searchSenderUserOptions = async (q: string) => {
  if (!q) {
    senderUserOptions.value = []
    return
  }
  senderUserLoading.value = true
  try {
    const res = await searchUsers(q)
    senderUserOptions.value = res.data
  } finally {
    senderUserLoading.value = false
  }
}

const searchReceiverUserOptions = async (q: string) => {
  if (!q) {
    receiverUserOptions.value = []
    return
  }
  receiverUserLoading.value = true
  try {
    const res = await searchUsers(q)
    receiverUserOptions.value = res.data
  } finally {
    receiverUserLoading.value = false
  }
}

const searchAppOptions = async (q: string) => {
  appLoading.value = true
  try {
    const res = await searchApps(q || '')
    appOptions.value = res.data
  } finally {
    appLoading.value = false
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    const params: AdminMessageQueryParams = {
      skip: (pagination.current - 1) * pagination.size,
      limit: pagination.size,
      keyword: queryParams.keyword || undefined,
      msg_type: queryParams.msg_type,
      content_type: queryParams.content_type,
      is_read: queryParams.is_read,
    }
    if (senderType.value === 'USER' && queryParams.sender_user_ids.length) {
      params.sender_user_ids = [...queryParams.sender_user_ids]
    }
    if (senderType.value === 'APP' && queryParams.sender_app_ids.length) {
      params.sender_app_ids = [...queryParams.sender_app_ids]
    }
    if (queryParams.receiver_user_ids.length) {
      params.receiver_user_ids = [...queryParams.receiver_user_ids]
    }
    if (dateRange.value) {
      params.start_date = dateRange.value[0]
      params.end_date = dateRange.value[1]
    }

    const res = await searchAdminMessages(params)
    tableData.value = res.data.items
    pagination.total = res.data.total
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.sender_user_ids = []
  queryParams.sender_app_ids = []
  queryParams.receiver_user_ids = []
  queryParams.msg_type = undefined
  queryParams.content_type = undefined
  queryParams.is_read = undefined
  senderType.value = 'ALL'
  readState.value = ''
  dateRange.value = null
  senderUserOptions.value = []
  receiverUserOptions.value = []
  appOptions.value = []
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pagination.size = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchData()
}

const showDetails = (row: AdminMessageItem) => {
  currentMessage.value = row
  detailsVisible.value = true
}

const formatDate = (s?: string | null) => {
  if (!s) return '-'
  return new Date(s).toLocaleString()
}

const contentTypeLabel = (t: ContentType) => {
  const map: Record<ContentType, string> = {
    TEXT: '文本',
    IMAGE: '图片',
    VIDEO: '视频',
    FILE: '文件',
    USER_NOTIFICATION: '申请通知',
  }
  return map[t] || t
}

const contentPreview = (row: AdminMessageItem) => {
  if (row.content_type === 'TEXT' || row.content_type === 'USER_NOTIFICATION') {
    return row.content || ''
  }
  return `[${contentTypeLabel(row.content_type)}]`
}

const senderLabel = (row: AdminMessageItem) => {
  if (row.sender_id) {
    const name = row.sender_name || ''
    const mobile = row.sender_mobile || ''
    if (name && mobile) return `用户：${name} (${mobile})`
    if (mobile) return `用户：${mobile}`
    return `用户：#${row.sender_id}`
  }
  if (row.app_id) {
    const name = row.app_name || row.app_app_id || `APP-${row.app_id}`
    return `应用：${name}`
  }
  return '系统'
}

const receiverLabel = (row: AdminMessageItem) => {
  const name = row.receiver_name || ''
  const mobile = row.receiver_mobile || ''
  if (name && mobile) return `${name} (${mobile})`
  if (mobile) return mobile
  return `#${row.receiver_id}`
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 12px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.detail-content {
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 240px;
  overflow-y: auto;
}
</style>
