<template>
  <ContentWrap>
    <!-- 搜索工作栏（简化，仅保留必要条件） -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="发票类别" prop="invoiceCategory">
        <el-select
          v-model="queryParams.invoiceCategory"
          placeholder="请选择发票类别"
          clearable
          class="!w-200px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.ERP_FINANCE_INVOICE_INOUT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.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
            v-for="dict in getStrDictOptions(DICT_TYPE.ERP_FINANCE_INVOICE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.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 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="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-260px"
        />
      </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">
        <template #default="{ row }">
          <DictTag :type="DICT_TYPE.ERP_FINANCE_INVOICE_INOUT_TYPE" :value="row.invoiceCategory" />
        </template>
      </el-table-column>
      <el-table-column label="发票类型" align="center" prop="invoiceType">
        <template #default="{ row }">
          <DictTag :type="DICT_TYPE.ERP_FINANCE_INVOICE_TYPE" :value="row.invoiceType" />
        </template>
      </el-table-column>
      <el-table-column label="会计科目" align="center" prop="accountSubjects" width="100" >
        <template #default="{ row }">
          <DictTag :type="DICT_TYPE.ERP_FINANCE_SUBJECT_TYPE" :value="row.accountSubjects" />
        </template>
      </el-table-column>
      <el-table-column label="发票号码" align="center" prop="invoiceNo" />
      <el-table-column label="发票方" align="center" prop="counterpartyName" />
       <!-- <el-table-column label="会计科目" align="center" prop="accountSubjects" width="100" >
        <template #default="{ row }">
          <DictTag :type="DICT_TYPE.ERP_FINANCE_SUBJECT_TYPE" :value="row.accountSubjects" />
        </template>
        </el-table-column> -->
      <el-table-column label="金额(不含税)" width="120"  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="isSettlement">
        <template #default="{ row }">
          <span>{{ row.isSettlement === 1 ? '已结算' : '未结算' }}</span>
        </template>
      </el-table-column>
      <!-- <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="success"
            :disabled="scope.row.isSettlement === 1"
            @click="handleSettlement(scope.row)"
            v-hasPermi="['finance:invoice:update']"
          >
            结算
          </el-button>
          <el-button
            link
            type="primary"
            :disabled="scope.row.invoiceStatus === '已认证'"
            @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, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { InvoiceApi, Invoice } from '@/api/erp/finance/invoice'
import InvoiceForm from './InvoiceForm.vue'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import DictTag from '@/components/DictTag/src/DictTag.vue'
// import { DICT_TYPE } from '@/utils/dict'

/** 财务发票主 列表 */
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,
  accountSubjects: undefined,
  amountWithoutTax: undefined,
  taxRate: undefined,
  taxAmount: undefined,
  totalAmount: undefined,
  attachment: undefined,
  invoiceStatus: undefined,
  isSettlement: undefined,
  certificationDate: [],
  voucherNo: undefined,
  accountingPeriod: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 将后端返回的时间值（时间戳或数字字符串）转换为 Date 对象
const toDateValue = (v: any): any => {
  if (v == null) return v
  // 数组（可能为范围）
  if (Array.isArray(v)) {
    return v.map((item) => toDateValue(item))
  }
  // 已经是 Date
  if (v instanceof Date) return v
  // 字符串时间（包含 '-' 或 ':'）直接返回原值，交给格式化工具处理
  if (typeof v === 'string' && /[-:]/.test(v)) return v
  // 数字或数字字符串视作时间戳（秒或毫秒）
  const n = Number(v)
  if (!Number.isNaN(n)) {
    // 如果看起来像秒（小于 1e12），则转换为毫秒
    const ms = n < 1e12 ? n * 1000 : n
    return new Date(ms)
  }
  return v
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 在发往后端前，把日期范围从 Date/时间戳 转为字符串格式，避免传时间戳
    const params: any = { ...queryParams }
    const formatDateOnly = (d: any) => {
      if (typeof d === 'string') return d.length >= 10 ? d.slice(0, 10) : d
      return formatDate(d, 'YYYY-MM-DD')
    }
    const formatDateTime = (d: any) => (typeof d === 'string' ? d : formatDate(d))
    ;['invoiceDate', 'certificationDate'].forEach((field) => {
      const v: any = (params as any)[field]
      if (Array.isArray(v) && v.length) {
        ;(params as any)[field] = v.map((d: any) => formatDateOnly(d))
      } else {
        ;(params as any)[field] = undefined
      }
    })
    ;['createTime'].forEach((field) => {
      const v: any = (params as any)[field]
      if (Array.isArray(v) && v.length) {
        ;(params as any)[field] = v.map((d: any) => formatDateTime(d))
      } else {
        ;(params as any)[field] = undefined
      }
    })

    const data = await InvoiceApi.getInvoicePage(params)
    // 将列表中可能为时间戳的字段转换为 YYYY-MM-DD HH:mm:ss 字符串，便于显示
    const formatField = (val: any) => {
      if (val == null) return ''
      if (Array.isArray(val)) {
        if (val.length === 3 && val.every((it) => Number.isInteger(it))) {
          const [y, m, d] = val as number[]
          const mm = String(m).padStart(2, '0')
          const dd = String(d).padStart(2, '0')
          return `${y}-${mm}-${dd}`
        }
        return val.map((it) =>
          typeof it === 'string' && /[-:]/.test(it) ? it : formatDate(toDateValue(it))
        )
      }
      if (typeof val === 'string' && /[-:]/.test(val)) return val
      return formatDate(toDateValue(val))
    }

    if (Array.isArray(data.list)) {
      data.list = data.list.map((row: any) => {
        const r = { ...row }
        if (r.invoiceDate) r.invoiceDate = formatField(r.invoiceDate)
        if (r.certificationDate) r.certificationDate = formatField(r.certificationDate)
        if (r.createTime) r.createTime = formatField(r.createTime)
        return r
      })
    }
    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 handleSettlement = async (row: Invoice) => {
  try {
    await message.confirm('确认结算该发票吗？')
    await InvoiceApi.settlementInvoice({ id: row.id })
    row.isSettlement = 1
    message.success('结算成功')
  } catch {}
}

/** 删除按钮操作 */
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 params: any = { ...queryParams }
    const formatDateOnly = (d: any) => {
      if (typeof d === 'string') return d.length >= 10 ? d.slice(0, 10) : d
      return formatDate(d, 'YYYY-MM-DD')
    }
    const formatDateTime = (d: any) => (typeof d === 'string' ? d : formatDate(d))
    ;['invoiceDate', 'certificationDate'].forEach((field) => {
      const v: any = (params as any)[field]
      if (Array.isArray(v) && v.length) {
        ;(params as any)[field] = v.map((d: any) => formatDateOnly(d))
      } else {
        ;(params as any)[field] = undefined
      }
    })
    ;['createTime'].forEach((field) => {
      const v: any = (params as any)[field]
      if (Array.isArray(v) && v.length) {
        ;(params as any)[field] = v.map((d: any) => formatDateTime(d))
      } else {
        ;(params as any)[field] = undefined
      }
    })

    const data = await InvoiceApi.exportInvoice(params)
    download.excel(data, '财务发票主.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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