<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="80px"
    >
      <el-form-item label="凭证编号" prop="voucherNo">
        <el-input
          v-model="queryParams.voucherNo"
          class="!w-200px"
          clearable
          placeholder="请输入凭证编号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="摘要" prop="summary">
        <el-input
          v-model="queryParams.summary"
          class="!w-200px"
          clearable
          placeholder="请输入摘要"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select
          v-model="queryParams.status"
          class="!w-200px"
          clearable
          placeholder="请选择审核状态"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_AUDIT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="制单人" prop="creatorUserName">
        <el-input
          v-model="queryParams.creatorUserName"
          class="!w-200px"
          clearable
          placeholder="请输入制单人"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['erp:bookkeeping-voucher:create']"
          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button
          v-hasPermi="['erp:bookkeeping-voucher:export']"
          :loading="exportLoading"
          plain
          type="success"
          @click="handleExport"
        >
          <Icon class="mr-5px" icon="ep:download" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :default-sort="{ prop: 'voucherNo', order: 'ascending' }"
      @row-click="handleRowClick"
    >
      <el-table-column align="center" label="凭证编号" prop="voucherNo" width="160" sortable />
      <el-table-column align="center" label="摘要" prop="summary" min-width="150" />
      <el-table-column align="center" label="借方金额合计" prop="debitTotal" width="120">
        <template #default="scope">
          {{ formatAmount(scope.row.debitTotal) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="贷方金额合计" prop="creditTotal" width="120">
        <template #default="scope">
          {{ formatAmount(scope.row.creditTotal) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="制单人" prop="creatorUserName" width="100" />
      <el-table-column align="center" label="审核人" prop="auditorUserName" width="100" />
      <el-table-column align="center" label="系统名" prop="systemName" width="100" />
      <el-table-column align="center" label="审核状态" prop="status" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_AUDIT_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" min-width="120" />
      <el-table-column align="center" fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button
            v-hasPermi="['erp:bookkeeping-voucher:query']"
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
          >
            详情
          </el-button>
          <el-button
            v-if="scope.row.status === 10"
            v-hasPermi="['erp:bookkeeping-voucher:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.status === 10"
            v-hasPermi="['erp:bookkeeping-voucher:audit']"
            link
            type="success"
            @click="handleAudit(scope.row.id)"
          >
            审核
          </el-button>
          <el-button
            v-if="scope.row.status === 20"
            v-hasPermi="['erp:bookkeeping-voucher:audit']"
            link
            type="warning"
            @click="handleUnaudit(scope.row.id)"
          >
            反审核
          </el-button>
          <el-button
            v-if="scope.row.status === 10"
            v-hasPermi="['erp:bookkeeping-voucher:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗 -->
  <BookkeepingVoucherForm ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import * as BookkeepingVoucherApi from '@/api/erp/finance/bookkeeping'
import BookkeepingVoucherForm from './BookkeepingVoucherForm.vue'
import {BookkeepingVoucherVO} from "@/api/erp/finance/bookkeeping";

defineOptions({ name: 'ErpBookkeepingVoucher' })

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

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  voucherNo: undefined,
  summary: undefined,
  status: undefined,
  creatorUserName: undefined,
  voucherDate: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 格式化金额 */
const formatAmount = (amount: number | undefined) => {
  if (amount === undefined || amount === null) {
    return '0.00'
  }
  return amount.toFixed(2)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BookkeepingVoucherApi.BookkeepingVoucherApi.getVoucherPage(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 handleAudit = async (id: number) => {
  try {
    await message.confirm('确认要审核该记账凭证吗？')
    await BookkeepingVoucherApi.BookkeepingVoucherApi.auditVoucher(id)
    message.success('审核成功')
    await getList()
  } catch {}
}

/** 反审核操作 */
const handleUnaudit = async (id: number) => {
  try {
    await message.confirm('确认要反审核该记账凭证吗？')
    await BookkeepingVoucherApi.BookkeepingVoucherApi.unauditVoucher(id)
    message.success('反审核成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await BookkeepingVoucherApi.BookkeepingVoucherApi.deleteVoucher(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 行点击操作 */
const handleRowClick = (row: BookkeepingVoucherVO, 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
  }

  // 已审核打开详情页面，未审核打开编辑页面
  openForm('detail', row.id)
}


/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await BookkeepingVoucherApi.BookkeepingVoucherApi.exportVoucher(queryParams)
    download.excel(data, '记账凭证.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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