<template>
  <ContentWrap>
    <!-- 搜索工作栏：简化标签+优化布局+折叠次要搜索项 -->
    <div class="search-bar" style="margin-bottom: 15px">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="80px"
        size="default"
      >
        <!-- 核心搜索项（默认展示） -->
        <el-form-item label="应付单号" prop="apoCode" tooltip="格式示例：AP20260115001">
          <el-input
            v-model="queryParams.apoCode"
            placeholder="请输入应付单号"
            clearable
            @keyup.enter="handleQuery"
            class="w-200px"
          />
        </el-form-item>
        <!-- <el-form-item label="供应商" prop="supplier">
          <el-input
            v-model="queryParams.supplier"
            placeholder="请输入供应商"
            clearable
            @keyup.enter="handleQuery"
            class="w-180px"
          />
        </el-form-item> -->
        <el-form-item label="单据日期" prop="billDate">
          <el-date-picker
            v-model="queryParams.billDate"
            value-format="YYYY-MM-DD"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="w-240px"
          />
        </el-form-item>
        <!-- <el-form-item label="单据状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            class="w-180px"
          >
            <el-option label="草稿" value="0" />
            <el-option label="待审核" value="1" />
            <el-option label="已审核" value="2" />
            <el-option label="已核销" value="3" />
            <el-option label="已取消" value="4" />
          </el-select> -->
        <!-- </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>
          <el-collapse v-model="collapseName" accordion style="width: fit-content">
            <el-collapse-item title="更多筛选" name="more">
              <el-form :model="queryParams" inline style="margin-top: 10px">
                <el-form-item label="到期日期" prop="dueDate">
                  <el-date-picker
                    v-model="queryParams.dueDate"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="w-240px"
                  />
                </el-form-item>
                <el-form-item label="应付金额" prop="totalAmount">
                  <el-input
                    v-model="queryParams.totalAmount"
                    placeholder="请输入应付总金额"
                    clearable
                    class="w-180px"
                  />
                </el-form-item>
                <el-form-item label="审核人" prop="auditUser">
                  <el-input
                    v-model="queryParams.auditUser"
                    placeholder="请输入审核人"
                    clearable
                    class="w-180px"
                  />
                </el-form-item>
                <el-form-item label="审核时间" prop="auditTime">
                  <el-date-picker
                    v-model="queryParams.auditTime"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="w-240px"
                  />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="queryParams.remark"
                    placeholder="请输入备注关键词"
                    clearable
                    class="w-200px"
                  />
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
        </el-form-item> -->

        <!-- 操作按钮：统一样式+间距 -->
        <el-form-item class="operation-btn-group">
          <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')">-->
<!--          <Icon icon="ep:plus" class="mr-5px" /> 新增-->
<!--        </el-button>-->
        <!-- <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
        <!-- <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </ContentWrap>

  <!-- 列表：简化列名+优化列宽+统一对齐 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      stripe
      border
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
      @row-click="handleRowClick"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column label="应付单ID" align="center" prop="id" width="100" /> -->
      <el-table-column
        label="应付单号"
        align="center"
        prop="apoCode"
        width="200"
        tooltip="格式示例：AP20260115001"
      />
      <el-table-column label="供应商" align="center" prop="supplier" />
      <el-table-column label="单据日期" align="center" prop="billDate" width="150" />
      <!-- <el-table-column label="到期付款日期" align="center" prop="dueDate" width="120" /> -->
      <!-- <el-table-column
        label="应付总金额"
        align="right"
        prop="nonTaxAmount"
        width="120"
        :formatter="formatAmount"
      /> -->
      <!-- <el-table-column label="税率" align="right" prop="taxAmount" width="100" /> -->
      <el-table-column label="已付金额" align="center" prop="paymentPrice" width="150" />
      <el-table-column label="总金额" align="center" prop="totalAmount" width="150" />
      <!-- <el-table-column label="会计科目" align="center" prop="subjectId" width="100" /> -->
      <!-- <el-table-column label="会计科目" align="center" prop="accountSubjects" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_FINANCE_SUBJECT_TYPE" :value="scope.row.accountSubjects" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="单据类型"
        align="center"
        prop="billType"
        width="110"
        :formatter="formatBillType"
      /> -->
      <!-- <el-table-column label="单据类型" align="center" prop="billType" width="110">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_FINANCE_INVOICE_TYPE" :value="scope.row.billType" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="单据状态" align="center" prop="status" width="110">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_FINANCE_INVOICE_INOUT_TYPE" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="审核人" align="center" prop="auditUser" width="100" /> -->
      <!-- <el-table-column
        label="审核时间"
        align="center"
        prop="auditTime"
        width="180"
        :formatter="dateFormatter"
      /> -->
      <!-- <el-table-column label="审核日期" align="center" prop="dueDate" width="120" /> -->
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        min-width="150"
        show-overflow-tooltip
      />
      <!--      <el-table-column label="操作" align="center" width="180" fixed="right">-->
      <!--        <template #default="scope">-->
      <!--          <el-button-->
      <!--            link-->
      <!--            type="primary"-->
      <!--            @click="openForm('update', scope.row.id)"-->
      <!--            icon="ep:edit"-->
      <!--            size="small"-->
      <!--          >-->
      <!--            编辑-->
      <!--          </el-button>-->
      <!--          <el-button-->
      <!--            link-->
      <!--            type="danger"-->
      <!--            @click="handleDelete(scope.row.id)"-->
      <!--            icon="ep:delete"-->
      <!--            size="small"-->
      <!--          >-->
      <!--            删除-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <!-- 分页：优化位置+样式 -->
    <div style="margin-top: 20px; text-align: right">
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        background
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PayableOrderForm 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 { PayableOrderApi, PayableOrder } from '@/api/erp/finance/payableorder'
import PayableOrderForm from './PayableOrderForm.vue'
import { DICT_TYPE } from '@/utils/dict'

