<template>
  <doc-alert
    title="【财务】会计期间管理"
    url="https://doc.iocoder.cn/finance/fiscal-period/"
  />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="期间名称" prop="periodName">
        <el-input
          v-model="queryParams.periodName"
          placeholder="请输入期间名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="会计年度" prop="fiscalYear">
        <el-input
          v-model="queryParams.fiscalYear"
          placeholder="请输入会计年度"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option key="1" label="开放" value="1" />
          <el-option key="2" label="关闭" value="2" />
          <el-option key="3" label="结账" value="3" />
        </el-select>
      </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')"
          v-hasPermi="['erp:fiscal-period:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:fiscal-period: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" @row-click="handleRowClick">
      <el-table-column label="期间编码" align="center" prop="periodCode" width="120" />
      <el-table-column label="期间名称" align="center" prop="periodName" width="150" />
      <el-table-column label="会计年度" align="center" prop="fiscalYear" width="120" />
      <el-table-column label="开始日期" align="center" prop="startDate" width="120" :formatter="dateFormatter" />
      <el-table-column label="结束日期" align="center" prop="endDate" width="120" :formatter="dateFormatter" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">开放</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="warning">关闭</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="danger">结账</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否当前期间" align="center" prop="isCurrent" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.isCurrent ? 'success' : 'info'">
            {{ scope.row.isCurrent ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" show-overflow-tooltip />

      <el-table-column label="操作" align="center" width="300">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:fiscal-period:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="handleOpen(scope.row.id)"
            v-hasPermi="['erp:fiscal-period:update']"
            v-if="scope.row.status === 2"
          >
            开启
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleClose(scope.row.id)"
            v-hasPermi="['erp:fiscal-period:update']"
            v-if="scope.row.status === 1"
          >
            关闭
          </el-button>
          <el-button
            link
            type="danger"
            @click="handlePost(scope.row.id)"
            v-hasPermi="['erp:fiscal-period:post']"
            v-if="scope.row.status === 2"
          >
            结账
          </el-button>
          <el-button
            link
            type="success"
            @click="handleCompleteClosing(scope.row.id)"
            v-hasPermi="['erp:fiscal-period:post']"
            v-if="scope.row.status === 2"
          >
            完整结账
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:fiscal-period:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <FiscalPeriodForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { FiscalPeriodApi, FiscalPeriodVO } from '@/api/erp/finance/fiscal-period'
import FiscalPeriodForm from './FiscalPeriodForm.vue'

/** ERP 会计期间 列表 */
defineOptions({ name: 'ErpFiscalPeriod' })

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

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

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await FiscalPeriodApi.getFiscalPeriodPage(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 handleRowClick = (row: FiscalPeriodVO, 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('update', row.id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FiscalPeriodApi.deleteFiscalPeriod(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 开启期间操作 */
const handleOpen = async (id: number) => {
  try {
    // 确认操作
    await message.confirm('确认开启该会计期间吗？')
    // 发起开启
    await FiscalPeriodApi.openFiscalPeriod(id)
    message.success('开启成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 关闭期间操作 */
const handleClose = async (id: number) => {
  try {
    // 确认操作
    await message.confirm('确认关闭该会计期间吗？')
    // 发起关闭
    await FiscalPeriodApi.closeFiscalPeriod(id)
    message.success('关闭成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 结账操作 */
const handlePost = async (id: number) => {
  try {
    // 确认操作
    await message.confirm('确认结账吗？结账后将无法修改该期间数据！')
    // 发起结账
    await FiscalPeriodApi.postFiscalPeriod(id)
    message.success('结账成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 完整结账操作 */
const handleCompleteClosing = async (id: number) => {
  try {
    // 确认操作
    await message.confirm('确认执行完整结账流程吗？该操作将执行试算平衡检查、计算期初余额并更新期间状态！')
    // 发起完整结账
    const report = await FiscalPeriodApi.performCompleteClosing(id)
    message.success('完整结账成功！')
    // 显示结账报告
    await message.alert(report)
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('完整结账失败:', error)
    message.error('完整结账失败，请检查控制台日志')
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await FiscalPeriodApi.exportFiscalPeriod(queryParams)
    download.excel(data, 'ERP 会计期间.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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