<template>
  <div class="app-page">
    <section class="glass-card section-card">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="退款单号">
          <el-input v-model="filters.refundNo" placeholder="退款单号" clearable style="width:170px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="原订单号">
          <el-input v-model="filters.orderNo" placeholder="原订单号" clearable style="width:170px" />
        </el-form-item>
        <el-form-item label="渠道">
          <el-select v-model="filters.channel" placeholder="全部渠道" clearable style="width:130px">
            <el-option label="Shopify" value="Shopify" />
            <el-option label="TikTok Shop" value="TikTok Shop" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款状态">
          <el-select v-model="filters.status" placeholder="全部" clearable style="width:130px">
            <el-option label="待退款" value="待退款" />
            <el-option label="退款中" value="退款中" />
            <el-option label="已退款" value="已退款" />
            <el-option label="退款失败" value="退款失败" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </section>

    <section class="glass-card section-card" style="padding:12px 24px">
      <div class="table-toolbar" style="margin-bottom:0">
        <div class="chip-list">
          <el-button @click="openBatchRefund">批量退款</el-button>
          <el-button @click="showReasonStats = !showReasonStats">{{ showReasonStats ? '隐藏' : '显示' }}原因统计</el-button>
        </div>
        <el-button @click="loadData">刷新</el-button>
      </div>
    </section>

    <section v-if="showReasonStats" class="glass-card section-card" style="padding:16px">
      <h4 style="margin:0 0 12px">退款原因分析</h4>
      <div class="stat-grid" style="grid-template-columns:repeat(4, 1fr)">
        <article class="stat-card">
          <div class="stat-card__label">商品破损</div>
          <div class="stat-card__value" style="font-size:24px">23%</div>
        </article>
        <article class="stat-card">
          <div class="stat-card__label">与描述不符</div>
          <div class="stat-card__value" style="font-size:24px">31%</div>
        </article>
        <article class="stat-card">
          <div class="stat-card__label">错发/漏发</div>
          <div class="stat-card__value" style="font-size:24px">18%</div>
        </article>
        <article class="stat-card">
          <div class="stat-card__label">其他原因</div>
          <div class="stat-card__value" style="font-size:24px">28%</div>
        </article>
      </div>
    </section>

    <section class="glass-card section-card">
      <el-table :data="filteredItems" style="width:100%" v-loading="loading" @selection-change="onSelection">
        <el-table-column type="selection" width="45" />
        <el-table-column prop="refundNo" label="退款单号" width="170" />
        <el-table-column prop="orderNo" label="原订单号" width="170">
          <template #default="{ row }">
            <el-button link type="primary">{{ row.orderNo }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="渠道" width="110" />
        <el-table-column prop="amount" label="退款金额" width="110">
          <template #default="{ row }">
            <span style="font-weight:600">{{ row.currency }} {{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="refundMethod" label="退款方式" width="100" />
        <el-table-column prop="reason" label="退款原因" min-width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="refundStatusConfig(row.status).type" size="small">{{ refundStatusConfig(row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="160" />
        <el-table-column prop="refundTime" label="退款时间" width="160" />
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="retryRefund(row)" v-if="row.status === '退款失败'">重试</el-button>
            <el-button link type="primary" @click="openDetail(row)">详情</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
    </section>

    <el-dialog v-model="detailVisible" title="退款详情" width="560px">
      <el-descriptions :column="1" border v-if="detailItem">
        <el-descriptions-item label="退款单号">{{ detailItem.refundNo }}</el-descriptions-item>
        <el-descriptions-item label="原订单号">{{ detailItem.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="渠道">{{ detailItem.channel }}</el-descriptions-item>
        <el-descriptions-item label="退款金额">{{ detailItem.currency }} {{ detailItem.amount }}</el-descriptions-item>
        <el-descriptions-item label="退款方式">{{ detailItem.refundMethod }}</el-descriptions-item>
        <el-descriptions-item label="退款原因">{{ detailItem.reason }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="refundStatusConfig(detailItem.refundStatus).type">{{ refundStatusConfig(detailItem.refundStatus).label }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detailItem.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="退款时间">{{ detailItem.refundTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="渠道退款单号">{{ detailItem.channelRefundNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailItem.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { api } from '@/api/services';
import { getRefundFinanceStatus } from '@/utils/enumMappings';
import type { OrderItem, RefundItem } from '@/types/page';

const items = ref<RefundItem[]>([]);

const loading = ref(false);
const selected = ref<RefundItem[]>([]);
const detailVisible = ref(false);
const detailItem = ref<RefundItem | null>(null);
const showReasonStats = ref(false);

const filters = ref({ refundNo: '', orderNo: '', channel: '', status: '' });

const filteredItems = computed(() => {
  return items.value.filter(item => {
    if (filters.value.refundNo && !item.refundNo.includes(filters.value.refundNo)) return false;
    if (filters.value.orderNo && !item.orderNo.includes(filters.value.orderNo)) return false;
    if (filters.value.channel && item.channel !== filters.value.channel) return false;
    if (filters.value.status && item.status !== filters.value.status) return false;
    return true;
  });
});

const refundStatusConfig = (s: string) => getRefundFinanceStatus(s);

const loadData = async () => {
  loading.value = true;
  try {
    const res = await api.getRefunds();
    items.value = res.items ?? [];
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => { filters.value = { refundNo: '', orderNo: '', channel: '', status: '' }; };

const onSelection = (rows: RefundItem[]) => { selected.value = rows; };

const openDetail = (row: RefundItem) => { detailItem.value = row; detailVisible.value = true; };

const retryRefund = async (row: RefundItem) => {
  await ElMessageBox.confirm('确认重新发起退款？', '重试退款');
  const idx = items.value.findIndex(i => i.refundNo === row.refundNo);
  if (idx !== -1) items.value[idx].status = '退款中';
  if (row.orderId) {
    await api.updateOrder(Number(row.orderId), { 
      refundStatus: '部分退款',
      orderStatus: 'refunded'
    } as Partial<OrderItem>);
  }
  ElMessage.success('退款已重新发起');
};

const openBatchRefund = async () => {
  if (!selected.value.length) { ElMessage.warning('请先选择要退款的记录'); return; }
  await ElMessageBox.confirm(`确认对选中的 ${selected.value.length} 条记录发起退款？`, '批量退款');
  for (const item of selected.value) {
    const idx = items.value.findIndex(i => i.refundNo === item.refundNo);
    if (idx !== -1) items.value[idx].status = '退款中';
    if (item.orderId) {
      await api.updateOrder(Number(item.orderId), { 
        refundStatus: '部分退款',
        orderStatus: 'refunded'
      } as Partial<OrderItem>);
    }
  }
  ElMessage.success('批量退款已发起，订单退款状态已更新');
};

onMounted(loadData);
</script>

<style scoped>
.filter-form :deep(.el-form-item) { margin-bottom: 0; }
</style>