<template>
  <div class="report-container">
    <el-page-header icon="" @back="goBack" content="医院预约报表中心" >
		<template #title>
		      <span></span>
		    </template>
	</el-page-header>

    <el-tabs v-model="activeTab" type="card" style="margin-top: 20px" @tab-change="handleTabChange">
      <!-- 手术预约 -->
      <el-tab-pane label="手术预约" name="surgery">
        <el-row :gutter="20" class="mb-20">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="hover" class="chart-card">
              <div ref="surgeryBarRef" class="chart-large"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="hover" class="chart-card">
              <div ref="surgeryPieRef" class="chart-large"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-card shadow="hover">
          <template #header>
            <div class="card-header">手术预约明细</div>
          </template>
          <el-table :data="surgeryTableData" stripe height="300" style="width: 100%">
            <el-table-column prop="dept" label="科室" />
            <el-table-column prop="surgeon" label="主刀医生" />
            <el-table-column prop="patient" label="患者姓名" />
            <el-table-column prop="date" label="预约日期" />
            <el-table-column prop="status" label="状态" />
            <el-table-column prop="count" label="预约量" />
          </el-table>
        </el-card>
      </el-tab-pane>

      <!-- 床位预约 -->
      <el-tab-pane label="床位预约" name="bed">
        <el-row :gutter="20" class="mb-20">
          <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
            <el-card shadow="hover" class="chart-card">
              <div ref="bedLineRef" class="chart-full"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
            <el-card shadow="hover" class="chart-card">
              <div ref="bedGaugeRef" class="chart-gauge"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="mb-20">
          <el-col :span="24">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">床位占用明细（按病区）</div>
              </template>
              <el-table :data="bedTableData" stripe height="280" style="width: 100%">
                <el-table-column prop="ward" label="病区" />
                <el-table-column prop="total" label="总床位" />
                <el-table-column prop="occupied" label="已占用" />
                <el-table-column prop="available" label="空闲" />
                <el-table-column prop="rate" label="占用率">
                  <template #default="{ row }">
                    <el-progress :percentage="row.rate" :color="getProgressColor(row.rate)" />
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 医技预约 -->
      <el-tab-pane label="医技预约" name="tech">
        <el-row :gutter="20" class="mb-20">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="hover" class="chart-card">
              <div ref="techBarRef" class="chart-large"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="hover" class="chart-card">
              <div ref="techPieRef" class="chart-large"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">医技预约明细</div>
              </template>
              <el-table :data="techTableData" stripe height="300" style="width: 100%">
                <el-table-column prop="type" label="检查类型" />
                <el-table-column prop="dept" label="申请科室" />
                <el-table-column prop="patient" label="患者" />
                <el-table-column prop="scheduledTime" label="预约时间" />
                <el-table-column prop="status" label="状态" />
                <!-- <el-table-column prop="waitTime" label="等待时长(小时)" /> -->
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
	import {
		useRoute,
		useRouter
	} from "vue-router"
	const route = useRoute()
	const router = useRouter()

const goBack = () => {
  ElMessage.info('返回上一页')
}
const activeTab = ref('surgery')

// 图表引用
const surgeryBarRef = ref(null)
const surgeryPieRef = ref(null)
const bedLineRef = ref(null)
const bedGaugeRef = ref(null)
const techBarRef = ref(null)
const techPieRef = ref(null)

// 存储所有图表实例
const chartInstances = {
  surgery: [],
  bed: [],
  tech: []
}

// 模拟表格数据
const surgeryTableData = ref([
  { dept: '普外科', surgeon: '张医生', patient: '李明', date: '2025-11-28', status: '已确认', count: 3 },
  { dept: '骨科', surgeon: '王医生', patient: '赵芳', date: '2025-11-29', status: '待确认', count: 2 },
  { dept: '心胸外科', surgeon: '刘医生', patient: '陈强', date: '2025-11-30', status: '已取消', count: 1 },
])

const bedTableData = ref([
  { ward: '内科A区', total: 50, occupied: 42, available: 8, rate: 84 },
  { ward: '外科B区', total: 40, occupied: 30, available: 10, rate: 75 },
  { ward: 'ICU', total: 20, occupied: 18, available: 2, rate: 90 },
  { ward: '儿科', total: 30, occupied: 22, available: 8, rate: 73 },
])

const techTableData = ref([
  { type: 'CT', dept: '急诊科', patient: '周伟', scheduledTime: '2025-11-28 10:00', status: '已完成', waitTime: 2.5 },
  { type: 'MRI', dept: '神经内科', patient: '吴敏', scheduledTime: '2025-11-29 14:30', status: '待检查', waitTime: 0 },
  { type: '超声', dept: '妇产科', patient: '林雪', scheduledTime: '2025-11-30 09:15', status: '已取消', waitTime: 1.2 },
])

