<script lang="ts" setup>
import { ChatLineRound, List, Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { getRechargeLog } from '@/api/model/index.ts';
import type { RechargeLogQueryParams } from '@/api/model/index.ts';
import { isUserVip } from '@/utils/user.ts';
import { showContactUs } from '@/utils/contact-us.ts';

interface RechargeLog {
  id: string;
  content: string;
  rechargeAmount: number;
  creationTime: string;
  expireDateTime: string;
  contactInfo: string;
  remark: string;
  userId: string;
}

const loading = ref(false);
const logData = ref<RechargeLog[]>([]);
const totalCount = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 查询参数
const queryParams = ref<RechargeLogQueryParams>({
  skipCount: 0,
  maxResultCount: 10,
});

// 筛选条件
const dateRange = ref<[Date, Date] | null>(null);
const freeFilter = ref<boolean | null>(null);
const minAmount = ref<number | undefined>(undefined);
const maxAmount = ref<number | undefined>(undefined);

// 快捷时间选择
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 移动端检测
const isMobile = ref(false);

function checkMobile() {
  isMobile.value = window.innerWidth < 768;
}

// 模拟数据获取
async function fetchRechargeLog(resetPage = false) {
  if (resetPage) {
    currentPage.value = 1;
  }

  loading.value = true;
  try {
    const params: RechargeLogQueryParams = {
      skipCount: currentPage.value,
      maxResultCount: queryParams.value.maxResultCount,
      startTime: queryParams.value.startTime,
      endTime: queryParams.value.endTime,
      orderByColumn: queryParams.value.orderByColumn,
      isAsc: queryParams.value.isAsc,
      isFree: queryParams.value.isFree,
      minRechargeAmount: queryParams.value.minRechargeAmount,
      maxRechargeAmount: queryParams.value.maxRechargeAmount,
    };

    const res = await getRechargeLog(params);
    if (res.data) {
      logData.value = res.data.items || [];
      totalCount.value = res.data.totalCount || 0;
    }
  }
  catch (error) {
    console.error('获取充值记录失败:', error);
    ElMessage.error('获取充值记录失败');
    logData.value = [];
    totalCount.value = 0;
  }
  finally {
    loading.value = false;
  }
}

// 排序处理
function handleSortChange({ prop, order }: { prop: string; order: string | null }) {
  if (order) {
    queryParams.value.orderByColumn = prop;
    queryParams.value.isAsc = order === 'ascending' ? 'ascending' : 'descending';
  }
  else {
    queryParams.value.orderByColumn = undefined;
    queryParams.value.isAsc = undefined;
  }
  fetchRechargeLog(true);
}

// 处理分页
function handlePageChange(page: number) {
  currentPage.value = page;
  fetchRechargeLog();
}

// 处理每页大小变化
function handleSizeChange(size: number) {
  pageSize.value = size;
  queryParams.value.maxResultCount = size;
  currentPage.value = 1;
  fetchRechargeLog();
}

// 处理时间筛选
function handleDateChange(value: [Date, Date] | null) {
  if (value && value.length === 2) {
    const startDate = new Date(value[0]);
    startDate.setHours(0, 0, 0, 0);
    const endDate = new Date(value[1]);
    endDate.setHours(23, 59, 59, 999);
    queryParams.value.startTime = startDate.toISOString();
    queryParams.value.endTime = endDate.toISOString();
  }
  else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }
  fetchRechargeLog(true);
}

// 处理是否免费筛选
function handleFreeFilterChange(value: boolean | null) {
  queryParams.value.isFree = value === null ? undefined : value;
  fetchRechargeLog(true);
}

// 处理金额筛选
function handleAmountChange() {
  queryParams.value.minRechargeAmount = minAmount.value;
  queryParams.value.maxRechargeAmount = maxAmount.value;
  fetchRechargeLog(true);
}

// 重置筛选
function resetFilters() {
  dateRange.value = null;
  freeFilter.value = null;
  minAmount.value = undefined;
  maxAmount.value = undefined;
  queryParams.value = {
    maxResultCount: pageSize.value,
    orderByColumn: undefined,
    isAsc: undefined,
    startTime: undefined,
    endTime: undefined,
    isFree: undefined,
    minRechargeAmount: undefined,
    maxRechargeAmount: undefined,
  };
  fetchRechargeLog(true);
}

// 判断是否有活动的筛选条件
const hasActiveFilters = computed(() => {
  return !!dateRange.value || freeFilter.value !== null || minAmount.value !== undefined || maxAmount.value !== undefined;
});

// 刷新数据
function refreshLog() {
  fetchRechargeLog();
}

