<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.paymentNo" placeholder="收款单号" clearable style="width:170px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="渠道订单号">
          <el-input v-model="filters.channelOrderNo" placeholder="渠道订单号" clearable style="width:180px" />
        </el-form-item>
        <el-form-item label="渠道">
          <el-select v-model="filters.channel" placeholder="全部渠道" clearable style="width:140px">
            <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.reconcileStatus" placeholder="全部" clearable style="width:130px">
            <el-option label="待对账" value="待对账" />
            <el-option label="已确认" value="已确认" />
            <el-option label="有差异" value="有差异" />
          </el-select>
        </el-form-item>
        <el-form-item label="收款时间">
          <el-date-picker v-model="filters.dateRange" type="daterange" range-separator="至" start-placeholder="开始" end-placeholder="结束" style="width:240px" />
        </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 type="primary" @click="openReconcile">对账确认</el-button>
          <el-button @click="doExport">导出</el-button>
        </div>
        <el-select v-model="summaryView" placeholder="汇总视图" clearable style="width:180px">
          <el-option label="按渠道汇总" value="channel" />
          <el-option label="按店铺汇总" value="shop" />
          <el-option label="按时间汇总" value="time" />
        </el-select>
      </div>
    </section>

    <section class="glass-card section-card">
      <el-table :data="filteredItems" stripe style="width:100%" v-loading="loading" @selection-change="onSelection">
        <el-table-column type="selection" width="45" />
        <el-table-column prop="paymentNo" label="收款单号" width="170" />
        <el-table-column prop="channelOrderNo" label="渠道订单号" width="170" />
        <el-table-column prop="channel" label="渠道" width="120" />
        <el-table-column prop="shopName" label="店铺" width="140" />
        <el-table-column prop="currency" label="币种" width="70" />
        <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="payMethod" label="支付方式" width="100" />
        <el-table-column prop="payTime" label="收款时间" width="160" />
        <el-table-column prop="reconcileStatus" label="对账状态" width="100">
          <template #default="{ row }">
            <el-tag :type="reconcileTag(row.reconcileStatus)" size="small">{{ row.reconcileStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDetail(row)">详情</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
    </section>

    <section 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;color:var(--cb-primary)">$12,450.00</div>
        </article>
        <article class="stat-card">
          <div class="stat-card__label">本周收款</div>
          <div class="stat-card__value" style="font-size:24px">$86,230.00</div>
        </article>
        <article class="stat-card">
          <div class="stat-card__label">本月收款</div>
          <div class="stat-card__value" style="font-size:24px">$328,500.00</div>
        </article>
        <article class="stat-card">
          <div class="stat-card__label">待对账</div>
          <div class="stat-card__value" style="font-size:24px;color:var(--cb-accent)">$15,680.00</div>
        </article>
      </div>
    </section>

    <el-dialog v-model="detailVisible" title="收款详情" width="560px">
      <el-descriptions :column="1" border v-if="detailItem">
        <el-descriptions-item label="收款单号">{{ detailItem.paymentNo }}</el-descriptions-item>
        <el-descriptions-item label="渠道订单号">{{ detailItem.channelOrderNo }}</el-descriptions-item>
        <el-descriptions-item label="渠道">{{ detailItem.channel }}</el-descriptions-item>
        <el-descriptions-item label="店铺">{{ detailItem.shopName }}</el-descriptions-item>
        <el-descriptions-item label="币种">{{ detailItem.currency }}</el-descriptions-item>
        <el-descriptions-item label="收款金额">{{ detailItem.currency }} {{ detailItem.amount }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ detailItem.payMethod }}</el-descriptions-item>
        <el-descriptions-item label="收款时间">{{ detailItem.payTime }}</el-descriptions-item>
        <el-descriptions-item label="对账状态">
          <el-tag :type="reconcileTag(detailItem.reconcileStatus)">{{ detailItem.reconcileStatus }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="交易流水号">{{ detailItem.transactionNo }}</el-descriptions-item>
        <el-descriptions-item label="手续费">{{ detailItem.currency }} {{ detailItem.fee }}</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 type { OrderItem } from '@/types/page';

interface PaymentItem {
  id: string;
  paymentNo: string;
  channelOrderNo: string;
  channel: string;
  shopName: string;
  currency: string;
  amount: string;
  payMethod: string;
  payTime: string;
  reconcileStatus: string;
  transactionNo: string;
  fee: string;
  remark: string;
  orderId?: string;
}

const items = ref<PaymentItem[]>([
  { id: 'P001', paymentNo: 'PAY-20260420-001', channelOrderNo: 'SHOP-US-20260420-0123', channel: 'Shopify', shopName: 'NomadPeak US', currency: 'USD', amount: '128.00', payMethod: 'Credit Card', payTime: '2026-04-20 10:30:15', reconcileStatus: '待对账', transactionNo: 'txn_3N4K8M9L2', fee: '3.84', remark: '', orderId: 'order-1' },
  { id: 'P002', paymentNo: 'PAY-20260420-002', channelOrderNo: 'SHOP-JP-20260420-0456', channel: 'Shopify', shopName: 'UrbanTrail JP', currency: 'JPY', amount: '8900', payMethod: 'PayPay', payTime: '2026-04-20 09:45:22', reconcileStatus: '已确认', transactionNo: 'txn_4P5Q9R8S3', fee: '267', remark: '', orderId: 'order-2' },
  { id: 'P003', paymentNo: 'PAY-20260419-003', channelOrderNo: 'TT-UK-20260419-0789', channel: 'TikTok Shop', shopName: 'AeroDry UK', currency: 'GBP', amount: '65.00', payMethod: 'TikTok Pay', payTime: '2026-04-19 21:09:33', reconcileStatus: '已确认', transactionNo: 'txn_5T6U7V9W4', fee: '1.95', remark: '', orderId: 'order-3' },
  { id: 'P004', paymentNo: 'PAY-20260419-004', channelOrderNo: 'SHOP-US-20260419-0321', channel: 'Shopify', shopName: 'NomadPeak US', currency: 'USD', amount: '259.00', payMethod: 'PayPal', payTime: '2026-04-19 18:20:45', reconcileStatus: '已确认', transactionNo: 'txn_6X7Y8Z9A5', fee: '7.77', remark: '', orderId: 'order-4' },
  { id: 'P005', paymentNo: 'PAY-20260419-005', channelOrderNo: 'TT-UK-20260419-0654', channel: 'TikTok Shop', shopName: 'AeroDry UK', currency: 'GBP', amount: '156.00', payMethod: 'Credit Card', payTime: '2026-04-19 16:35:08', reconcileStatus: '有差异', transactionNo: 'txn_7B8C9D0E6', fee: '4.68', remark: '金额差异 $2.00', orderId: 'order-5' },
  { id: 'P006', paymentNo: 'PAY-20260418-006', channelOrderNo: 'SHOP-JP-20260418-0987', channel: 'Shopify', shopName: 'UrbanTrail JP', currency: 'JPY', amount: '12500', payMethod: 'Credit Card', payTime: '2026-04-18 14:12:30', reconcileStatus: '已确认', transactionNo: 'txn_8F9G0H1I7', fee: '375', remark: '', orderId: 'order-6' }
]);

const loading = ref(false);
const selected = ref<PaymentItem[]>([]);
const summaryView = ref('');
const detailVisible = ref(false);
const detailItem = ref<PaymentItem | null>(null);

const filters = ref({
  paymentNo: '',
  channelOrderNo: '',
  channel: '',
  reconcileStatus: '',
  dateRange: [] as string[]
});

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

const reconcileTag = (status: string) => {
  const map: Record<string, string> = { '待对账': 'warning', '已确认': 'success', '有差异': 'danger' };
  return map[status] || '';
};

const loadData = () => {
  loading.value = true;
  setTimeout(() => { loading.value = false; }, 300);
};

const resetFilters = () => {
  filters.value = { paymentNo: '', channelOrderNo: '', channel: '', reconcileStatus: '', dateRange: [] };
};

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

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

const openReconcile = 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(p => p.id === item.id);
    if (idx !== -1) items.value[idx].reconcileStatus = '已确认';
    if (item.orderId) {
      await api.updateOrder(Number(item.orderId), { 
        orderStatus: 'paid',
        paymentStatus: 'paid',
        paidAt: new Date().toISOString()
      } as Partial<OrderItem>);
    }
  }
  ElMessage.success('对账已完成，订单状态已同步更新');
};

const doExport = () => {
  ElMessage.info('导出开始，完成后将自动下载');
};

onMounted(loadData);
</script>

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