<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="应收单号" prop="aroCode">
        <el-input
          v-model="queryParams.aroCode"
          placeholder="请输入应收单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="单据日期" prop="billDate">
        <el-date-picker
          v-model="queryParams.billDate"
          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="dueDate">
        <el-date-picker
          v-model="queryParams.dueDate"
          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="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          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="nonTaxAmount">
        <el-input
          v-model="queryParams.nonTaxAmount"
          placeholder="请输入不含税金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="单据类型：1-销售发票，2-服务费账单，3-其他应收" prop="billType">
        <el-select
          v-model="queryParams.billType"
          placeholder="请选择单据类型：1-销售发票，2-服务费账单，3-其他应收"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态：0-草稿，1-待审核，2-已审核，3-已核销，4-已取消" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态：0-草稿，1-待审核，2-已审核，3-已核销，4-已取消"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </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="auditUser">
        <el-input
          v-model="queryParams.auditUser"
          placeholder="请输入审核人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="审核时间" prop="auditTime">
        <el-date-picker
          v-model="queryParams.auditTime"
          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')">-->
        <!--          <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>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      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" /> -->
      <el-table-column label="应收单号" align="center" prop="aroCode" width="200" />
      <el-table-column label="客户" align="center" prop="customer" />
      <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="center" prop="receiptPrice" width="150" />
      <el-table-column label="总金额" align="center" prop="totalAmount" width="150" />
      <!-- <el-table-column label="税率" align="right" prop="taxAmount" width="100" /> -->
      <!-- <el-table-column label="不含税金额" align="right" prop="nonTaxAmount" width="120" /> -->
      <!-- <el-table-column label="会计科目" align="center" prop="subjectId" /> -->
      <!-- <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">
        <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="dueDate" width="120" /> -->
      <el-table-column label="备注" align="center" prop="remark" min-width="150" />
      <!-- <el-table-column label="审核人" align="center" prop="auditUser" width="100" /> -->
      <!-- <el-table-column
        label="审核时间"
        align="center"
        prop="auditTime"
        :formatter="dateFormatter"
        width="180px"
      /> -->
      <!--      <el-table-column label="操作" align="center" width="180" fixed="right">-->
      <!--        <template #default="scope">-->
      <!--          <el-button link type="primary" @click="openForm('update', scope.row.id)">-->
      <!--            编辑-->
      <!--          </el-button>-->
      <!--          <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

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

/** 应收单 列表 */
defineOptions({ name: 'ReceivableOrder' })

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

const loading = ref(true) // 列表的加载中
type ReceivableOrderRow = ReceivableOrder & { sourceTable?: string; sourceId?: number }
const list = ref<ReceivableOrderRow[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  aroCode: undefined,
  billDate: [],
  dueDate: [],
  totalAmount: undefined,
  taxAmount: undefined,
  nonTaxAmount: undefined,
  accountSubjects: undefined,
  billType: undefined,
  status: undefined,
  remark: undefined,
  auditUser: undefined,
  auditTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ReceivableOrderApi.autoGetShowReceivableOrder(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)
    }
    const dataList = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : []
    if (Array.isArray(dataList)) {
      const mapped = dataList.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 = mapped
    } else {
      list.value = []
    }
    total.value = typeof data?.total === 'number' ? data.total : list.value.length
  } finally {
    loading.value = false
  }
}

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

onMounted(async () => {
  await getList()
})

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

/** 重置按钮操作 */
const resetQuery = async () => {
  queryFormRef.value.resetFields()
  await 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 ReceivableOrderApi.deleteReceivableOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除应收单 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ReceivableOrderApi.deleteReceivableOrderList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

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

/** 行点击操作：根据来源表跳转到对应列表并自动查询 */
const router = useRouter()
const handleRowClick = (row: ReceivableOrderRow, 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
  }

  const sourceTable = row.sourceTable
  if (!sourceTable || !row.aroCode) {
    message.warning('未找到来源信息，无法跳转')
    return
  }

  if (sourceTable === 'erp_sale_out') {
    sessionStorage.setItem('erp_sale_out_no', row.aroCode)
    const targetRouteName = 'ErpSaleOut'
    if (router.hasRoute(targetRouteName)) {
      router.push({ name: targetRouteName })
    } else {
      router.push({ path: '/erp/sale/out' })
    }
    return
  }

  if (sourceTable === 'erp_sale_outwarehouse') {
    sessionStorage.setItem('erp_sale_outwarehouse_no', row.aroCode)
    const targetRouteName = 'ErpSaleOutwarehouse'
    if (router.hasRoute(targetRouteName)) {
      router.push({ name: targetRouteName })
    } else {
      router.push({ path: '/P3ERP/sale/outwarehouse' })
    }
    return
  }

  message.warning(`暂不支持来源：${sourceTable}`)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ReceivableOrderApi.exportReceivableOrder(queryParams)
    download.excel(data, '应收单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
</script>
