<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 业务说明: 左侧上报状态树 — 按年份+月份分层展示最近3年的月报上报状态。绿色=该月已上报，橙色=该月未上报(需要关注)，灰色=父节点年/季 -->
      <el-col :span="5">
        <el-card shadow="never">
          <template #header><span>上报状态</span></template>
          <el-tree :data="treeData" :props="treeProps" node-key="id" default-expand-all>
            <template #default="{ node, data }">
              <span :style="{ color: data.reported === true ? '#67c23a' : data.children ? '#333' : '#e6a23c' }">
                {{ data.label }}
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年份" prop="year">
        <el-select v-model="queryParams.year" placeholder="请选择年份" clearable style="width: 160px">
          <el-option v-for="y in yearOptions" :key="y" :label="y + '年'" :value="y" />
        </el-select>
      </el-form-item>
      <el-form-item label="月份" prop="month">
        <el-select v-model="queryParams.month" placeholder="请选择月份" clearable style="width: 160px">
          <el-option v-for="m in 12" :key="m" :label="m + '月'" :value="m" />
        </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">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="fetchStats"></right-toolbar>
    </el-row>

    <!-- 业务说明: 汇总统计卡片 — 四项指标: 总期间数(所选范围的月份总数)、已上报(状态=已上报的数量)、已审核(状态=已审核的数量)、未上报(状态=未上报的数量，需重点关注) -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header><span>总期间数</span></template>
          <div class="stat-value">{{ summary.total || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header><span>已上报</span></template>
          <div class="stat-value" style="color:#67c23a">{{ summary.reported || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header><span>已审核</span></template>
          <div class="stat-value" style="color:#409eff">{{ summary.checked || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header><span>未上报</span></template>
          <div class="stat-value" style="color:#f56c6c">{{ summary.unreported || 0 }}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="statData" stripe>
      <el-table-column label="月份" align="center" prop="month" width="120" />
      <el-table-column label="上报单位数" align="center" prop="reportedCount" width="120" />
      <el-table-column label="未上报单位数" align="center" prop="unreportedCount" width="120" />
      <el-table-column label="上报率(%)" align="center" prop="rate" width="120" />
    </el-table>

    <el-card shadow="hover" class="mt20">
      <template #header><span>各月上报率趋势</span></template>
      <div ref="chartRef" style="height: 400px;"></div>
    </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="AcciMontStat">
import { getCurrentInstance, onMounted, reactive, ref, toRefs, nextTick } from 'vue'
import { listBisAcciMont, getAcciMontSummary, getAcciTreeData } from "@/api/slaj/acci"
import * as echarts from "echarts"

const { proxy } = getCurrentInstance()

const loading = ref(false)
const showSearch = ref(true)
const statData = ref([])
const chartRef = ref(null)
let chartInstance = null

// 业务说明: 左侧树数据 — 按年份>月份分层展示近3年状态，green=已上报, orange=未上报, 灰色=父节点
const treeData = ref([])
const treeProps = { children: 'children', label: 'label' }
// 业务说明: 汇总统计 — 由后端统计总期间数/已上报/已审核/未上报四项指标
const summary = ref({})

const currentYear = new Date().getFullYear()
const yearOptions = []
for (let y = 2020; y <= currentYear; y++) {
  yearOptions.push(y)
}

const data = reactive({
  queryParams: {
    year: currentYear,
    month: undefined
  }
})
const { queryParams } = toRefs(data)

/** 查询月报数据并汇总统计 */
function fetchStats() {
  loading.value = true
  const params = { pageNum: 1, pageSize: 99999 }
  if (queryParams.value.year) params.year = String(queryParams.value.year)

  listBisAcciMont(params).then(res => {
    loading.value = false
    const rows = res.rows || []
    calcStats(rows)
  }).catch(() => {
    loading.value = false
  })
}

// 业务说明: 获取左侧上报状态树 — 后端返回近3年按月汇总的上报状态数据，叶子节点按颜色标识是否已上报
function fetchTree() {
  getAcciTreeData().then(res => { treeData.value = res.data || [] })
}

// 业务说明: 获取汇总统计 — total=总期间数, reported=已上报, checked=已审核, unreported=未上报
function fetchSummary() {
  getAcciMontSummary(queryParams.value).then(res => { summary.value = res.data || {} })
}

/** 业务说明: 前端汇总计算各月上报情况 — 根据月报列表数据，按月份归集上报单位数、未上报单位数和上报率。上报率=已上报单位数/总单位数×100% */
function calcStats(rows) {
  const monthMap = {}
  const allOrgs = new Set()

  rows.forEach(row => {
    const m = row.mont
    if (!m) return
    if (!monthMap[m]) monthMap[m] = { orgs: new Set() }
    const orgKey = row.orgGuid || row.deptId || row.createBy
    if (orgKey) {
      monthMap[m].orgs.add(orgKey)
      allOrgs.add(orgKey)
    }
  })

  const totalOrgs = allOrgs.size
  let stats = Object.entries(monthMap)
    .sort(([a], [b]) => (a || '').localeCompare(b || ''))
    .map(([month, data]) => ({
      month,
      reportedCount: data.orgs.size,
      unreportedCount: totalOrgs - data.orgs.size,
      rate: totalOrgs > 0 ? ((data.orgs.size / totalOrgs) * 100).toFixed(2) : '0.00'
    }))

  // 按月份筛选
  if (queryParams.value.month) {
    const mStr = String(queryParams.value.month).padStart(2, '0')
    stats = stats.filter(item => item.month.endsWith('-' + mStr))
  }

  statData.value = stats
  nextTick(() => initChart(stats))
}

/** 业务说明: 初始化上报率趋势柱状图 — 按月份展示各单位上报率的时序变化，便于分析上报进度和滞后月份 */
function initChart(data) {
  if (!chartRef.value) return
  if (chartInstance) chartInstance.dispose()
  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const p = params[0]
        return p.axisValue + '<br/>上报率: ' + p.value + '%'
      }
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: data.map(d => d.month), axisLabel: { rotate: 30 } },
    yAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value}%' } },
    series: [{
      name: '上报率', type: 'bar', barWidth: '50%',
      data: data.map(d => Number(d.rate)),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#409eff' },
          { offset: 1, color: '#79bbff' }
        ])
      },
      label: { show: true, position: 'top', formatter: '{c}%' }
    }]
  })
}

function handleQuery() {
  fetchStats()
}

function resetQuery() {
  queryParams.value.month = undefined
  proxy.resetForm("queryRef")
  fetchStats()
}

function handleExport() {
  proxy.download("acci/bisaccimont/export", {
    ...queryParams.value
  }, `montStat_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  fetchStats()
  fetchTree()
  fetchSummary()
})
</script>
