<template>
  <Dialog
    title="选择发票"
    v-model="dialogVisible"
    :appendToBody="true"
    :scroll="true"
    width="1080"
  >
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <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="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-form-item>
      </el-form>
    </ContentWrap>

    <ContentWrap>
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="list"
        :show-overflow-tooltip="true"
        :stripe="true"
        row-key="id"
        :reserve-selection="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column min-width="180" label="发票号码" align="center" prop="invoiceNo" />
        <el-table-column label="发票方" align="center" prop="counterpartyName" />
        <el-table-column
          label="发票日期"
          align="center"
          prop="invoiceDate"
          :formatter="dateFormatter2"
          width="120px"
        />
        <el-table-column label="金额(不含税)" align="center" prop="amountWithoutTax" />
        <el-table-column label="税额" align="center" prop="taxAmount" />
      </el-table>
      <!-- 分页 -->
      <Pagination
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="getList"
      />
    </ContentWrap>
    <template #footer>
      <el-button :disabled="selectedRows.length === 0" type="primary" @click="submitForm">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { Invoice, InvoiceApi } from '@/api/erp/finance/invoice'
import { dateFormatter2, formatDate } from '@/utils/formatTime'

defineOptions({ name: 'InvoiceSelectList' })

const props = defineProps<{
  invoiceCategory: number
  fetchInvoicePage: (params: any) => Promise<any>
}>()

const list = ref<Invoice[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const loading = ref(false) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  invoiceNo: undefined,
  counterpartyName: undefined,
  invoiceDate: [],
  invoiceCategory: props.invoiceCategory,
  isSettlement: 1,
  selected: 0
})
const queryFormRef = ref() // 搜索的表单
const tableRef = ref()

/** 选中行 */
const selectedRows = ref<Invoice[]>([])
const selectedIds = ref<string[]>([])
const handleSelectionChange = (rows: Invoice[]) => {
  selectedRows.value = rows
  selectedIds.value = rows.map((item) => String(item.id))
}

/** 打开弹窗 */
const open = async (ids: Array<string | number> = []) => {
  selectedIds.value = ids.map((id) => String(id))
  dialogVisible.value = true
  await nextTick() // 等待，避免 queryFormRef 为空
  await resetQuery()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交选择 */
const emits = defineEmits<{
  (e: 'success', value: Invoice[]): void
}>()
const submitForm = () => {
  try {
    if (!selectedRows.value.length) return
    emits('success', selectedRows.value)
  } finally {
    dialogVisible.value = false
  }
}

/** 加载列表  */
const getList = async () => {
  loading.value = true
  try {
    const params: any = { ...queryParams }
    const formatDateOnly = (d: any) => (typeof d === 'string' ? d.slice(0, 10) : formatDate(d, 'YYYY-MM-DD'))
    if (Array.isArray(params.invoiceDate) && params.invoiceDate.length) {
      params.invoiceDate = params.invoiceDate.map((d: any) => formatDateOnly(d))
    } else {
      params.invoiceDate = undefined
    }
    params.invoiceCategory = props.invoiceCategory
    params.isSettlement = 1
    params.selected = 0
    const data = await props.fetchInvoicePage(params)
    list.value = data.list || []
    total.value = data.total || 0
    await nextTick()
    syncSelection()
    await ensureSelectedInList()
  } finally {
    loading.value = false
  }
}

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

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

const syncSelection = () => {
  if (!tableRef.value) return
  tableRef.value.clearSelection()
  if (!selectedIds.value.length) return
  const idSet = new Set(selectedIds.value)
  const matchedRows = list.value.filter((row) => idSet.has(String(row.id)))
  matchedRows.forEach((row) => tableRef.value.toggleRowSelection(row, true))
  selectedRows.value = matchedRows
}

const ensureSelectedInList = async () => {
  if (!selectedIds.value.length) return
  const existingIds = new Set(list.value.map((row) => String(row.id)))
  const missingIds = selectedIds.value.filter((id) => !existingIds.has(String(id)))
  if (!missingIds.length) return
  const detailList = await Promise.all(
    missingIds.map(async (id) => {
      try {
        return await InvoiceApi.getInvoice(Number(id))
      } catch {
        return null
      }
    })
  )
  const extraRows = detailList.filter((row): row is Invoice => !!row)
  if (!extraRows.length) return
  const merged = [...extraRows, ...list.value]
  const seen = new Set<string>()
  list.value = merged.filter((row) => {
    const key = String(row.id)
    if (seen.has(key)) return false
    seen.add(key)
    return true
  })
  await nextTick()
  syncSelection()
}
</script>
