<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="3">流域机构上报</el-radio>
            <el-radio value="2">下级水行政部门上报</el-radio>
          </el-radio-group>
          <el-button size="small" @click="handlePendingApproval" style="margin-left:auto;">
            待审批<el-badge v-if="pendingCount > 0" :value="pendingCount" :max="99" style="margin-left:4px;" />
          </el-button>
          <el-button size="small" type="primary" @click="handleReport">上报</el-button>
          <el-button size="small" @click="handleBatchRevoke">撤销</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;">一键解锁</el-button>
          <el-button size="small" @click="handleCustomPeriod">自定义上报期</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)">{{ scope.row.repName || 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">
            <el-table-column label="重大隐患" align="center" width="80" prop="impHiddCount" />
            <el-table-column label="逾期未整改" align="center" width="90" prop="overUnImplRect" />
            <el-table-column label="未落实整改" align="center" width="90" prop="unSolvedCount" />
            <el-table-column label="正在整改" align="center" width="80" prop="solvingCount" />
            <el-table-column label="完成整改" align="center" width="80" prop="hasSolvedCount" />
            <el-table-column label="整改率" align="center" width="70">
              <template #default="scope">
                {{ scope.row.solveRate != null ? Number(scope.row.solveRate * 100).toFixed(2) + '%' : '0.00%' }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="操作" align="center" width="110" fixed="right">
            <template #default="scope">
              <template v-if="unitType === '0'">
                <el-button v-if="scope.row.repAct === '1'" link type="primary" @click="handleRevocApply(scope.row)">回撤</el-button>
                <span v-else style="color: #999;">未上报</span>
              </template>
              <template v-else>
                <el-tag v-if="scope.row.repAct === '1'" type="success" size="small">已上报</el-tag>
                <el-button v-else link type="warning" @click="handleSupervise(scope.row)">督促上报</el-button>
                <el-button v-if="scope.row.repAct === '1'" link type="danger" @click="handleReturn(scope.row)">退回</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </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="800px" 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="repOrgName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="申请月份" align="center" prop="repTime" width="120" />
        <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)">同意</el-button>
            <el-button link type="danger" @click="handleReject(scope.row)">不同意</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="unlockOpen" width="500px" append-to-body>
      <el-form :model="unlockForm" ref="unlockRef" label-width="100px">
        <el-form-item label="月份">
          <span>{{ selectedMonth || '请先在左侧选择月份' }}</span>
        </el-form-item>
        <el-form-item label="解锁说明">
          <el-input v-model="unlockForm.unlockDesc" type="textarea" :rows="3" placeholder="请输入解锁说明（选填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitUnlock">确 定</el-button>
        <el-button @click="unlockOpen = false">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog title="自定义上报期" v-model="periodOpen" width="600px" append-to-body>
      <el-form :model="periodForm" ref="periodRef" label-width="110px">
        <el-form-item label="年份">
          <el-select v-model="periodForm.year" placeholder="选择年份" style="width:150px">
            <el-option v-for="y in availableYears" :key="y" :label="y + '年'" :value="y" />
          </el-select>
        </el-form-item>
        <el-form-item label="月份">
          <el-select v-model="periodForm.month" placeholder="选择月份" style="width:150px">
            <el-option v-for="m in 12" :key="m" :label="m + '月'" :value="m" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate" :rules="[{ required: true, message: '请选择开始日期', trigger: 'change' }]">
          <el-date-picker v-model="periodForm.startDate" type="date" placeholder="选择开始日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate" :rules="[{ required: true, message: '请选择结束日期', trigger: 'change' }]">
          <el-date-picker v-model="periodForm.endDate" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitPeriod">确 定</el-button>
        <el-button @click="periodOpen = false">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="detailTitle" v-model="detailOpen" width="85%" top="5vh" append-to-body destroy-on-close>
      <div v-loading="detailLoading" style="min-height:400px;">
        <iframe v-if="detailOpen && detailUrl" :src="detailUrl" style="width:100%;height:70vh;border:0;" />
      </div>
      <template #footer>
        <el-button @click="detailOpen = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MonthReport">
import { getRepTreeData, getMonthListStats, revokeMonth, returnMonth, approveRevoke, batchUnlock, urgeReport, revokeApproveList, checkCanRevoke, addBisOrgMonRepPeri } from "@/api/slaj/hidd"

const { proxy } = getCurrentInstance()

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

const loading = ref(false)
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 unlockOpen = ref(false)
const unlockForm = ref({})
const periodOpen = ref(false)
const periodForm = ref({ year: new Date().getFullYear(), month: new Date().getMonth() + 1, startDate: '', endDate: '' })
const availableYears = [new Date().getFullYear() - 2, new Date().getFullYear() - 1, new Date().getFullYear()]

const detailOpen = ref(false)
const detailTitle = ref('隐患月报详情')
const detailLoading = ref(false)
const detailUrl = ref('')

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()
  loadPendingCount()
}

function loadPendingCount() {
  revokeApproveList().then(res => {
    const list = res.rows || res.data || []
    pendingCount.value = list.length
  }).catch(() => {
    pendingCount.value = 0
  })
}

