<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { invoiceApi } from '@/api/finance.js'

const statusMap = { 0: '待开', 1: '已开', 2: '已红冲' }
const statusType = { 0: 'warning', 1: 'success', 2: 'danger' }
const typeMap = { 1: '电子', 2: '纸质' }

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)

const searchForm = reactive({ invoice_no: '', status: '', type: '' })
const pagination = reactive({ page: 1, per_page: 15 })

const formRef = ref(null)
const form = reactive({ id: null, invoice_no: '', customer_id: '', type: 1, amount: 0, tax_amount: 0, title: '', tax_no: '' })
const isEdit = ref(false)
const formRules = { invoice_no: [{ required: true, message: '请输入发票号', trigger: 'blur' }] }

async function fetchList() {
  loading.value = true
  try {
    const res = await invoiceApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { invoice_no: '', status: '', type: '' }); handleSearch() }

function handleAdd() {
  isEdit.value = false
  Object.assign(form, { id: null, invoice_no: '', customer_id: '', type: 1, amount: 0, tax_amount: 0, title: '', tax_no: '' })
  dialogVisible.value = true
}
async function handleEdit(row) { isEdit.value = true; Object.assign(form, { ...row }); dialogVisible.value = true }

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await invoiceApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await invoiceApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除发票「${row.invoice_no}」吗？`, '删除确认', { type: 'warning' })
  await invoiceApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

async function handleIssue(row) {
  await ElMessageBox.confirm(`确定开具发票「${row.invoice_no}」吗？`, '开票确认', { type: 'info' })
  await invoiceApi.issue(row.id); ElMessage.success('开票成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }
onMounted(() => fetchList())
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input v-model="searchForm.invoice_no" placeholder="发票号" style="width:180px" clearable @keydown.enter="handleSearch" />
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-select v-model="searchForm.type" placeholder="类型" clearable style="width:120px">
        <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">发票列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增发票</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column prop="invoice_no" label="发票号" min-width="150" />
          <el-table-column prop="customer_id" label="客户ID" width="100" align="center" />
          <el-table-column label="类型" width="80" align="center"><template #default="{ row }"><el-tag size="small">{{ typeMap[row.type] }}</el-tag></template></el-table-column>
          <el-table-column prop="amount" label="金额" width="100" align="right" />
          <el-table-column prop="tax_amount" label="税额" width="100" align="right" />
          <el-table-column prop="title" label="发票抬头" min-width="180" show-overflow-tooltip />
          <el-table-column label="状态" width="90" align="center"><template #default="{ row }"><el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag></template></el-table-column>
          <el-table-column prop="issued_at" label="开票时间" width="160" />
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status===0" size="small" type="success" text @click="handleIssue(row)">开票</el-button>
              <el-button v-if="row.status===0" size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button v-if="row.status===0" size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,15,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="isEdit?'编辑发票':'新增发票'" width="550px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="发票号" prop="invoice_no"><el-input v-model="form.invoice_no" placeholder="请输入发票号" /></el-form-item>
        <el-form-item label="客户ID"><el-input v-model="form.customer_id" placeholder="请输入客户ID" /></el-form-item>
        <el-form-item label="类型"><el-select v-model="form.type" style="width:100%"><el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" /></el-select></el-form-item>
        <el-form-item label="金额"><el-input-number v-model="form.amount" :min="0" :precision="2" style="width:100%" /></el-form-item>
        <el-form-item label="税额"><el-input-number v-model="form.tax_amount" :min="0" :precision="2" style="width:100%" /></el-form-item>
        <el-form-item label="发票抬头"><el-input v-model="form.title" placeholder="请输入发票抬头" /></el-form-item>
        <el-form-item label="税号"><el-input v-model="form.tax_no" placeholder="请输入税号" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="dialogVisible=false">取消</el-button><el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button></template>
    </el-dialog>
  </div>
</template>