/** 应付单 列表 */
defineOptions({ name: 'PayableOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 折叠面板状态
const collapseName = ref('')
// 列表的加载中
const loading = ref(true)
// 列表的数据
type PayableOrderRow = PayableOrder & {
  purchaseInId?: number
  sourceId?: number
  source_id?: number
  bizId?: number
}
const list = ref<PayableOrderRow[]>([])
// 列表的总页数
const total = ref(0)
// 查询参数：简化+规范命名
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  apoCode: undefined,
  supplier: undefined, // 新增：补充供应商ID搜索（原代码遗漏）
  billDate: [],
  dueDate: [],
  totalAmount: undefined,
  taxAmount: undefined, // 次要项移到更多筛选，保留字段但不展示在默认搜索
  nonTaxAmount: undefined, // 次要项移到更多筛选
  subjectId: undefined, // 次要项移到更多筛选
  accountSubjects: undefined,
  billType: undefined,
  status: undefined,
  remark: undefined,
  auditUser: undefined,
  auditTime: []
})
const queryFormRef = ref()
const exportLoading = ref(false)

// 单据类型枚举（统一管理）
const billTypeMap = {
  1: '采购发票',
  2: '费用账单'
  // 3: '其他应付'
}

// 单据状态枚举（统一管理）
const statusMap = {
  0: '草稿',
  1: '待审核',
  2: '已审核',
  3: '已核销',
  4: '已取消'
}

/** 格式化金额（保留2位小数+右对齐） */
const formatAmount = (row: PayableOrder, prop: string) => {
  return row[prop] ? Number(row[prop]).toFixed(2) : '0.00'
}

/** 格式化单据类型 */
const formatBillType = (row: PayableOrder) => {
  return billTypeMap[row.billType] || '未知'
}

/** 格式化单据状态 */
const formatStatus = (row: PayableOrder) => {
  return statusMap[row.status] || '未知'
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PayableOrderApi.autoGetShowPayableOrder(queryParams)
    const formatDateOnly = (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) => formatDateOnly(it)).join(',')
      }
      if (typeof val === 'string') {
        if (/^\d{4},\d{1,2},\d{1,2}$/.test(val)) {
          const [y, m, d] = val.split(',').map((item) => Number(item))
          const mm = String(m).padStart(2, '0')
          const dd = String(d).padStart(2, '0')
          return `${y}-${mm}-${dd}`
        }
        if (/-/.test(val)) return val.slice(0, 10)
        if (/:/.test(val)) return val.split(' ')[0]
      }
      const n = Number(val)
      if (!Number.isNaN(n)) {
        const ms = n < 1e12 ? n * 1000 : n
        return formatDate(new Date(ms), 'YYYY-MM-DD')
      }
      return String(val)
    }
    if (Array.isArray(data.list)) {
      data.list = data.list.map((row: any) => {
        const r = { ...row }
        if (r.billDate) r.billDate = formatDateOnly(r.billDate)
        if (r.dueDate) r.dueDate = formatDateOnly(r.dueDate)
        return r
      })
    }
    list.value = data.list
    total.value = data.total
  } catch (error) {
    message.error('查询失败：' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

/** 进入应付列表时自动更新 */
const autoUpdate = async () => {
  try {
    await PayableOrderApi.autoUpdatePayableOrder()
  } catch (error) {
    console.error('应付单自动更新失败', error)
  }
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  // 重置折叠面板
  collapseName.value = ''
  // 重置所有查询参数
  Object.keys(queryParams).forEach((key) => {
    if (key === 'pageNo') queryParams[key] = 1
    else if (key === 'pageSize') queryParams[key] = 10
    else queryParams[key] = undefined
  })
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await PayableOrderApi.deletePayableOrder(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch (error) {
    message.error('删除失败：' + (error as Error).message)
  }
}

/** 批量删除应付单 */
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await PayableOrderApi.deletePayableOrderList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch (error) {
    message.error('批量删除失败：' + (error as Error).message)
  }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: PayableOrder[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 行点击操作：跳转采购入库页面并带查询条件 */
const router = useRouter()
const handleRowClick = (row: PayableOrderRow, column: any, event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (
    target.tagName === 'BUTTON' ||
    target.tagName === 'A' ||
    target.tagName === 'I' ||
    target.tagName === 'svg' ||
    target.closest('button') ||
    target.closest('a') ||
    target.closest('.el-button') ||
    target.closest('.el-checkbox')
  ) {
    return
  }

  if (!row.apoCode) {
    message.warning('未找到应付单号，无法跳转')
    return
  }

  sessionStorage.setItem('erp_purchase_in_no', row.apoCode)
  const targetRouteName = 'ErpPurchaseIn'
  if (router.hasRoute(targetRouteName)) {
    router.push({ name: targetRouteName })
  } else {
    router.push({ path: '/erp/purchase/in' })
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await PayableOrderApi.exportPayableOrder(queryParams)
    download.excel(data, '应付单_' + new Date().toLocaleDateString() + '.xls')
  } catch (error) {
    message.error('导出失败：' + (error as Error).message)
  } finally {
    exportLoading.value = false
  }
}

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

<style scoped>
/* 统一样式优化 */
.search-bar {
  padding: 10px 0;
}

.operation-btn-group :deep(.el-button) {
  margin-right: 8px;
}

/* 表格样式优化 */
:deep(.el-table) {
  --el-table-header-text-color: #303133;
  --el-table-row-hover-bg-color: #f8f9fa;
}

/* 折叠面板样式 */
:deep(.el-collapse-item__header) {
  padding: 0 15px;
}
</style>