// 进度条颜色
const getProgressColor = (rate) => {
  if (rate > 90) return '#e74c3c'
  if (rate > 70) return '#f39c12'
  return '#2ecc71'
}

// 初始化指定标签页的图表
const initTabCharts = (tab) => {
  // 先销毁该标签页已有的图表
  if (chartInstances[tab]) {
    chartInstances[tab].forEach(chart => chart.dispose())
    chartInstances[tab] = []
  }

  const initChart = (ref, option) => {
    if (!ref.value) return
    // 确保DOM元素可见
    const resizeObserver = new ResizeObserver(() => {
      const chart = echarts.init(ref.value)
      chart.setOption(option)
      chartInstances[tab].push(chart)
      resizeObserver.disconnect()
    })
    resizeObserver.observe(ref.value)
  }

  switch (tab) {
    case 'surgery':
      // 手术预约图表
      initChart(surgeryBarRef, {
        title: { text: '近7天手术预约量', left: 'center' },
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
        xAxis: { type: 'category', data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] },
        yAxis: { type: 'value' },
        series: [{ data: [12, 19, 15, 22, 18, 10, 8], type: 'bar', color: '#5470c6' }]
      })

      initChart(surgeryPieRef, {
        title: { text: '手术类型分布', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{
          type: 'pie',
          radius: '60%',
          data: [
            { value: 335, name: '普外科' },
            { value: 310, name: '骨科' },
            { value: 234, name: '心胸外科' },
            { value: 135, name: '神经外科' },
            { value: 154, name: '其他' }
          ]
        }]
      })
      break

    case 'bed':
      // 床位预约图表
      initChart(bedLineRef, {
        title: { text: '床位占用趋势（月度）', left: 'left' },
        tooltip: { trigger: 'axis' },
        legend: { data: ['已预约', '空闲'] },
        grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true },
        xAxis: { type: 'category', data: ['1月', '2月', '3月', '4月', '5月', '6月'] },
        yAxis: { type: 'value' },
        series: [
          { name: '已预约', type: 'line', data: [820, 932, 901, 934, 1290, 1330], smooth: true },
          { name: '空闲', type: 'line', data: [180, 168, 199, 166, 110, 170], smooth: true }
        ]
      })

      initChart(bedGaugeRef, {
        title: { text: '床位使用率', left: 'center', top: '1%' },
        series: [{
          type: 'gauge',
          startAngle: 180,
          endAngle: 0,
          min: 0,
          max: 100,
          progress: { show: true, width: 18 },
          pointer: { show: false },
          axisLine: { lineStyle: { width: 18 } },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
          detail: { 
            formatter: '{value}%', 
            valueAnimation: true,
            offsetCenter: [0, '60%'],
            fontSize: 30
          },
          data: [{ value: 78, name: '' }]
        }]
      })
      break

    case 'tech':
      // 医技预约图表
      initChart(techBarRef, {
        title: { text: '申请科室分布', left: 'center' },
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
        xAxis: { type: 'category', data: ['CT', 'MRI', '超声', '心电图', '内镜'] },
        yAxis: { type: 'value' },
        series: [{ data: [45, 32, 67, 28, 53], type: 'bar', color: '#91cc75' }]
      })

      initChart(techPieRef, {
        title: { text: '预约状态分布', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{
          type: 'pie',
          radius: ['40%', '70%'],
          data: [
            { value: 120, name: '已完成' },
            { value: 30, name: '已取消' },
            { value: 50, name: '待检查' },
			{ value: 10, name: '爽约' }
          ]
        }]
      })
      break
  }
}

// 处理标签切换
const handleTabChange = (tab) => {
  nextTick(() => {
    initTabCharts(tab)
  })
}

// 窗口大小变化时调整图表
const handleResize = () => {
  Object.values(chartInstances).forEach(charts => {
    charts.forEach(chart => chart.resize())
  })
}

onMounted(() => {
	if(route.query.type){
		activeTab.value=route.query.type
	}
  // 初始化默认标签页图表
  initTabCharts(activeTab.value)
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  // 销毁所有图表实例
  Object.values(chartInstances).forEach(charts => {
    charts.forEach(chart => chart.dispose())
  })
})
</script>

<style scoped>
.report-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.mb-20 {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.chart-card {
  height: 100%;
}

/* 图表容器：大尺寸 */
.chart-large {
  width: 100%;
  min-height: 380px;
}

/* 全宽图表（用于折线图） */
.chart-full {
  width: 100%;
  min-height: 360px;
}

/* 仪表盘专用 */
.chart-gauge {
  width: 100%;
  min-height: 360px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>