<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.invoiceNo" placeholder="发票号" clearable style="width:160px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="发票类型">
          <el-select v-model="filters.invoiceType" 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-input v-model="filters.buyerName" placeholder="购买方名称" clearable style="width:150px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="全部" clearable style="width:120px">
            <el-option label="待开票" value="待开票" />
            <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="openApply">申请开票</el-button>
          <el-button @click="doExport">导出</el-button>
        </div>
        <span class="tip-text">累计开票金额: <b style="color:var(--cb-primary)">¥1,258,600.00</b></span>
      </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="invoiceNo" label="发票号" width="160" />
        <el-table-column prop="invoiceType" label="发票类型" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ row.invoiceType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="buyerName" label="购买方" min-width="160" />
        <el-table-column prop="sellerName" label="销售方" min-width="160" />
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            <span style="font-weight:600">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="taxRate" label="税率" width="70" />
        <el-table-column prop="taxAmount" label="税额" width="100" />
        <el-table-column prop="invoiceDate" label="开票日期" width="110" />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="statusTag(row.status)" size="small">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="100" show-overflow-tooltip />
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDetail(row)">详情</el-button>
            <el-button link type="primary" @click="openEdit(row)" v-if="row.status === '待开票'">编辑</el-button>
            <el-button link type="danger" @click="voidInvoice(row)" v-if="row.status === '已开票'">作废</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)">¥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)">¥45,200.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-danger)">¥12,800.00</div>
        </article>
        <article class="stat-card">
          <div class="stat-card__label">进项税额</div>
          <div class="stat-card__value" style="font-size:24px">¥52,560.00</div>
        </article>
      </div>
    </section>

    <el-dialog v-model="applyVisible" title="申请开票" width="560px">
      <el-form :model="applyForm" label-width="100px">
        <el-form-item label="发票类型" required>
          <el-select v-model="applyForm.invoiceType" style="width:100%">
            <el-option label="增值税专用发票" value="专用" />
            <el-option label="增值税普通发票" value="普通" />
            <el-option label="电子发票" value="电子" />
          </el-select>
        </el-form-item>
        <el-form-item label="购买方名称" required>
          <el-input v-model="applyForm.buyerName" placeholder="请输入购买方名称" />
        </el-form-item>
        <el-form-item label="税号">
          <el-input v-model="applyForm.taxNo" placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="开户行">
          <el-input v-model="applyForm.bankName" placeholder="请输入开户行" />
        </el-form-item>
        <el-form-item label="银行账号">
          <el-input v-model="applyForm.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="地址电话">
          <el-input v-model="applyForm.addressPhone" placeholder="请输入地址和电话" />
        </el-form-item>
        <el-form-item label="关联单据">
          <el-select v-model="applyForm.relatedOrders" multiple placeholder="选择关联订单" style="width:100%">
            <el-option label="ORD-20260420-001" value="ORD-20260420-001" />
            <el-option label="ORD-20260419-002" value="ORD-20260419-002" />
          </el-select>
        </el-form-item>
        <el-form-item label="价税合计">
          <el-input-number v-model="applyForm.amount" :min="0" style="width:100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="applyForm.remark" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="applyVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApply">提交</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="detailVisible" title="发票详情" width="560px">
      <el-descriptions :column="1" border v-if="detailItem">
        <el-descriptions-item label="发票号">{{ detailItem.invoiceNo }}</el-descriptions-item>
        <el-descriptions-item label="发票类型">{{ detailItem.invoiceType }}</el-descriptions-item>
        <el-descriptions-item label="购买方">{{ detailItem.buyerName }}</el-descriptions-item>
        <el-descriptions-item label="销售方">{{ detailItem.sellerName }}</el-descriptions-item>
        <el-descriptions-item label="金额">¥{{ detailItem.amount }}</el-descriptions-item>
        <el-descriptions-item label="税率">{{ detailItem.taxRate }}</el-descriptions-item>
        <el-descriptions-item label="税额">¥{{ detailItem.taxAmount }}</el-descriptions-item>
        <el-descriptions-item label="价税合计">¥{{ (parseFloat(detailItem.amount) + parseFloat(detailItem.taxAmount)).toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="开票日期">{{ detailItem.invoiceDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusTag(detailItem.status)">{{ detailItem.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="购买方税号">{{ detailItem.buyerTaxNo }}</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 { InvoiceItem } from '@/types/page';

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

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

const filters = ref({
  invoiceNo: '',
  invoiceType: '',
  buyerName: '',
  status: '',
  dateRange: [] as string[]
});

const applyForm = ref({
  invoiceType: '专用',
  buyerName: '',
  taxNo: '',
  bankName: '',
  bankAccount: '',
  addressPhone: '',
  relatedOrders: [] as string[],
  amount: 0,
  remark: ''
});

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

const statusTag = (status: string) => {
  const map: Record<string, string> = { '待开票': 'warning', '已开票': 'success', '已作废': 'info', '已红冲': 'danger' };
  return map[status] || '';
};

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

const resetFilters = () => {
  filters.value = { invoiceNo: '', invoiceType: '', buyerName: '', status: '', dateRange: [] };
};

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

const openApply = () => {
  applyForm.value = { invoiceType: '专用', buyerName: '', taxNo: '', bankName: '', bankAccount: '', addressPhone: '', relatedOrders: [], amount: 0, remark: '' };
  applyVisible.value = true;
};

const submitApply = () => {
  if (!applyForm.value.buyerName) {
    ElMessage.warning('请填写购买方名称');
    return;
  }
  ElMessage.success('开票申请已提交');
  applyVisible.value = false;
};

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

const openEdit = (row: InvoiceItem) => {
  ElMessage.info('编辑功能开发中');
};

const voidInvoice = async (row: InvoiceItem) => {
  await ElMessageBox.confirm(`确认作废发票 ${row.invoiceNo}？`, '发票作废');
  const idx = items.value.findIndex(i => i.id === row.id);
  if (idx !== -1) items.value[idx].status = '已作废';
  ElMessage.success('发票已作废');
};

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

onMounted(loadData);
</script>

<style scoped>
.filter-form :deep(.el-form-item) { margin-bottom: 0; }
.tip-text { font-size: 13px; color: var(--cb-text-secondary); }
</style>