<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="transactionDate" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.transactionDate) }}
        </template>
      </el-table-column>
      <el-table-column label="凭证号" align="center" prop="voucherNo" width="120" />
      <el-table-column label="摘要" align="left" prop="summary" width="200" />
      <el-table-column label="科目编码" align="center" prop="subjectCode" width="120" />
      <el-table-column label="科目名称" align="left" prop="subjectName" width="180" />
      <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="left" prop="counterpartSubject" width="180" />
      <el-table-column label="制单人" align="center" prop="creator" width="100" />
      <el-table-column label="审核人" align="center" prop="auditor" width="100" />
      <el-table-column label="审核状态" align="center" prop="auditStatus" width="100" />
      <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 { SubjectApi, SubjectVO } from '@/api/erp/finance/subject'

// 定义明细账数据类型
interface LedgerDetailVO {
  id: number
  transactionDate: string
  voucherNo: string
  summary: string
  subjectCode: string
  subjectName: string
  debitAmount: number
  creditAmount: number
  direction: string
  balance: number
  counterpartSubject: string
  creator: string
  auditor: string
  auditStatus: string
  createTime: number | Date
  subjectId: number
}

/** ERP 明细账 列表 */
defineOptions({ name: 'ErpLedgerDetail' })

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

const loading = ref(true) // 列表的加载中
const list = ref<LedgerDetailVO[]>([]) // 列表的数据
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 subjectList = ref<SubjectVO[]>([]) // 科目列表

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

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

/** 生成模拟数据 */
const generateMockData = () => {
  const mockData: LedgerDetailVO[] = []
  const subjects = [
    { id: 1, code: '1001', name: '库存现金' },
    { id: 2, code: '1002', name: '银行存款' },
    { id: 3, code: '1122', name: '应收账款' },
    { id: 4, code: '2202', name: '应付账款' },
    { id: 5, code: '6001', name: '主营业务收入' }
  ]

  const counterpartSubjects = [
    '库存现金', '银行存款', '应收账款', '应付账款', '主营业务收入', '管理费用', '销售费用'
  ]

  const creators = ['张三', '李四', '王五', '赵六']
  const auditors = ['财务经理', '会计主管', '审计员']
  const auditStatuses = ['已审核', '待审核', '审核中', '被驳回']

  for (let i = 0; i < 50; i++) {
    const subject = subjects[Math.floor(Math.random() * subjects.length)]
    mockData.push({
      id: i + 1,
      transactionDate: `2024-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      voucherNo: `VCH${String(i + 1).padStart(6, '0')}`,
      summary: `业务${i + 1}的摘要信息`,
      subjectCode: subject.code,
      subjectName: subject.name,
      debitAmount: Math.random() > 0.5 ? Math.floor(Math.random() * 1000000) / 100 : 0,
      creditAmount: Math.random() > 0.5 ? Math.floor(Math.random() * 1000000) / 100 : 0,
      direction: Math.random() > 0.5 ? '借' : '贷',
      balance: Math.floor(Math.random() * 1000000) / 100,
      counterpartSubject: counterpartSubjects[Math.floor(Math.random() * counterpartSubjects.length)],
      creator: creators[Math.floor(Math.random() * creators.length)],
      auditor: auditors[Math.floor(Math.random() * auditors.length)],
      auditStatus: auditStatuses[Math.floor(Math.random() * auditStatuses.length)],
      createTime: Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000,
      subjectId: subject.id
    })
  }

  return mockData
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 使用模拟数据
    const mockData = generateMockData()

    // 应用过滤器
    let filteredData = mockData

    if (queryParams.subjectId) {
      filteredData = filteredData.filter(item => item.subjectId === queryParams.subjectId)
    }

    if (queryParams.period) {
      filteredData = filteredData.filter(item => {
        const itemDate = new Date(item.transactionDate)
        const itemMonth = `${itemDate.getFullYear()}-${String(itemDate.getMonth() + 1).padStart(2, '0')}`
        return itemMonth === queryParams.period
      })
    }

    if (queryParams.voucherNo) {
      filteredData = filteredData.filter(item =>
        item.voucherNo.includes(queryParams.voucherNo)
      )
    }

    // 应用分页
    const startIndex = (queryParams.pageNo - 1) * queryParams.pageSize
    const endIndex = startIndex + queryParams.pageSize

    list.value = filteredData.slice(startIndex, endIndex)
    total.value = filteredData.length
  } 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 mockData = generateMockData()
    let exportData = mockData

    // 应用相同的过滤器
    if (queryParams.subjectId) {
      exportData = exportData.filter(item => item.subjectId === queryParams.subjectId)
    }

    if (queryParams.period) {
      exportData = exportData.filter(item => {
        const itemDate = new Date(item.transactionDate)
        const itemMonth = `${itemDate.getFullYear()}-${String(itemDate.getMonth() + 1).padStart(2, '0')}`
        return itemMonth === queryParams.period
      })
    }

    if (queryParams.voucherNo) {
      exportData = exportData.filter(item =>
        item.voucherNo.includes(queryParams.voucherNo)
      )
    }

    // 创建Excel数据
    const excelData = exportData.map(item => ({
      日期: item.transactionDate,
      凭证号: item.voucherNo,
      摘要: item.summary,
      科目编码: item.subjectCode,
      科目名称: item.subjectName,
      借方金额: item.debitAmount,
      贷方金额: item.creditAmount,
      方向: item.direction,
      余额: item.balance,
      对方科目: item.counterpartSubject,
      制单人: item.creator,
      审核人: item.auditor,
      审核状态: item.auditStatus,
      创建时间: new Date(item.createTime).toLocaleString()
    }))

    // 创建CSV数据
    let csvContent = "data:text/csv;charset=utf-8,"
    csvContent += "日期,凭证号,摘要,科目编码,科目名称,借方金额,贷方金额,方向,余额,对方科目,制单人,审核人,审核状态,创建时间\n"
    exportData.forEach(item => {
      csvContent += `"${item.transactionDate}","${item.voucherNo}","${item.summary}","${item.subjectCode}","${item.subjectName}",${item.debitAmount},${item.creditAmount},"${item.direction}",${item.balance},"${item.counterpartSubject}","${item.creator}","${item.auditor}","${item.auditStatus}","${new Date(item.createTime).toLocaleString()}"\n`
    })

    // 创建下载链接
    const encodedUri = encodeURI(csvContent)
    const link = document.createElement("a")
    link.setAttribute("href", encodedUri)
    link.setAttribute("download", "明细账.csv")
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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