<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="border-card">
      <el-tab-pane label="月报列表" name="list">
        <div ref="containerRef" class="table-page-wrap">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
          <!-- 业务说明: 查询范围 dataFrom 控制月报数据的所属维度。1=直属单位(本级直接管辖)，2=下级水行政(下级水利部门)，3=流域机构(流域管理范围) -->
          <el-form-item label="查询范围" prop="dataFrom">
            <el-select v-model="queryParams.dataFrom" placeholder="查询范围" clearable style="width: 240px">
              <el-option label="直属单位" value="1" />
              <el-option label="下级水行政" value="2" />
              <el-option label="流域机构" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="年份" prop="year">
            <el-input v-model="queryParams.year" placeholder="请输入年份" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="月份" prop="month">
            <el-input v-model="queryParams.month" placeholder="请输入月份" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="montStat">
            <el-select v-model="queryParams.montStat" placeholder="请选择状态" clearable style="width: 240px">
              <el-option v-for="dict in acci_mont_stat" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['acci:bisaccimont:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" storageKey="acci-bisaccimont-index"></right-toolbar>
        </el-row>

        <div class="table-wrapper">
        <el-table :height="tableHeight" v-loading="loading" :data="montList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="月份" align="center" prop="mont" v-if="columns.mont.visible" width="120" />
          <el-table-column label="状态" align="center" prop="montStat" v-if="columns.montStat.visible" width="120">
            <template #default="scope">
              <dict-tag :options="acci_mont_stat" :value="scope.row.montStat" />
            </template>
          </el-table-column>
          <el-table-column label="上报时间" align="center" prop="repTime" v-if="columns.repTime.visible" width="180" />
          <el-table-column label="审核意见" align="center" prop="checkOpinion" v-if="columns.checkOpinion.visible" :show-overflow-tooltip="true" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="420">
            <template #default="scope">
              <!-- 业务说明: 审核 — 通过后月报状态变更为"已审核"(状态值2)，表示上级单位确认月报内容合格 -->
              <el-tooltip content="审核" placement="top">
                <el-button link type="success" icon="CircleCheck" @click="handleCheck(scope.row)" v-hasPermi="['acci:bisaccimont:check']"></el-button>
              </el-tooltip>
              <!-- 业务说明: 退回 — 退回后月报状态回退为"未上报"(状态值0)，下级单位需重新填报后再提交 -->
              <el-tooltip content="退回" placement="top">
                <el-button link type="warning" icon="CloseBold" @click="handleReturn(scope.row)" v-hasPermi="['acci:bisaccimont:return']"></el-button>
              </el-tooltip>
              <!-- 业务说明: 申请撤销 — 仅月报已上报(montStat=1)时可申请撤销，流程为: 申请 → 上级审核通过/驳回 -->
              <el-tooltip content="申请撤销" placement="top" v-if="scope.row.montStat === '1'">
                <el-button link type="info" icon="RefreshLeft" @click="handleApplyRevoke(scope.row)" v-hasPermi="['acci:bisaccimont:revoke']">申请撤销</el-button>
              </el-tooltip>
              <!-- 业务说明: 撤销审核 — 上级单位审核撤销申请(montStat=4)。选择"通过"则月报回退可重新填报，选择"驳回"则维持已上报状态 -->
              <el-tooltip content="撤销审核" placement="top" v-if="scope.row.montStat === '4'">
                <el-button link type="primary" icon="Finished" @click="handleRevokeCheck(scope.row)" v-hasPermi="['acci:bisaccimont:check']">撤销审核</el-button>
              </el-tooltip>
              <el-tooltip content="附件" placement="top">
                <el-button link type="primary" icon="Paperclip" @click="handleAttachment(scope.row)"></el-button>
              </el-tooltip>
              <!-- 业务说明: 加锁/解锁 — 仅水利部管理员可操作。加锁后该月报无法上报和修改，用于冻结已归档或审计中的期间数据 -->
              <el-tooltip :content="scope.row.isLock === '1' ? '解锁' : '加锁'" placement="top">
                <el-button link :type="scope.row.isLock === '1' ? 'danger' : 'primary'" :icon="scope.row.isLock === '1' ? 'Unlock' : 'Lock'" @click="handleLock(scope.row)" v-hasPermi="['acci:bisaccimont:lock']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['acci:bisaccimont:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        </div>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-tab-pane>

      <el-tab-pane label="月报填报" name="fill">
        <el-form :model="fillForm" :rules="fillRules" ref="fillRef" label-width="100px" style="max-width: 600px; margin-top: 20px;">
          <el-form-item label="选择月份" prop="mont">
            <el-date-picker v-model="fillForm.mont" type="month" value-format="YYYY-MM" placeholder="选择月份" style="width: 100%" />
          </el-form-item>
          <el-form-item label="月报内容" prop="montContent">
            <el-input v-model="fillForm.montContent" type="textarea" :rows="8" placeholder="请输入月报内容" />
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input v-model="fillForm.note" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Plus" @click="submitFill" :loading="fillLoading">保存月报</el-button>
            <el-button icon="Refresh" @click="resetFill">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 业务说明: 期间表管理 — 系统按年份自动生成1-12月共12条期间记录，作为各级单位按月填报事故月报的时间基准。每年初由系统批量初始化，锁定后无法上报 -->
      <el-tab-pane label="期间表管理" name="period">
        <el-form :model="periodQuery" ref="periodQueryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="年份" prop="year">
            <el-input v-model="periodQuery.year" placeholder="请输入年份" clearable style="width: 240px" @keyup.enter="handlePeriodQuery" />
          </el-form-item>
          <el-form-item label="月份" prop="month">
            <el-input v-model="periodQuery.month" placeholder="请输入月份" clearable style="width: 240px" @keyup.enter="handlePeriodQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="montStat">
            <el-select v-model="periodQuery.montStat" placeholder="请选择状态" clearable style="width: 240px">
              <el-option v-for="dict in acci_mont_stat" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handlePeriodQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetPeriodQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="periodLoading" :data="periodList" stripe>
          <el-table-column label="月份" align="center" prop="mont" width="120" />
          <el-table-column label="状态" align="center" prop="montStat" width="120">
            <template #default="scope">
              <dict-tag :options="acci_mont_stat" :value="scope.row.montStat" />
            </template>
          </el-table-column>
          <el-table-column label="上报时间" align="center" prop="repTime" width="180" />
          <el-table-column label="锁定状态" align="center" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.isLock === '1' ? 'danger' : 'success'" disable-transitions>
                {{ scope.row.isLock === '1' ? '已锁定' : '未锁定' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button
                :type="scope.row.isLock === '1' ? 'danger' : 'primary'"
                :icon="scope.row.isLock === '1' ? 'Unlock' : 'Lock'"
                size="small"
                @click="handleLock(scope.row)"
                v-hasPermi="['acci:bisaccimont:lock']"
              >
                {{ scope.row.isLock === '1' ? '解锁' : '锁定' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="periodTotal > 0" :total="periodTotal" v-model:page="periodQuery.pageNum" v-model:limit="periodQuery.pageSize" @pagination="fetchPeriodList" />
      </el-tab-pane>
    </el-tabs>

    <!-- 审核对话框 -->
    <el-dialog title="审核月报" v-model="checkOpen" width="500px" append-to-body>
      <el-form :model="checkForm" :rules="checkRules" ref="checkRef" label-width="100px">
        <el-form-item label="月份">
          <el-input v-model="checkForm.mont" disabled />
        </el-form-item>
        <el-form-item label="审核意见" prop="checkOpinion">
          <el-input v-model="checkForm.checkOpinion" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCheck">确 定</el-button>
          <el-button @click="checkOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 退回对话框 -->
    <el-dialog title="退回月报" v-model="returnOpen" width="500px" append-to-body>
      <el-form :model="returnForm" :rules="returnRules" ref="returnRef" label-width="100px">
        <el-form-item label="月份">
          <el-input v-model="returnForm.mont" disabled />
        </el-form-item>
        <el-form-item label="退回原因" prop="returnOpinion">
          <el-input v-model="returnForm.returnOpinion" type="textarea" :rows="4" placeholder="请输入退回原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReturn">确 定</el-button>
          <el-button @click="returnOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 申请撤销对话框 -->
    <el-dialog title="申请撤销" v-model="revokeApplyOpen" width="500px" append-to-body>
      <el-form :model="revokeApplyForm" :rules="revokeApplyRules" ref="revokeApplyRef" label-width="100px">
        <el-form-item label="月份">
          <el-input v-model="revokeApplyForm.mont" disabled />
        </el-form-item>
        <el-form-item label="撤销原因" prop="revokeReason">
          <el-input v-model="revokeApplyForm.revokeReason" type="textarea" :rows="4" placeholder="请输入撤销原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitApplyRevoke">提 交</el-button>
          <el-button @click="revokeApplyOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 撤销审核对话框 -->
    <el-dialog title="撤销审核" v-model="revokeCheckOpen" width="500px" append-to-body>
      <el-form :model="revokeCheckForm" :rules="revokeCheckRules" ref="revokeCheckRef" label-width="100px">
        <el-form-item label="月份">
          <el-input v-model="revokeCheckForm.mont" disabled />
        </el-form-item>
        <el-form-item label="撤销原因">
          <el-input v-model="revokeCheckForm.revokeReason" type="textarea" :rows="2" disabled />
        </el-form-item>
        <el-form-item label="审核结果" prop="checkResult">
          <el-radio-group v-model="revokeCheckForm.checkResult">
            <el-radio value="1">通过</el-radio>
            <el-radio value="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="checkOpinion">
          <el-input v-model="revokeCheckForm.checkOpinion" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRevokeCheck">确 定</el-button>
          <el-button @click="revokeCheckOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 附件管理对话框 -->
    <el-dialog title="附件管理" v-model="attachOpen" width="700px" append-to-body>
      <div style="margin-bottom: 12px;">
        <el-upload
          ref="uploadRef"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :data="{ bizGuid: currentAttachGuid }"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar"
          :disabled="attachUploading"
        >
          <el-button type="primary" plain icon="Upload" :loading="attachUploading">上传附件</el-button>
          <template #tip>
            <div class="el-upload__tip" style="display: inline-block; margin-left: 8px; color: #909399;">
              支持常见文档/图片格式，单个文件不超过10MB
            </div>
          </template>
        </el-upload>
      </div>
      <el-table v-loading="attachLoading" :data="attachList" empty-text="暂无附件">
        <el-table-column label="文件名" align="center" prop="medName" :show-overflow-tooltip="true" />
        <el-table-column label="上传时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button link type="primary" icon="Download" @click="handleDownloadAttach(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="BisAcciMont">
import request from '@/utils/request'
import { useTableHeight } from '@/hooks/useTableHeight'
import { getToken } from '@/utils/auth'
import { listBisAcciMont, getBisAcciMont, addBisAcciMont, updateBisAcciMont, delBisAcciMont, checkBisAcciMont, returnBisAcciMont, revokeBisAcciMont, lockBisAcciMont } from "@/api/slaj/acci"

const { tableHeight, containerRef } = useTableHeight()

const { proxy } = getCurrentInstance()
const { acci_mont_stat } = proxy.useDict("acci_mont_stat")

const activeTab = ref("list")
const montList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 审核
const checkOpen = ref(false)
const checkForm = ref({})
const checkRules = {
  checkOpinion: [{ required: true, message: "审核意见不能为空", trigger: "blur" }]
}

// 退回
const returnOpen = ref(false)
const returnForm = ref({})
const returnRules = {
  returnOpinion: [{ required: true, message: "退回原因不能为空", trigger: "blur" }]
}

// 申请撤销
const revokeApplyOpen = ref(false)
const revokeApplyForm = ref({})
const revokeApplyRules = {
  revokeReason: [{ required: true, message: "撤销原因不能为空", trigger: "blur" }]
}

// 撤销审核
const revokeCheckOpen = ref(false)
const revokeCheckForm = ref({})
const revokeCheckRules = {
  checkResult: [{ required: true, message: "请选择审核结果", trigger: "change" }],
  checkOpinion: [{ required: true, message: "审核意见不能为空", trigger: "blur" }]
}

// 附件管理
const attachOpen = ref(false)
const attachLoading = ref(false)
const attachList = ref([])
const currentAttachGuid = ref("")
const attachUploading = ref(false)
const uploadUrl = import.meta.env.VITE_SERVICE_BASE_TITLE + '/common/upload'
const uploadHeaders = {
  Authorization: 'Bearer ' + getToken()
}

// 月报填报
const fillLoading = ref(false)
const fillForm = ref({})
const fillRules = {
  mont: [{ required: true, message: "请选择月份", trigger: "change" }],
  montContent: [{ required: true, message: "月报内容不能为空", trigger: "blur" }]
}

// 期间表管理
const periodLoading = ref(false)
const periodList = ref([])
const periodTotal = ref(0)
const periodQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  year: undefined,
  month: undefined,
  montStat: undefined
})

const columns = ref({
  mont: { label: '月份', visible: true },
  montStat: { label: '状态', visible: true },
  repTime: { label: '上报时间', visible: true },
  checkOpinion: { label: '审核意见', visible: true }
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dataFrom: undefined,
    year: undefined,
    month: undefined,
    montStat: undefined
  },
  rules: {}
})

const { queryParams, form, rules } = toRefs(data)

// ========== 月报列表 ==========

/** 查询月报列表 */
function getList() {
  loading.value = true
  listBisAcciMont(queryParams.value).then(res => {
    loading.value = false
    montList.value = res.rows
    total.value = res.total
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.guid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 业务说明: 打开审核对话框，填写审核意见后提交，后端将月报状态变更为"已审核"(状态值2) */
function handleCheck(row) {
  checkForm.value = {
    guid: row.guid,
    mont: row.mont,
    checkOpinion: undefined
  }
  checkOpen.value = true
}

/** 业务说明: 提交月报审核 — 审核通过后状态由"已上报"变更为"已审核"，表示上级确认内容合规 */
function submitCheck() {
  proxy.$refs["checkRef"].validate(valid => {
    if (valid) {
      checkBisAcciMont(checkForm.value).then(response => {
        proxy.$modal.msgSuccess("审核成功")
        checkOpen.value = false
        getList()
      })
    }
  })
}

/** 业务说明: 打开退回对话框。退回后将月报状态回退至"未上报"(状态值0)，下级单位需重新填报后再提交审核 */
function handleReturn(row) {
  returnForm.value = {
    guid: row.guid,
    mont: row.mont,
    returnOpinion: undefined
  }
  returnOpen.value = true
}

/** 业务说明: 提交退回 — 状态从任意已处理状态回退为"未上报"，下级单位收到退回原因后需修改后重新上报 */
function submitReturn() {
  proxy.$refs["returnRef"].validate(valid => {
    if (valid) {
      returnBisAcciMont(returnForm.value).then(response => {
        proxy.$modal.msgSuccess("退回成功")
        returnOpen.value = false
        getList()
      })
    }
  })
}

/** 业务说明: 申请撤销 — 仅月报状态为"已上报"(状态值1)时可申请。提交后状态变为"撤销申请中"(状态值4)，等待上级审核 */
function handleApplyRevoke(row) {
  revokeApplyForm.value = {
    guid: row.guid,
    mont: row.mont,
    revokeReason: undefined
  }
  revokeApplyOpen.value = true
}

/** 业务说明: 提交撤销申请 — 后端将月报状态置为"撤销申请中"(状态值4)，待上级单位审核通过或驳回 */
function submitApplyRevoke() {
  proxy.$refs["revokeApplyRef"].validate(valid => {
    if (valid) {
      revokeBisAcciMont(revokeApplyForm.value).then(response => {
        proxy.$modal.msgSuccess("撤销申请已提交")
        revokeApplyOpen.value = false
        getList()
      })
    }
  })
}

/** 业务说明: 撤销审核 — 上级审核撤销申请。"通过"(checkResult=1)则月报回退至可编辑状态重新填报；"驳回"(checkResult=2)则维持已上报状态 */
function handleRevokeCheck(row) {
  revokeCheckForm.value = {
    guid: row.guid,
    mont: row.mont,
    revokeReason: row.revokeReason || row.checkOpinion || '',
    checkResult: undefined,
    checkOpinion: undefined
  }
  revokeCheckOpen.value = true
}

/** 业务说明: 提交撤销审核结果 — 通过后月报状态回退至"未上报"，驳回后恢复为"已上报" */
function submitRevokeCheck() {
  proxy.$refs["revokeCheckRef"].validate(valid => {
    if (valid) {
      revokeBisAcciMont({
        guid: revokeCheckForm.value.guid,
        checkResult: revokeCheckForm.value.checkResult,
        checkOpinion: revokeCheckForm.value.checkOpinion
      }).then(response => {
        const action = revokeCheckForm.value.checkResult === '1' ? '撤销审核通过' : '撤销审核驳回'
        proxy.$modal.msgSuccess(action)
        revokeCheckOpen.value = false
        getList()
      })
    }
  })
}

/** 业务说明: 加锁/解锁 — 仅水利部管理员可操作。加锁(isLock=1)后该月报被冻结，下级单位无法上报和修改，用于归档锁定；解锁后恢复可上报 */
function handleLock(row) {
  const action = row.isLock === '1' ? '解锁' : '加锁'
  const title = action + '月份为"' + row.mont + '"的月报？'
  proxy.$modal.confirm('是否确认' + title).then(function () {
    return lockBisAcciMont({ guid: row.guid, isLock: row.isLock === '1' ? '0' : '1' })
  }).then(() => {
    getList()
    fetchPeriodList()
    proxy.$modal.msgSuccess(action + "成功")
  }).catch(() => {})
}

/** 删除按钮操作 */
function handleDelete(row) {
  const guids = row.guid || ids.value
  proxy.$modal.confirm('是否确认删除月报编号为"' + guids + '"的数据项？').then(function () {
    return delBisAcciMont(guids)
  }).then(() => {
    getList()
    fetchPeriodList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("acci/bisaccimont/export", {
    ...queryParams.value
  }, `acciMont_${new Date().getTime()}.xlsx`)
}

// ========== 月报填报 ==========

/** 业务说明: 提交月报填报 — 下级单位选择月份并填写月报内容后提交，新增一条月报记录，状态默认为"未上报"(状态值0) */
function submitFill() {
  proxy.$refs["fillRef"].validate(valid => {
    if (valid) {
      fillLoading.value = true
      addBisAcciMont(fillForm.value).then(response => {
        fillLoading.value = false
        proxy.$modal.msgSuccess("保存成功")
        resetFill()
        activeTab.value = "list"
        getList()
      }).catch(() => {
        fillLoading.value = false
      })
    }
  })
}

/** 重置填报表单 */
function resetFill() {
  fillForm.value = {
    mont: undefined,
    montContent: undefined,
    note: undefined
  }
  proxy.resetForm("fillRef")
}

// ========== 期间表管理 ==========
// 业务说明: 期间表是系统按年份预先生成的12个月报填报期间(1-12月)，各级单位基于期间表按月填报事故月报。
// 期间表由系统在每年初自动批量初始化，状态分为: 未上报(0)、已上报(1)、已审核(2)、撤销申请中(4)

/** 业务说明: 查询期间表列表 — 获取指定年份/月份的期间记录，用于查看各月填报状态和锁定情况 */
function fetchPeriodList() {
  periodLoading.value = true
  listBisAcciMont(periodQuery).then(res => {
    periodLoading.value = false
    periodList.value = res.rows
    periodTotal.value = res.total
  })
}

/** 期间表搜索 */
function handlePeriodQuery() {
  periodQuery.pageNum = 1
  fetchPeriodList()
}

/** 重置期间表搜索 */
function resetPeriodQuery() {
  periodQuery.year = undefined
  periodQuery.month = undefined
  periodQuery.montStat = undefined
  proxy.resetForm("periodQueryRef")
  handlePeriodQuery()
}

// ========== 附件管理 ==========

/** 附件管理按钮 */
function handleAttachment(row) {
  currentAttachGuid.value = row.guid
  attachOpen.value = true
  fetchAttachList()
}

/** 查询附件列表 */
function fetchAttachList() {
  if (!currentAttachGuid.value) return
  attachLoading.value = true
  request({
    url: '/acci/medbase/list',
    method: 'get',
    params: { bizGuid: currentAttachGuid.value }
  }).then(res => {
    attachLoading.value = false
    attachList.value = res.rows || []
  }).catch(() => {
    attachLoading.value = false
  })
}

/** 上传前校验 */
function beforeUpload(file) {
  const maxSize = 10 * 1024 * 1024
  if (file.size > maxSize) {
    proxy.$modal.msgError('文件大小不能超过10MB')
    return false
  }
  attachUploading.value = true
  return true
}

/** 上传成功 */
function handleUploadSuccess(response, file, fileList) {
  if (response.code === 200) {
    attachUploading.value = false
    proxy.$modal.msgSuccess('上传成功')
    fetchAttachList()
  } else {
    attachUploading.value = false
    proxy.$modal.msgError(response.msg || '上传失败')
  }
}

/** 上传失败 */
function handleUploadError() {
  attachUploading.value = false
  proxy.$modal.msgError('上传失败')
}

/** 下载附件 */
function handleDownloadAttach(row) {
  proxy.download('common/download', { fileName: row.medPath }, row.medName)
}

onMounted(() => {
  getList()
  fetchPeriodList()
})
</script>
