<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'

import AdminPaginationBar from '@/components/admin/AdminPaginationBar.vue'
import AdminStatusTag from '@/components/admin/AdminStatusTag.vue'
import { fetchAdminMessageDeliveries } from '@/services/admin'
import type { AdminMessageDeliveryListItem, AdminPagination } from '@/types/admin'
import { formatAdminDateTime } from '@/utils/admin-time'
import { adminMessageDeliveryStatusOptions } from '@/utils/admin-options'

const loading = ref(true)
const errorMessage = ref('')
const items = ref<AdminMessageDeliveryListItem[]>([])

const provider = ref('agiso')
const platform = ref('xianyu')
const status = ref('')
const shopId = ref('')
const platformOrderId = ref('')
const taskNo = ref('')
const dateFrom = ref('')
const dateTo = ref('')

const pagination = ref<AdminPagination>({
  page: 1,
  pageSize: 20,
  total: 0,
})

const summary = computed(() => ({
  successCount: items.value.filter((item) => item.status === 'success').length,
  failedCount: items.value.filter((item) => item.status === 'failed').length,
  pendingCount: items.value.filter((item) => item.status === 'pending').length,
}))

async function loadMessageDeliveries(page = pagination.value.page) {
  loading.value = true
  errorMessage.value = ''

  try {
    const response = await fetchAdminMessageDeliveries({
      page,
      pageSize: pagination.value.pageSize,
      provider: provider.value.trim(),
      platform: platform.value.trim(),
      status: status.value.trim(),
      shopId: shopId.value.trim(),
      platformOrderId: platformOrderId.value.trim(),
      taskNo: taskNo.value.trim(),
      dateFrom: dateFrom.value.trim(),
      dateTo: dateTo.value.trim(),
    })
    items.value = response.data.items
    pagination.value = response.data.pagination
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : '读取消息发送记录失败'
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  provider.value = 'agiso'
  platform.value = 'xianyu'
  status.value = ''
  shopId.value = ''
  platformOrderId.value = ''
  taskNo.value = ''
  dateFrom.value = ''
  dateTo.value = ''
  void loadMessageDeliveries(1)
}

function formatResponse(item: AdminMessageDeliveryListItem) {
  if (item.responseStatus <= 0 && !item.errorMessage) {
    return '-'
  }

  const parts = []
  if (item.responseStatus > 0) {
    parts.push(`HTTP ${item.responseStatus}`)
  }

  const msg = String(item.response?.Error_Msg || item.response?.msg || item.response?.message || item.response?.error || '').trim()
  if (msg) {
    parts.push(msg)
  }

  return parts.join(' · ') || item.errorMessage || '-'
}

onMounted(loadMessageDeliveries)
</script>

<template>
  <section class="admin-panel">
    <header class="panel-header">
      <div>
        <h1>消息发送记录</h1>
        <p>查看领取链接消息是否真正发出、平台返回了什么、失败原因是什么。</p>
      </div>
    </header>

    <section class="filter-bar">
      <input v-model="provider" class="text-input" placeholder="服务商，如 agiso" />
      <input v-model="platform" class="text-input" placeholder="业务平台，如 xianyu" />
      <select v-model="status" class="text-input select-input">
        <option v-for="option in adminMessageDeliveryStatusOptions" :key="option.value" :value="option.value">
          {{ option.label }}
        </option>
      </select>
      <input v-model="shopId" class="text-input" placeholder="店铺 ID" />
    </section>

    <section class="filter-bar">
      <input v-model="platformOrderId" class="text-input" placeholder="平台订单号" />
      <input v-model="taskNo" class="text-input" placeholder="任务号" />
      <input v-model="dateFrom" class="text-input" type="date" placeholder="开始日期" />
      <input v-model="dateTo" class="text-input" type="date" placeholder="结束日期" />
      <el-button round type="primary" @click="() => loadMessageDeliveries(1)">查询</el-button>
      <el-button round @click="resetFilters">清空</el-button>
    </section>

    <section v-if="!loading && items.length > 0" class="summary-grid">
      <article class="summary-card">
        <span class="summary-label">当前页成功</span>
        <strong class="summary-value">{{ summary.successCount }}</strong>
      </article>
      <article class="summary-card">
        <span class="summary-label">当前页失败</span>
        <strong class="summary-value">{{ summary.failedCount }}</strong>
      </article>
      <article class="summary-card">
        <span class="summary-label">当前页等待</span>
        <strong class="summary-value">{{ summary.pendingCount }}</strong>
      </article>
    </section>

    <p v-if="errorMessage" class="error-copy">{{ errorMessage }}</p>
    <div v-if="loading" class="empty-block">消息发送记录加载中</div>
    <div v-else-if="items.length === 0" class="empty-block">当前筛选下还没有消息发送记录。</div>

    <div v-else class="table-card">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>来源</th>
            <th>订单 / 任务</th>
            <th>发送状态</th>
            <th>消息内容</th>
            <th>Claim 链接</th>
            <th>接口结果</th>
            <th>时间</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in items" :key="item.deliveryId">
            <td>#{{ item.deliveryId }}</td>
            <td>
              <div class="cell-stack">
                <div class="cell-title">{{ item.provider || '-' }} / {{ item.platform || '-' }}</div>
                <div class="cell-subtle">{{ item.shopName || item.shopId || '-' }}</div>
                <div class="cell-subtle">{{ item.channel || '-' }}</div>
              </div>
            </td>
            <td>
              <div class="cell-stack">
                <div class="cell-title">{{ item.platformOrderId || '-' }}</div>
                <div class="meta-chip-row">
                  <span v-if="item.orderId" class="meta-chip">
                    订单
                    <RouterLink class="inline-link" :to="`/admin/orders/${item.orderId}`">{{ item.orderId }}</RouterLink>
                  </span>
                  <span v-if="item.taskId" class="meta-chip">
                    任务
                    <RouterLink class="inline-link" :to="`/admin/tasks/${item.taskId}`">{{ item.taskNo || item.taskId }}</RouterLink>
                  </span>
                </div>
                <div v-if="item.taskStatus" class="tag-row">
                  <AdminStatusTag :status="item.taskStatus" />
                </div>
              </div>
            </td>
            <td>
              <div class="cell-stack">
                <div class="tag-row">
                  <AdminStatusTag :status="item.status" />
                </div>
                <div class="cell-subtle">HTTP {{ item.responseStatus || 0 }}</div>
                <div v-if="item.errorMessage" class="error-inline">{{ item.errorMessage }}</div>
              </div>
            </td>
            <td>
              <div class="message-cell" :title="item.messageContent">
                {{ item.messageContent || '-' }}
              </div>
            </td>
            <td>
              <a v-if="item.claimUrl" class="claim-link" :href="item.claimUrl" target="_blank" rel="noreferrer">
                打开链接
              </a>
              <span v-else>-</span>
            </td>
            <td>
              <div class="cell-stack">
                <div class="cell-title">{{ formatResponse(item) }}</div>
                <div v-if="item.requestUrl" class="cell-subtle">{{ item.requestUrl }}</div>
              </div>
            </td>
            <td>
              <div class="cell-stack">
                <div class="cell-title">创建 {{ formatAdminDateTime(item.createdAt) }}</div>
                <div class="cell-subtle">发送 {{ formatAdminDateTime(item.sentAt) }}</div>
                <div class="cell-subtle">更新 {{ formatAdminDateTime(item.updatedAt) }}</div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <AdminPaginationBar
        :page="pagination.page"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :loading="loading"
        @change="loadMessageDeliveries"
      />
    </div>
  </section>
</template>

<style scoped>
.admin-panel {
  display: grid;
  gap: 16px;
}

.panel-header h1 {
  margin: 0;
  color: #1d3555;
}

.panel-header p {
  margin: 8px 0 0;
  color: #64748b;
}

.filter-bar {
  display: flex;
  gap: 12px;
  align-items: center;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.summary-card,
.table-card,
.empty-block,
.error-copy {
  padding: 18px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.94);
  border: 1px solid rgba(86, 108, 138, 0.1);
}

.summary-card {
  display: grid;
  gap: 8px;
}

.summary-label {
  color: #2559a7;
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 0.04em;
}

.summary-value {
  font-size: 30px;
  line-height: 1;
  color: #1d3555;
}

.error-copy {
  color: #b42318;
}

.empty-block {
  color: #64748b;
}

.text-input {
  width: 100%;
  min-height: 42px;
  padding: 0 14px;
  border-radius: 14px;
  border: 1px solid rgba(86, 108, 138, 0.18);
  background: rgba(255, 255, 255, 0.94);
}

.select-input {
  appearance: none;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 10px;
  text-align: left;
  border-bottom: 1px solid rgba(86, 108, 138, 0.08);
  color: #334155;
  vertical-align: top;
}

.data-table th {
  color: #64748b;
  font-size: 13px;
}

.cell-stack {
  display: grid;
  gap: 6px;
}

.cell-title {
  color: #1d3555;
  font-weight: 700;
}

.cell-subtle {
  color: #64748b;
}

.message-cell {
  max-width: 360px;
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}

.claim-link,
.inline-link {
  color: #175cd3;
  text-decoration: none;
}

.meta-chip-row,
.tag-row {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.meta-chip {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  min-height: 28px;
  padding: 0 10px;
  border-radius: 999px;
  background: #f5f8fc;
  color: #304866;
  font-size: 12px;
}

.error-inline {
  color: #b42318;
  line-height: 1.6;
}

@media (max-width: 1180px) {
  .summary-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 980px) {
  .filter-bar,
  .summary-grid {
    grid-template-columns: minmax(0, 1fr);
    display: grid;
  }

  .table-card {
    overflow-x: auto;
  }

  .data-table {
    min-width: 1200px;
  }
}
</style>
