<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <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="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="发票类别" prop="invoiceCategory">
        <el-input
          v-model="queryParams.invoiceCategory"
          placeholder="请输入发票类别（进项发票/销项发票）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发票类型" prop="invoiceType">
        <el-select
          v-model="queryParams.invoiceType"
          placeholder="请选择发票类型（增值税专用发票/普通发票）"
          clearable
          class="!w-240px"
        >
          <!-- <el-option label="请选择字典生成" value="" /> -->
            <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-240px"
        />
      </el-form-item>
      <el-form-item label="供应商名" prop="counterpartyName">
        <el-input
          v-model="queryParams.counterpartyName"
          placeholder="请输入客户/供应商名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="金额" prop="amountWithoutTax">
        <el-input
          v-model="queryParams.amountWithoutTax"
          placeholder="请输入金额（不含税）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="税率%" prop="taxRate">
        <el-input
          v-model="queryParams.taxRate"
          placeholder="请输入税率（%）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="税额" prop="taxAmount">
        <el-input
          v-model="queryParams.taxAmount"
          placeholder="请输入税额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="价税合计" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入价税合计"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发票附件" prop="attachment">
        <el-input
          v-model="queryParams.attachment"
          placeholder="请输入发票附件"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发票状态" prop="invoiceStatus">
        <el-select
          v-model="queryParams.invoiceStatus"
          placeholder="请选择发票状态（待接收/已认证/已作废等）"
          clearable
          class="!w-240px"
        >
          <!-- <el-option label="请选择字典生成" value="" /> -->
        <el-option label="待接收" value="AUDITED" />
        <el-option label="已认证" value="INVALID" />
        <el-option label="已作废" value="ARCHIVED" />
        </el-select>
      </el-form-item>
      <el-form-item label="认证日期:仅进项票" label-width="150px" 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="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="凭证字号" prop="voucherNo">
        <el-input
          v-model="queryParams.voucherNo"
          placeholder="请输入凭证字号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="记账期间" prop="accountingPeriod">
        <el-input
          v-model="queryParams.accountingPeriod"
          placeholder="请输入记账期间（如2026-01）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </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="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['finance:invoice:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['finance:invoice:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['finance:invoice:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="发票日期" align="center" prop="invoiceDate" />
      <el-table-column label="发票类别" align="center" prop="invoiceCategory" />
      <el-table-column label="发票类型" align="center" prop="invoiceType" />
      <el-table-column label="发票号码" align="center" prop="invoiceNo" />
      <el-table-column label="供应商名" align="center" prop="counterpartyName" />
      <el-table-column label="金额(不含税)" align="center" prop="amountWithoutTax" />
      <el-table-column label="税率（%）" align="center" prop="taxRate" />
      <el-table-column label="税额" align="center" prop="taxAmount" />
      <el-table-column label="价税合计" align="center" prop="totalAmount" />
      <el-table-column label="发票附件" align="center" prop="attachment" />
      <el-table-column label="发票状态" align="center" prop="invoiceStatus" />
      <el-table-column label="认证日(仅进项票)" align="center" prop="certificationDate" />
      <el-table-column label="凭证字号" align="center" prop="voucherNo" />
      <el-table-column label="记账期间" align="center" prop="accountingPeriod" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <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>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <InvoiceForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
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 message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Invoice[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  invoiceDate: [],
  invoiceCategory: undefined,
  invoiceType: undefined,
  invoiceNo: undefined,
  counterpartyName: undefined,
  amountWithoutTax: undefined,
  taxRate: undefined,
  taxAmount: undefined,
  totalAmount: undefined,
  attachment: undefined,
  invoiceStatus: undefined,
  certificationDate: [],
  voucherNo: undefined,
  accountingPeriod: undefined,
  remark: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InvoiceApi.getInvoicePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
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'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除财务发票主 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await InvoiceApi.deleteInvoiceList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
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')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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