<template>
  <doc-alert
    title="【财务】总账管理"
    url="https://doc.iocoder.cn/finance/ledger/"
  />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="科目" prop="subjectId">
        <el-select
          v-model="queryParams.subjectId"
          placeholder="请选择科目"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in subjectList"
            :key="item.id"
            :label="`${item.code} - ${item.name}`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="期间" prop="period">
        <el-date-picker
          v-model="queryParams.period"
          type="month"
          placeholder="请选择期间"
          value-format="YYYY-MM"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="凭证号" prop="voucherNo">
        <el-input
          v-model="queryParams.voucherNo"
          placeholder="请输入凭证号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </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="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:ledger:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="科目编码" align="center" prop="subjectCode" width="100" />
      <el-table-column label="科目名称" align="left" prop="subjectName" width="180" />
      <el-table-column label="期间" align="center" prop="period" width="100" />
      <el-table-column label="摘要" align="left" prop="summary" width="120" />
      <el-table-column label="借方金额" align="right" prop="debitAmount" width="120">
        <template #default="scope">
          {{ formatAmount(scope.row.debitAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="贷方金额" align="right" prop="creditAmount" width="120">
        <template #default="scope">
          {{ formatAmount(scope.row.creditAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="方向" align="center" prop="direction" width="80" />
      <el-table-column label="余额" align="right" prop="balance" width="120">
        <template #default="scope">
          {{ formatAmount(scope.row.balance) }}
        </template>
      </el-table-column>
      <el-table-column label="凭证数量" align="center" prop="voucherCount" width="80" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        min-width="180"
      />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { LedgerApi, LedgerVO } from '@/api/erp/finance/ledger'
import { AccountApi, AccountVO } from '@/api/erp/finance/account'
import { SubjectApi, SubjectVO } from '@/api/erp/finance/subject'

/** ERP 总账 列表 */
defineOptions({ name: 'ErpLedger' })

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

const loading = ref(true) // 列表的加载中
const list = ref<LedgerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  subjectId: undefined,
  period: undefined,
  voucherNo: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const accountList = ref<AccountVO[]>([]) // 账户列表
const subjectList = ref<SubjectVO[]>([]) // 科目列表

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

/** 格式化日期 */
const formatDate = (date: Date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 处理日期范围参数
    const params: any = { ...queryParams }
    if (params.transactionDate && params.transactionDate.length === 2) {
      params.startDate = params.transactionDate[0]
      params.endDate = params.transactionDate[1]
      delete params.transactionDate
    }

    const data = await LedgerApi.getLedgerPage(params)
    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 handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await LedgerApi.exportLedger(queryParams)
    download.excel(data, '总账.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 */
onMounted(async () => {
  await getList()
  // 加载账户和科目列表
  accountList.value = await AccountApi.getAccountSimpleList()
  subjectList.value = await SubjectApi.getSubjectSimpleList()
})
</script>
