<template>
  <div class="app-container">
    <div class="global-top-bar">
      <span v-html="promptText" style="font-weight: bold; font-size: 13px;"></span>
    </div>
    <div class="month-layout">
      <div class="tree-panel">
        <div class="tree-header">
          上报状态&nbsp;&nbsp;
          <span class="status-dot reported"></span> 已上报&nbsp;
          <span class="status-dot unreported"></span> 未上报
          <el-button link type="primary" icon="Refresh" @click="loadTree" style="float:right;" />
        </div>
        <el-tree ref="treeRef" :data="treeData" :props="treeProps" node-key="id" :highlight-current="true" :expand-on-click-node="true" :default-expand-all="false" @node-click="handleNodeClick">
          <template #default="{ data }">
            <span v-if="data.IsUpload !== undefined" :style="{ color: data.IsUpload === 1 ? '#579575' : '#D8B83F' }">{{ data.label }}</span>
            <span v-else>{{ data.label }}</span>
          </template>
        </el-tree>
      </div>
      <div class="table-panel">
        <div class="filter-bar">
          <span class="filter-label">月报期间：</span>
          <span style="font-size:13px;">{{ periodText }}</span>
          <span class="filter-label" style="margin-left:12px;">上报单位：</span>
          <el-radio-group v-model="unitType" @change="loadStats" class="filter-radios">
            <el-radio value="0">本单位上报</el-radio>
            <el-radio value="1">直属单位上报</el-radio>
            <el-radio value="2">下级行政主管部门上报</el-radio>
          </el-radio-group>
          <el-button size="small" @click="handlePendingApproval" style="margin-left:auto;" v-hasPermi="['acci:month:supervise']">
            待审批<el-badge v-if="pendingCount > 0" :value="pendingCount" :max="99" style="margin-left:4px;" />
          </el-button>
          <el-button size="small" type="primary" @click="handleReport" v-hasPermi="['acci:month:report']">上报</el-button>
          <el-button size="small" @click="handleBatchRevoke" v-hasPermi="['acci:month:report']">撤销</el-button>
        </div>
        <div class="action-bar">
          <span class="filter-label">选择月份：</span>
          <el-select v-model="selectedMonth" placeholder="请选择月份" size="small" style="width:160px" @change="handleMonthChange">
            <el-option v-for="item in monthOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-button size="small" @click="handleBatchUnlock" style="margin-left:12px;" v-hasPermi="['acci:month:supervise']">一键解锁</el-button>
        </div>
        <el-table v-loading="loading" :data="statsList" stripe border height="calc(100vh - 280px)" style="width: 100%">
          <el-table-column label="序号" align="center" type="index" width="55" />
          <el-table-column label="上报单位" align="center" min-width="130" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-link type="primary" @click="handleOrgDetail(scope.row)" v-hasPermi="['acci:month:detail']">{{ scope.row.orgName || '--' }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="上报时间" align="center" width="90">
            <template #default="scope">
              {{ scope.row.repAct === '1' ? (scope.row.repTime ? scope.row.repTime.substring(0, 10) : '--') : '' }}
            </template>
          </el-table-column>
          <el-table-column label="事故总起数" align="center" width="90" prop="totalCount" />
          <el-table-column label="死亡人数（人）" align="center" width="110" prop="casNum" />
          <el-table-column label="重伤人数（人）" align="center" width="110" prop="serInjNum" />
          <el-table-column label="直接经济损失（万元）" align="center" width="140" prop="econLoss" />
          <el-table-column label="操作" align="center" width="110" fixed="right">
            <template #default="scope">
              <el-button v-if="scope.row.repAct !== '1'" link type="warning" @click="handleSupervise(scope.row)" v-hasPermi="['acci:month:supervise']">督促上报</el-button>
              <el-tag v-else type="success" size="small">已上报</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="loadStats" />
      </div>
    </div>

    <el-dialog title="月报撤回申请" v-model="revocOpen" width="500px" append-to-body>
      <el-form :model="revocForm" ref="revocRef" label-width="100px">
        <el-form-item label="撤回原因" prop="revocDesc" :rules="[{ required: true, message: '请填写撤回原因', trigger: 'blur' }]">
          <el-input v-model="revocForm.revocDesc" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请输入撤回原因（500字以内）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitRevoc">确 定</el-button>
        <el-button @click="revocOpen = false">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog title="退回重报" v-model="returnOpen" width="500px" append-to-body>
      <el-form :model="returnForm" ref="returnRef" label-width="100px">
        <el-form-item label="退回说明" prop="returnDesc" :rules="[{ required: true, message: '请填写退回说明', trigger: 'blur' }]">
          <el-input v-model="returnForm.returnDesc" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请输入退回说明（500字以内）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitReturn">确 定</el-button>
        <el-button @click="returnOpen = false">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog title="审批详情" v-model="pendingOpen" width="900px" append-to-body>
      <el-table :data="pendingList" stripe border>
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="申请单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column label="申请月份" align="center" prop="mont" width="100" />
        <el-table-column label="上报说明" align="center" prop="reportDesc" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="撤回原因" align="center" prop="revocDesc" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="140">
          <template #default="scope">
            <el-button link type="primary" @click="handleApprove(scope.row)" v-hasPermi="['acci:month:supervise']">同意</el-button>
            <el-button link type="danger" @click="handleReject(scope.row)" v-hasPermi="['acci:month:supervise']">不同意</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="pendingOpen = false">关 闭</el-button>
      </template>
    </el-dialog>
    <el-dialog title="月报详情" v-model="detailOpen" width="80%" top="3vh" append-to-body destroy-on-close>
      <div style="display:flex; gap:10px;">
        <div style="width:200px; min-width:200px; border:1px solid #e4e7ed; border-radius:4px; padding:8px; max-height:500px; overflow:auto;">
          <el-tree :data="detailTree" :props="detailTreeProps" node-key="guid" highlight-current @node-click="handleDetailTreeClick" default-expand-all />
        </div>
        <div style="flex:1; min-width:0;">
          <div style="font-weight:bold; font-size:14px; padding-bottom:8px; border-bottom:1px solid #e4e7ed; margin-bottom:12px;">基本档案</div>
          <el-table :data="detailList" border size="small" height="400" style="width:100%">
            <el-table-column label="序号" align="center" type="index" width="50" />
            <el-table-column label="发生事故单位" align="center" min-width="140" :show-overflow-tooltip="true">
              <template #default="scope">
                {{ scope.row.acciWiunName || '--' }}&nbsp;
                <el-tag size="small">{{ scope.row.acciWiunType === '1' ? '直属' : scope.row.acciWiunType === '2' ? '下级' : scope.row.acciWiunType === '3' ? '流域' : '' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="死亡人数（人）" align="center" prop="casNum" width="100" />
            <el-table-column label="重伤人数（人）" align="center" prop="serInjNum" width="100" />
            <el-table-column label="直接经济损失（万元）" align="center" prop="econLoss" width="140" />
            <el-table-column label="事故类别" align="center" prop="acciCate" width="90" />
          </el-table>
          <pagination :total="detailTotal" v-model:page="detailQuery.pageNum" v-model:limit="detailQuery.pageSize" @pagination="loadDetailList" layout="total, prev, pager, next" style="padding-top:8px;" />
          <div style="margin-top:12px; padding-top:8px; border-top:1px solid #e4e7ed;">
            <span style="font-weight:bold;">相关资料：</span>
            <span v-if="detailList.length === 0" style="color:#999;">暂无</span>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailOpen = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AcciMonth">
import { listBisAcciMont, getAcciTreeData, getAcciMontSummary, revokeBisAcciMont, returnBisAcciMont, updateBisAcciMont, batchUnlockAcciMont, urgeAcciMont } from "@/api/slaj/acci"
import { listObjAcci } from "@/api/slaj/acci"

const { proxy } = getCurrentInstance()

const treeRef = ref(null)
const treeData = ref([])
const treeProps = { children: 'children', label: 'label' }

const loading = ref(false)
const total = ref(0)
const queryParams = reactive({ pageNum: 1, pageSize: 10 })
const statsList = ref([])
const unitType = ref('1')
const selectedMonth = ref('')
const selectedYear = ref('')

const promptText = ref('')

function getPeriodText() {
  const d = new Date()
  let mon = d.getDate() <= 9 ? d.getMonth() : d.getMonth() + 1
  if (mon === 0) mon = 12
  const nextMonth = mon === 12 ? 1 : mon + 1
  const nextYear = mon === 12 ? d.getFullYear() + 1 : d.getFullYear()
  const start = d.getFullYear() + '-' + String(mon).padStart(2, '0') + '-07'
  const end = nextYear + '-' + String(nextMonth).padStart(2, '0') + '-06'
  return start + ' 至 ' + end
}
const periodText = ref(getPeriodText())

const statsTotal = reactive({ directlyNum: 0, directlyRepNum: 0, riverInstNum: 0, riverInstRepNum: 0, subAdminNum: 0, subAdminRepNum: 0 })

const revocOpen = ref(false)
const revocForm = ref({})
const returnOpen = ref(false)
const returnForm = ref({})
const pendingOpen = ref(false)
const pendingList = ref([])
const pendingCount = ref(0)

const detailOpen = ref(false)
const detailTree = ref([])
const detailTreeProps = { children: 'children', label: 'orgName' }
const detailList = ref([]); const detailTotal = ref(0)
const detailQuery = reactive({ pageNum: 1, pageSize: 10 })

const monthOptions = ref([])
function buildMonthOptions() {
  const options = []
  const now = new Date()
  for (let y = now.getFullYear(); y >= now.getFullYear() - 2; y--) {
    for (let m = 12; m >= 1; m--) {
      options.push({ value: y + '-' + String(m).padStart(2, '0'), label: y + '年' + m + '月' })
    }
  }
  monthOptions.value = options
}

function handleMonthChange(val) {
  if (!val) return
  const parts = val.split('-')
  selectedYear.value = parts[0]
  selectedMonth.value = val
  loadStats()
  loadPromptStats()
}

function loadTree() {
  getAcciTreeData().then(res => {
    treeData.value = res.data || []
    if (treeData.value.length > 0) {
      const yearNode = treeData.value[0]
      if (yearNode.children && yearNode.children.length > 0) {
        const now = new Date()
        const currentMonth = now.getMonth() + 1
        let found = yearNode.children.find(n => Number(n.month) === currentMonth)
        if (!found) found = yearNode.children[yearNode.children.length - 1]
        setTimeout(() => {
          treeRef.value?.setCurrentKey(found.id)
          handleNodeClick(found)
          selectedMonth.value = found.id
        }, 100)
      }
    }
  })
}

function handleNodeClick(data) {
  if (!data.month) return
  selectedMonth.value = data.id
  selectedYear.value = data.pId
  loadStats()
  loadPromptStats()
}

function updatePrompt() {
  const d = new Date()
  const dateStr = d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日'
  let mon = d.getDate() <= 9 ? d.getMonth() : d.getMonth() + 1
  if (mon === 0) mon = 12
  const nextMonth = mon === 12 ? 1 : mon + 1
  promptText.value = `温馨提示:&nbsp;&nbsp;今天是${dateStr},${mon}月事故月报:&nbsp;&nbsp;直属单位月报上报情况:${statsTotal.directlyRepNum}/${statsTotal.directlyNum};&nbsp;&nbsp;下级行政主管部门月报上报情况:${statsTotal.subAdminRepNum}/${statsTotal.subAdminNum};&nbsp;&nbsp;月报开始时间:${mon}月07日至${nextMonth}月09日`
}

function loadPromptStats() {
  if (!selectedMonth.value) return
  getAcciMontSummary({ mont: selectedMonth.value }).then(res => {
    const data = res.data || []
    statsTotal.directlyNum = 0; statsTotal.directlyRepNum = 0
    statsTotal.riverInstNum = 0; statsTotal.riverInstRepNum = 0
    statsTotal.subAdminNum = 0; statsTotal.subAdminRepNum = 0
    data.forEach(item => {
      const t = item.repType
      if (t === '1') { statsTotal.directlyNum += item.totalCount || 0; if (item.repAct === '1') statsTotal.directlyRepNum += item.repCount || 0 }
      else if (t === '2') { statsTotal.subAdminNum += item.totalCount || 0; if (item.repAct === '1') statsTotal.subAdminRepNum += item.repCount || 0 }
      else if (t === '3') { statsTotal.riverInstNum += item.totalCount || 0; if (item.repAct === '1') statsTotal.riverInstRepNum += item.repCount || 0 }
    })
    updatePrompt()
  }).catch(() => { updatePrompt() })
}

function loadStats() {
  if (!selectedMonth.value) return
  loading.value = true
  listBisAcciMont({ mont: selectedMonth.value, pageNum: queryParams.pageNum, pageSize: queryParams.pageSize }).then(res => {
    statsList.value = (res.rows || []).map(r => ({ ...r, repAct: r.montStat === '1' || r.montStat === '2' ? '1' : '0' }))
    total.value = res.total || 0
  }).finally(() => { loading.value = false })
}

function handleReport() {
  if (!selectedMonth.value) { proxy.$modal.msgWarning('请先在左侧选择月份'); return }
  proxy.$router.push({ path: '/slaj/acci/monthDetail', query: { month: selectedMonth.value, year: selectedYear.value } })
}

function handleOrgDetail(row) {
  detailOpen.value = true
  detailTree.value = [{ guid: row.orgGuid || '0', orgName: row.orgName || '本单位', children: [] }]
  loadDetailList()
}
function loadDetailList() {
  listObjAcci({ mont: selectedMonth.value, pageNum: detailQuery.pageNum, pageSize: detailQuery.pageSize }).then(res => {
    detailList.value = res.rows || []; detailTotal.value = res.total || 0
  })
}
function handleDetailTreeClick(data) {
  listObjAcci({ orgGuid: data.guid, mont: selectedMonth.value, pageNum: detailQuery.pageNum, pageSize: detailQuery.pageSize }).then(res => {
    detailList.value = res.rows || []; detailTotal.value = res.total || 0
  })
}

function handleRevocApply(row) {
  revocForm.value = { guid: row.guid, revocDesc: '' }
  revocOpen.value = true
}

function submitRevoc() {
  proxy.$refs.revocRef.validate(valid => {
    if (valid) {
      revokeBisAcciMont({ guid: revocForm.value.guid, revocationAudit: '0', revocationAuditResult: revocForm.value.revocDesc, repAct: '4' }).then(() => {
        proxy.$modal.msgSuccess('撤回申请已提交')
        revocOpen.value = false
        loadStats(); loadPromptStats()
      })
    }
  })
}

function handleSupervise(row) {
  proxy.$modal.confirm('您确定要督促上报这条数据吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
    urgeAcciMont(row.orgGuid, selectedMonth.value).then(() => {
      proxy.$modal.msgSuccess('督促上报成功')
    })
  }).catch(() => {})
}

function handleReturn(row) {
  returnForm.value = { guid: row.guid, returnDesc: '' }
  returnOpen.value = true
}

function submitReturn() {
  proxy.$refs.returnRef.validate(valid => {
    if (valid) {
      returnBisAcciMont(returnForm.value).then(() => {
        proxy.$modal.msgSuccess('退回成功')
        returnOpen.value = false
        loadStats(); loadPromptStats()
      })
    }
  })
}

function handleBatchUnlock() {
  if (!selectedMonth.value) { proxy.$modal.msgWarning('请先在左侧选择月份'); return }
  const monthGuids = statsList.value.filter(r => r.repAct === '1').map(r => r.guid)
  if (monthGuids.length === 0) { proxy.$modal.msgWarning('当前月份没有已上报的单位'); return }
  proxy.$modal.confirm('您确定要进行解锁操作吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
    batchUnlockAcciMont(monthGuids).then(() => {
      proxy.$modal.msgSuccess('解锁成功')
      loadStats(); loadPromptStats()
    })
  }).catch(() => {})
}

function handlePendingApproval() {
  listBisAcciMont({ montStat: '4', pageSize: 999 }).then(res => {
    pendingList.value = res.rows || []
    pendingCount.value = pendingList.value.length
    pendingOpen.value = true
  })
}
function handleApprove(row) {
  proxy.$modal.confirm('同意该申请后，该单位可进行上报、撤销操作。确认同意？').then(() => {
    updateBisAcciMont({ guid: row.guid, repAct: '0', revocationAudit: '1', revocationAuditResult: '同意' }).then(() => {
      proxy.$modal.msgSuccess('已同意')
      pendingList.value = pendingList.value.filter(r => r.guid !== row.guid)
      pendingCount.value = pendingList.value.length
      loadStats()
    })
  }).catch(() => {})
}
function handleReject(row) {
  proxy.$modal.confirm('驳回后该单位不能进行上报、撤销操作。确认驳回？').then(() => {
    updateBisAcciMont({ guid: row.guid, repAct: '3', revocationAudit: '2', revocationAuditResult: '驳回' }).then(() => {
      proxy.$modal.msgSuccess('已驳回')
      pendingList.value = pendingList.value.filter(r => r.guid !== row.guid)
      pendingCount.value = pendingList.value.length
    })
  }).catch(() => {})
}

function handleBatchRevoke() {
  const canRevoke = statsList.value.filter(r => r.repAct === '1' && unitType.value === '0')
  if (canRevoke.length === 0) { proxy.$modal.msgWarning('当前没有可撤销的月报'); return }
  proxy.$modal.confirm('已超过上报期，确定在线申请撤销？请输入申请撤销原因。', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
    revocForm.value = { guid: canRevoke[0].guid, revocDesc: '' }
    revocOpen.value = true
  }).catch(() => {})
}