// 联系售后弹窗
function contactCustomerService() {
  // 如果用户有购买记录，则显示售后群
  if (logData.value.length > 0) {
    showContactUs({ scenario: 'afterSales' });
  }
  else {
    showContactUs({ scenario: 'regular' });
  }
}

// 暴露方法给父组件使用
defineExpose({
  contactCustomerService,
  refresh: fetchRechargeLog,
});

onMounted(() => {
  checkMobile();
  window.addEventListener('resize', checkMobile);
  fetchRechargeLog();
});

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile);
});
</script>

<template>
  <div class="recharge-log-container">
    <div class="log-header">
      <h2 class="log-title">
        <el-icon><List /></el-icon>
        充值记录
      </h2>
      <div class="header-actions">
        <el-tag v-if="totalCount > 0" type="primary" size="default" class="count-tag" effect="plain">
          共 {{ totalCount }} 条记录
        </el-tag>
        <el-tooltip v-if="isUserVip()" content="联系售后" placement="top">
          <el-button circle :loading="loading" @click="contactCustomerService">
            <el-icon color="#07c160">
              <ChatLineRound />
            </el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="刷新数据" placement="top">
          <el-button circle :loading="loading" @click="refreshLog">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="filter-row">
        <div class="filter-item">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="default"
            :shortcuts="shortcuts"
            class="date-picker"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :editable="false"
            @change="handleDateChange"
          />
        </div>
        <div class="filter-item">
          <el-select
            v-model="freeFilter"
            placeholder="全部类型"
            clearable
            size="default"
            class="free-select"
            @change="handleFreeFilterChange"
          >
            <el-option label="免费" :value="true" />
            <el-option label="付费" :value="false" />
          </el-select>
        </div>
        <div class="filter-item amount-range">
          <el-input-number
            v-model="minAmount"
            :min="0"
            :precision="2"
            :controls="false"
            placeholder="最小金额"
            size="default"
            class="amount-input"
            @change="handleAmountChange"
          />
          <span class="range-separator">-</span>
          <el-input-number
            v-model="maxAmount"
            :min="0"
            :precision="2"
            :controls="false"
            placeholder="最大金额"
            size="default"
            class="amount-input"
            @change="handleAmountChange"
          />
        </div>
        <div class="filter-actions">
          <el-button
            v-if="hasActiveFilters"
            size="default"
            @click="resetFilters"
          >
            <el-icon><i-ep-refresh-left /></el-icon>
            重置
          </el-button>
        </div>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="logData"
      style="width: 100%"
      border
      stripe
      highlight-current-row
      @sort-change="handleSortChange"
    >
      <el-table-column
        prop="content"
        label="套餐类型"
        min-width="150"
        sortable
        show-overflow-tooltip
      />
      <el-table-column
        show-overflow-tooltip
        prop="rechargeAmount"
        label="金额(元)"
        min-width="110"
        sortable
      >
        <template #default="{ row }">
          <span class="amount-cell">¥{{ row.rechargeAmount.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="creationTime"
        label="充值时间"
        min-width="160"
        sortable
        show-overflow-tooltip
      />
      <el-table-column
        prop="expireDateTime"
        label="到期时间"
        min-width="160"
        sortable
        show-overflow-tooltip
      />
      <!-- <el-table-column show-overflow-tooltip prop="contactInfo" width="100" label="联系方式">
        <template #default="{ row }">
          <el-tooltip v-if="row.contactInfo && row.contactInfo.length > 8" :content="row.contactInfo" placement="top">
            <span class="ellipsis-text">{{ row.contactInfo }}</span>
          </el-tooltip>
          <span v-else>{{ row.contactInfo || '-' }}</span>
        </template>
      </el-table-column> -->
      <el-table-column show-overflow-tooltip prop="remark" label="备注" min-width="160">
        <template #default="{ row }">
          <el-tooltip v-if="row.remark && row.remark.length > 10" :content="row.remark" placement="top">
            <span class="ellipsis-text">{{ row.remark }}</span>
          </el-tooltip>
          <span v-else>{{ row.remark || '-' }}</span>
        </template>
      </el-table-column>
    </el-table>

    <div class="log-footer">
      <!-- 空状态 -->
      <div v-if="!logData.length && !loading" class="empty-container">
        <el-empty :description="hasActiveFilters ? '当前筛选条件下无数据' : '暂无充值记录'">
          <el-button v-if="hasActiveFilters" type="primary" @click="resetFilters">
            清除筛选
          </el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <div v-if="totalCount > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 新增全屏图片样式 */
.fullscreen-image-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.85);
  backdrop-filter: blur(8px);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.fullscreen-image {
  max-width: 90%;
  max-height: 90%;
  border: 8px solid white;
  border-radius: 20px;
  box-shadow: 0 0 60px rgba(255, 255, 255, 0.3);
  animation: zoomIn 0.3s ease;
}

@keyframes zoomIn {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

.recharge-log-container {
  padding: 10px;
  background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  height: 100%;
  overflow-y: auto;
}

.recharge-log-container:hover {
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.12);
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e9ecef;
}

.log-title {
  display: flex;
  align-items: center;
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #333;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.log-title .el-icon {
  margin-right: 10px;
  color: #409eff;
  font-size: 24px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.amount-cell {
  font-family: 'Arial', sans-serif;
  font-weight: 700;
  font-size: 15px;
  color: #e74c3c;
  text-shadow: 0 1px 2px rgba(231, 76, 60, 0.2);
}

.ellipsis-text {
  display: inline-block;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}

.log-footer {
  flex-direction: column;
  margin-top: 25px;
  padding-top: 20px;
  border-top: 2px solid #e9ecef;
}

/* 筛选工具栏 */
.filter-toolbar {
  margin-bottom: 20px;
  padding: 16px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid #e8eaed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

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

.filter-item {
  flex: 0 0 auto;
}

.date-picker {
  width: 320px;
}

.free-select {
  width: 140px;
}

/* 金额范围筛选 */
.amount-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.amount-input {
  width: 120px;
}

.range-separator {
  color: #909399;
  font-size: 14px;
}

.filter-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

/* 记录数标签 */
.count-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  font-weight: 600;
  border-radius: 16px;
}

/* 空状态 */
.empty-container {
  padding: 40px 0;
  width: 100%;
}

/* 分页容器 */
.pagination-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.summary {
  color: #666;
  font-size: 15px;
  font-weight: 500;
}

.highlight {
  color: #409eff;
  font-weight: 700;
  font-size: 18px;
  padding: 0 6px;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f8fafc;
  color: #333;
  font-weight: 600;
  font-size: 14px;
  padding: 8px 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

:deep(.el-table th .cell) {
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f8f9fb;
}

:deep(.el-table .cell) {
  padding: 12px 16px;
}

:deep(.el-table tbody tr) {
  transition: all 0.3s ease;
}

:deep(.el-table tbody tr:hover) {
  background: linear-gradient(90deg, #f0f7ff 0%, #e6f4ff 100%) !important;
  transform: scale(1.01);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 分页样式优化 */
:deep(.el-pagination) {
  padding: 0;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
  color: #fff;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #409eff;
}

/* 移动端响应式优化 */
@media (max-width: 768px) {
  .recharge-log-container {
    padding: 12px;
  }

  .log-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
    margin-bottom: 16px;
    padding-bottom: 12px;
  }

  .log-title {
    font-size: 18px;
  }

  .log-title .el-icon {
    font-size: 20px;
  }

  .header-actions {
    flex-wrap: wrap;
    width: 100%;
  }

  /* 移动端筛选工具栏 */
  .filter-toolbar {
    padding: 12px;
  }

  .filter-row {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .filter-item {
    width: 100%;
  }

  .date-picker,
  .free-select {
    width: 100%;
  }

  .amount-range {
    width: 100%;
  }

  .amount-input {
    flex: 1;
    width: auto;
  }

  .filter-actions {
    margin-left: 0;
    display: flex;
    gap: 8px;
  }

  .filter-actions .el-button {
    flex: 1;
  }

  /* 表格移动端优化 */
  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-table th) {
    font-size: 12px;
    padding: 6px 0;
  }

  :deep(.el-table .cell) {
    padding: 8px 6px;
  }

  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }

  .amount-cell {
    font-size: 13px;
  }

  .log-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
    margin-top: 16px;
    padding-top: 12px;
  }

  .summary {
    font-size: 14px;
    text-align: center;
  }

  :deep(.el-pagination) {
    justify-content: center;
  }

  /* 对话框移动端优化 */
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto !important;
  }

  :deep(.el-dialog__body) {
    padding: 15px;
  }

  .fullscreen-image {
    max-width: 95%;
    max-height: 95%;
    border: 4px solid white;
    border-radius: 12px;
  }
}

@media (max-width: 480px) {
  .recharge-log-container {
    padding: 8px;
  }

  .log-title {
    font-size: 16px;
  }

  :deep(.el-table) {
    font-size: 11px;
  }

  :deep(.el-table th) {
    font-size: 11px;
  }

  :deep(.el-table .cell) {
    padding: 6px 4px;
  }

  .header-actions .el-button {
    padding: 8px;
  }
}
</style>