function loadTree() {
  getRepTreeData().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.riverInstRepNum}/${statsTotal.riverInstNum};&nbsp;&nbsp;下级水行政主管部门月报上报情况:${statsTotal.subAdminRepNum}/${statsTotal.subAdminNum};&nbsp;&nbsp;月报开始时间:${mon}月07日至${nextMonth}月09日`
}

function loadPromptStats() {
  if (!selectedMonth.value) return
  getMonthListStats({ repTime: 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++; if (item.repAct === '1') statsTotal.directlyRepNum++ }
      else if (t === '3') { statsTotal.riverInstNum++; if (item.repAct === '1') statsTotal.riverInstRepNum++ }
      else if (t === '2') { statsTotal.subAdminNum++; if (item.repAct === '1') statsTotal.subAdminRepNum++ }
    })
    updatePrompt()
  }).catch(() => { updatePrompt() })
}

function loadStats() {
  if (!selectedMonth.value) return
  loading.value = true
  getMonthListStats({ repTime: selectedMonth.value, unitType: unitType.value }).then(res => {
    statsList.value = res.data || []
  }).finally(() => { loading.value = false })
}

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

function handleOrgDetail(row) {
  const orgGuid = row.repOrgGuid || row.orgGuid
  const orgName = row.repName || ''
  detailTitle.value = '隐患月报详情'
  detailUrl.value = `/slaj/hidd/monthDetail?guid=${row.guid}&month=${selectedMonth.value}&orgName=${encodeURIComponent(orgName)}`
  detailOpen.value = true
}

function handleRevocApply(row) {
  checkCanRevoke(selectedMonth.value).then(res => {
    if (res.data === true || res.data === 'true') {
      revocForm.value = { guid: row.guid, revocDesc: '' }
      revocOpen.value = true
    } else {
      proxy.$modal.msgWarning('上级部门已上报无法撤回')
    }
  }).catch(() => {
    revocForm.value = { guid: row.guid, revocDesc: '' }
    revocOpen.value = true
  })
}

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

function handleSupervise(row) {
  const orgGuid = row.repOrgGuid || row.orgGuid
  if (orgGuid) {
    urgeReport(orgGuid, selectedMonth.value).then(() => {
      proxy.$modal.msgSuccess('已发送督促通知')
    })
  }
}

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

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

function handlePendingApproval() {
  revokeApproveList().then(res => {
    pendingList.value = res.rows || res.data || []
    pendingOpen.value = true
  }).catch(() => {
    pendingList.value = []
    pendingOpen.value = true
  })
}

function handleApprove(row) {
  approveRevoke(row.guid, true, '').then(() => {
    proxy.$modal.msgSuccess('已同意撤回')
    pendingList.value = pendingList.value.filter(r => r.guid !== row.guid)
    pendingCount.value = pendingList.value.length
    loadStats()
    loadPromptStats()
  })
}

function handleReject(row) {
  approveRevoke(row.guid, false, '').then(() => {
    proxy.$modal.msgSuccess('已驳回')
    pendingList.value = pendingList.value.filter(r => r.guid !== row.guid)
    pendingCount.value = pendingList.value.length
  })
}

function handleBatchUnlock() {
  if (!selectedMonth.value) { proxy.$modal.msgWarning('请先在左侧选择月份'); return }
  unlockForm.value = { unlockDesc: '' }
  unlockOpen.value = true
}

function submitUnlock() {
  const monthGuids = statsList.value.filter(r => r.repAct === '1').map(r => r.guid)
  if (monthGuids.length === 0) {
    proxy.$modal.msgWarning('当前月份没有已上报的单位')
    unlockOpen.value = false; return
  }
  batchUnlock(monthGuids).then(() => {
    proxy.$modal.msgSuccess('解锁成功')
    unlockOpen.value = false
    loadStats()
    loadPromptStats()
  }).catch(() => {})
}

function handleCustomPeriod() {
  periodForm.value = { year: new Date().getFullYear(), month: new Date().getMonth() + 1, startDate: '', endDate: '' }
  periodOpen.value = true
}

function submitPeriod() {
  proxy.$refs.periodRef.validate(valid => {
    if (valid) {
      const p = periodForm.value
      addBisOrgMonRepPeri({
        repName: p.year + '年' + String(p.month).padStart(2, '0') + '月隐患期间表',
        repAct: '2',
        repType: '0',
        repTime: p.year + '-' + String(p.month).padStart(2, '0'),
        startDate: p.startDate,
        endDate: p.endDate
      }).then(() => {
        proxy.$modal.msgSuccess('自定义上报期设置成功')
        periodOpen.value = false
        loadTree()
      }).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('是否确认撤销本月已上报的月报？').then(() => {
    return revokeMonth(canRevoke[0].guid)
  }).then(() => {
    proxy.$modal.msgSuccess('撤销成功')
    loadStats()
    loadPromptStats()
  }).catch(() => {})
}

onMounted(() => { loadTree(); buildMonthOptions(); loadPendingCount() })
</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;
}
.top-bar-actions {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}
.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>
