<template>
  <!-- 搜索区域：拆分基础筛选+更多筛选，避免一行拥挤 -->
  <ContentWrap class="mb-10px">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      inline
      label-width="80px"
      class="search-form"
    >
      <!-- 基础筛选（常用字段） -->
      <el-form-item label="发票日期" prop="invoiceDate">
        <el-date-picker
          v-model="queryParams.invoiceDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="dateDefaultTime"
          class="w-220px"
        />
      </el-form-item>

      <el-form-item label="发票类别" prop="invoiceCategory">
        <el-select
          v-model="queryParams.invoiceCategory"
          placeholder="请选择"
          clearable
          class="w-200px"
        >
          <el-option label="进项发票" value="进项发票" />
          <el-option label="销项发票" value="销项发票" />
        </el-select>
      </el-form-item>

      <el-form-item label="发票类型" prop="invoiceType">
        <el-select
          v-model="queryParams.invoiceType"
          placeholder="请选择"
          clearable
          class="w-200px"
        >
          <el-option label="增值税专用发票" value="增值税专用发票" />
          <el-option label="增值税普通发票" value="增值税普通发票" />
        </el-select>
      </el-form-item>

      <el-form-item label="发票号码" prop="invoiceNo">
        <el-input
          v-model="queryParams.invoiceNo"
          placeholder="请输入发票号码"
          clearable
          @keyup.enter="handleQuery"
          class="w-200px"
        />
      </el-form-item>

      <el-form-item label="客户/供应商" prop="counterpartyName">
        <el-input
          v-model="queryParams.counterpartyName"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="w-200px"
        />
      </el-form-item>

      <!-- 更多筛选按钮 -->
      <el-form-item>
        <el-button type="text" @click="showMoreSearch = !showMoreSearch">
          {{ showMoreSearch ? '收起筛选' : '更多筛选' }}
          <el-icon :rotate="showMoreSearch ? 180 : 0"><ArrowDown /></el-icon>
        </el-button>
      </el-form-item>

      <!-- 功能按钮区：独立出来更整洁 -->
      <el-form-item class="operation-group">
        <el-button @click="handleQuery" type="primary">
          <el-icon><Search /></el-icon> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <el-icon><Refresh /></el-icon> 重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['finance:invoice:create']"
        >
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['finance:invoice:export']"
        >
          <el-icon><Download /></el-icon> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['finance:invoice:delete']"
        >
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 更多筛选（折叠展示，默认隐藏） -->
    <el-form
      v-if="showMoreSearch"
      :model="queryParams"
      inline
      label-width="80px"
      class="more-search-form mt-10px"
    >
      <el-form-item label="金额（不含税）" prop="amountWithoutTax">
        <el-input
          v-model="queryParams.amountWithoutTax"
          placeholder="请输入金额"
          clearable
          @keyup.enter="handleQuery"
          class="w-200px"
        />
      </el-form-item>

      <el-form-item label="税率(%)" prop="taxRate">
        <el-input
          v-model="queryParams.taxRate"
          placeholder="请输入税率"
          clearable
          @keyup.enter="handleQuery"
          class="w-200px"
        />
      </el-form-item>

      <el-form-item label="发票状态" prop="invoiceStatus">
        <el-select
          v-model="queryParams.invoiceStatus"
          placeholder="请选择"
          clearable
          class="w-200px"
        >
          <el-option label="待接收" value="待接收" />
          <el-option label="已认证" value="已认证" />
          <el-option label="已作废" value="已作废" />
        </el-select>
      </el-form-item>

      <el-form-item label="认证日期" prop="certificationDate">
        <el-date-picker
          v-model="queryParams.certificationDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="dateDefaultTime"
          class="w-220px"
        />
      </el-form-item>

      <el-form-item label="记账期间" prop="accountingPeriod">
        <el-input
          v-model="queryParams.accountingPeriod"
          placeholder="如：2026-01"
          clearable
          @keyup.enter="handleQuery"
          class="w-200px"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="dateDefaultTime"
          class="w-220px"
        />
      </el-form-item>

      <!-- 低频筛选项：合并到最后，减少视觉干扰 -->
      <el-form-item label="其他筛选" prop="other">
        <el-input
          v-model="queryParams.taxAmount"
          placeholder="税额"
          clearable
          class="w-150px"
        />
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="价税合计"
          clearable
          class="w-150px ml-5px"
        />
        <el-input
          v-model="queryParams.voucherNo"
          placeholder="凭证字号"
          clearable
          class="w-150px ml-5px"
        />
      </el-form-item>

      <el-form-item label="备注/附件" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="备注内容"
          clearable
          class="w-200px"
        />
        <el-input
          v-model="queryParams.attachment"
          placeholder="附件路径"
          clearable
          class="w-200px ml-5px"
        />
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表区域：简化列名，优化布局 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      stripe
      show-overflow-tooltip
      @selection-change="handleRowCheckboxChange"
      class="invoice-table"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="发票日期" align="center" prop="invoiceDate" width="120" />
      <el-table-column label="发票类别" align="center" prop="invoiceCategory" width="100" />
      <el-table-column label="发票类型" align="center" prop="invoiceType" width="120" />
      <el-table-column label="发票号码" align="center" prop="invoiceNo" min-width="150" />
      <el-table-column label="往来单位" align="center" prop="counterpartyName" min-width="120" />
      <el-table-column label="不含税金额" align="center" prop="amountWithoutTax" width="100" />
      <el-table-column label="税率(%)" align="center" prop="taxRate" width="80" />
      <el-table-column label="税额" align="center" prop="taxAmount" width="80" />
      <el-table-column label="价税合计" align="center" prop="totalAmount" width="100" />
      <el-table-column label="发票状态" align="center" prop="invoiceStatus" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.invoiceStatus)">
            {{ scope.row.invoiceStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="记账期间" align="center" prop="accountingPeriod" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180" />
      
      <!-- 次要列：放到最后，可根据需求调整显隐 -->
      <el-table-column label="附件" align="center" prop="attachment" width="150" show-overflow-tooltip />
      <el-table-column label="认证日期" align="center" prop="certificationDate" width="120" />
      <el-table-column label="凭证字号" align="center" prop="voucherNo" width="100" />
      <el-table-column label="备注" align="center" prop="remark" width="120" show-overflow-tooltip />
      
      <el-table-column label="操作" align="center" width="120" flex="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['finance:invoice:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['finance:invoice:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页：独立底部，样式更整洁 -->
    <div class="pagination-wrap">
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </ContentWrap>

  <!-- 表单弹窗 -->
  <InvoiceForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from 'vue-i18n'
import { ArrowDown, Search, Refresh, Plus, Download, Delete } from '@element-plus/icons-vue'

import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { InvoiceApi, Invoice } from '@/api/erp/finance/invoice'
import InvoiceForm from './InvoiceForm.vue'

// 组件名称
defineOptions({ name: 'Invoice' })

// 全局常量抽离：减少重复代码
const dateDefaultTime = ref([new Date('1 00:00:00'), new Date('1 23:59:59')])
const showMoreSearch = ref(false) // 控制更多筛选显隐

// 全局方法/状态
const message = useMessage()
const { t } = useI18n()

// 列表相关状态
const loading = ref(true)
const list = ref<Invoice[]>([])
const total = ref(0)
const exportLoading = ref(false)
const checkedIds = ref<number[]>([])
const formRef = ref()
const queryFormRef = ref()

// 查询参数：简化默认值，去掉冗余的undefined
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  invoiceDate: [],
  invoiceCategory: '',
  invoiceType: '',
  invoiceNo: '',
  counterpartyName: '',
  amountWithoutTax: '',
  taxRate: '',
  taxAmount: '',
  totalAmount: '',
  attachment: '',
  invoiceStatus: '',
  certificationDate: [],
  voucherNo: '',
  accountingPeriod: '',
  remark: '',
  createTime: [],
})

