<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="统计年份" prop="statYear">
        <el-date-picker v-model="queryParams.statYear" type="year" placeholder="选择年份" value-format="YYYY" />
      </el-form-item>
      <el-form-item label="机构名称" prop="orgGuid">
        <el-input v-model="queryParams.orgGuid" placeholder="请输入机构名称" clearable style="width: 180px" @keyup.enter="handleQuery" />
      </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="['hidd:eva:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" storageKey="hidd-eva-index"></right-toolbar>
    </el-row>

    <el-row :gutter="20" class="mb8">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>隐患等级分布</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="gradChartRef" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>隐患状态分布</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="statChartRef" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb8">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>月度趋势</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="trendChartRef" style="height: 400px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="table-wrapper">
    <el-table v-loading="loading" :data="hiddEvaList">
      <el-table-column label="机构名称" align="center" prop="orgGuid" :show-overflow-tooltip="true" />
      <el-table-column label="统计年份" align="center" prop="statYear" />
      <el-table-column label="重大隐患数" align="center" prop="majorHidd" />
      <el-table-column label="一般隐患数" align="center" prop="normalHidd" />
      <el-table-column label="隐患总数" align="center" prop="totalHidd" />
      <el-table-column label="已整改数" align="center" prop="solvedHidd" />
      <el-table-column label="整改率" align="center" prop="solveRate">
        <template #default="scope">
          <el-progress :percentage="scope.row.solveRate" :color="scope.row.solveRate >= 80 ? '#67C23A' : scope.row.solveRate >= 60 ? '#E6A23C' : '#F56C6C'"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="评分" align="center" prop="score" />
    </el-table>
    </div>

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

<script setup name="TBusiHiddEva">
import { listTBusiHiddEva } from "@/api/slaj/hidd"
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()

const hiddEvaList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)

const gradChartRef = ref(null)
const statChartRef = ref(null)
const trendChartRef = ref(null)

let gradChart = null
let statChart = null
let trendChart = null

const columns = ref({
  orgGuid: { label: '机构名称', visible: true },
  statYear: { label: '统计年份', visible: true },
  majorHidd: { label: '重大隐患数', visible: true },
  normalHidd: { label: '一般隐患数', visible: true },
  totalHidd: { label: '隐患总数', visible: true },
  solvedHidd: { label: '已整改数', visible: true },
  solveRate: { label: '整改率', visible: true },
  score: { label: '评分', visible: true }
})

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    statYear: undefined,
    orgGuid: undefined
  }
})

const { queryParams } = toRefs(data)

/** 查询隐患评估列表 */
function getList() {
  loading.value = true
  listTBusiHiddEva(queryParams.value).then(res => {
    loading.value = false
    hiddEvaList.value = res.rows
    total.value = res.total
    initCharts()
  })
}

/** 初始化图表 */
function initCharts() {
  initGradChart()
  initStatChart()
  initTrendChart()
}

/** 初始化等级分布图表 */
function initGradChart() {
  if (gradChart) {
    gradChart.dispose()
  }
  gradChart = echarts.init(gradChartRef.value)
  
  const majorHidd = hiddEvaList.value.reduce((sum, item) => sum + (item.majorHidd || 0), 0)
  const normalHidd = hiddEvaList.value.reduce((sum, item) => sum + (item.normalHidd || 0), 0)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '隐患等级',
        type: 'pie',
        radius: '50%',
        data: [
          { value: majorHidd, name: '重大隐患' },
          { value: normalHidd, name: '一般隐患' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  gradChart.setOption(option)
}

/** 初始化状态分布图表 */
function initStatChart() {
  if (statChart) {
    statChart.dispose()
  }
  statChart = echarts.init(statChartRef.value)
  
  const solvedHidd = hiddEvaList.value.reduce((sum, item) => sum + (item.solvedHidd || 0), 0)
  const totalHidd = hiddEvaList.value.reduce((sum, item) => sum + (item.totalHidd || 0), 0)
  const solvingHidd = hiddEvaList.value.reduce((sum, item) => sum + (item.solvingHidd || 0), 0)
  const unsolvedHidd = totalHidd - solvedHidd - solvingHidd
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '隐患状态',
        type: 'pie',
        radius: '50%',
        data: [
          { value: solvedHidd, name: '已整改' },
          { value: solvingHidd, name: '整改中' },
          { value: unsolvedHidd, name: '未整改' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  statChart.setOption(option)
}

/** 初始化月度趋势图表 */
function initTrendChart() {
  if (trendChart) {
    trendChart.dispose()
  }
  trendChart = echarts.init(trendChartRef.value)
  
  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  const totalData = new Array(12).fill(0)
  const solvedData = new Array(12).fill(0)
  
  hiddEvaList.value.forEach(item => {
    if (item.statMonth) {
      const month = parseInt(item.statMonth) - 1
      if (month >= 0 && month < 12) {
        totalData[month] += item.totalHidd || 0
        solvedData[month] += item.solvedHidd || 0
      }
    }
  })
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['隐患总数', '已整改数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '隐患总数',
        type: 'line',
        data: totalData,
        smooth: true
      },
      {
        name: '已整改数',
        type: 'line',
        data: solvedData,
        smooth: true
      }
    ]
  }
  trendChart.setOption(option)
}

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

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

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

onMounted(() => {
  getList()
  window.addEventListener('resize', () => {
    gradChart?.resize()
    statChart?.resize()
    trendChart?.resize()
  })
})

onUnmounted(() => {
  gradChart?.dispose()
  statChart?.dispose()
  trendChart?.dispose()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-container {
  width: 100%;
}
</style>