onMounted(() => { loadTree(); buildMonthOptions() })
</script>

<style scoped>
.global-top-bar { display: flex; justify-content: space-between; align-items: center; padding: 10px 16px; background: #fff; border: 1px solid #e4e7ed; border-radius: 4px; margin-bottom: 10px; min-height: 40px; }
.month-layout { display: flex; gap: 12px; height: calc(100vh - 150px); }
.tree-panel { width: 220px; min-width: 220px; border: 1px solid #e4e7ed; border-radius: 4px; padding: 8px; overflow-y: auto; background: #fff; }
.tree-header { font-size: 12px; padding: 4px 0 8px 0; border-bottom: 1px solid #e4e7ed; margin-bottom: 8px; }
.status-dot { display: inline-block; width: 14px; height: 14px; border-radius: 2px; vertical-align: middle; margin: 0 2px; }
.status-dot.reported { background-color: #579575; }
.status-dot.unreported { background-color: #D8B83F; }
.table-panel { flex: 1; display: flex; flex-direction: column; gap: 8px; }
.filter-bar { display: flex; align-items: center; padding: 6px 10px; background: #f9f9f9; border: 1px solid #e4e7ed; border-radius: 4px; flex-wrap: wrap; gap: 4px; }
.filter-label { font-size: 13px; font-weight: bold; margin-right: 4px; white-space: nowrap; }
.filter-radios { display: flex; flex-wrap: wrap; }
.action-bar { display: flex; align-items: center; padding: 6px 10px; background: #f9f9f9; border: 1px solid #e4e7ed; border-radius: 4px; margin-top: 6px; gap: 8px; }
:deep(.el-table__header-wrapper th > .cell) { white-space: nowrap !important; }
</style>