// 发票状态标签类型映射：优化视觉体验
const getStatusTagType = (status: string) => {
  const statusMap = {
    待接收: 'info',
    已认证: 'success',
    已作废: 'danger',
    已归档: 'warning'
  }
  return statusMap[status] || 'info'
}

// 查询列表：简化try/catch，逻辑更清晰
const getList = async () => {
  loading.value = true
  try {
    const { list: resList, total: resTotal } = await InvoiceApi.getInvoicePage(queryParams)
    list.value = resList
    total.value = resTotal
  } catch (error) {
    message.error('查询发票列表失败，请重试')
    console.error('发票列表查询失败：', error)
  } finally {
    loading.value = false
  }
}

// 搜索/重置：简化逻辑
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  Object.keys(queryParams).forEach(key => {
    if (Array.isArray(queryParams[key])) {
      queryParams[key] = []
    } else {
      queryParams[key] = ''
    }
  })
  queryParams.pageNo = 1
  queryParams.pageSize = 10
  getList()
}

// 弹窗操作
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

// 删除操作：统一错误处理
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await InvoiceApi.deleteInvoice(id)
    message.success(t('common.delSuccess'))
    getList()
  } catch (error) {
    message.error('删除失败，请重试')
    console.error('删除发票失败：', error)
  }
}

// 批量删除
const handleDeleteBatch = async () => {
  if (isEmpty(checkedIds.value)) return
  try {
    await message.delConfirm()
    await InvoiceApi.deleteInvoiceList(checkedIds.value)
    message.success(t('common.delSuccess'))
    getList()
  } catch (error) {
    message.error('批量删除失败，请重试')
    console.error('批量删除发票失败：', error)
  }
}

// 选择行事件
const handleRowCheckboxChange = (records: Invoice[]) => {
  checkedIds.value = records.map(item => item.id)
}

// 导出操作
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await InvoiceApi.exportInvoice(queryParams)
    download.excel(data, '财务发票管理.xls')
    message.success('导出成功')
  } catch (error) {
    message.error('导出失败，请重试')
    console.error('导出发票失败：', error)
  } finally {
    exportLoading.value = false
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
/* 简化样式，统一间距和宽度 */
.search-form, .more-search-form {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.operation-group {
  margin-left: 20px !important;
}

.more-search-form {
  border: none;
}

.pagination-wrap {
  margin-top: 20px;
  text-align: right;
}

.invoice-table {
  --el-table-header-text-color: #666;
  --el-table-row-hover-bg-color: #f8f9fa;
}

/* 响应式适配：小屏幕下自动换行 */
@media (max-width: 1400px) {
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>