<template>
  <div class="left-bottom">
    <div class="panel-title">
      <div class="tabs">
        <span class="tab" :class="{ active: activeTab === '高危作业' }" @click="handleTabClick('高危作业')">高危作业</span>
        <span class="divider">|</span>
        <span class="tab" :class="{ active: activeTab === '安全培训考试' }" @click="handleTabClick('安全培训考试')">安全培训考试</span>
        <span class="divider">|</span>
        <span class="tab" :class="{ active: activeTab === '应急预案及演练' }" @click="handleTabClick('应急预案及演练')">应急预案及演练</span>
      </div>
    </div>
    <img style="margin: 8px 0" src="@/assets/images/title_border_line.png" />
    <div class="bottom-card-risk">
      <div class="bottom-card-title">
        <span>{{ activeTab === '高危作业' ? '各园区统计' : activeTab === '安全培训考试' ? '安全培训考试' : '园区演练完成率' }}</span>
        <img width="50%" style="margin: 8px 0" src="@/assets/images/line_1.png" />
      </div>
    </div>
    <!-- <Echart v-if="activeTab !== '高危作业'" :options="riskChartOption" class="donut-chart-with-labels" height="30vh" /> -->

    <AlertList maxHeight="40vh" v-if="activeTab === '安全培训考试'" :table-title="tableTitle" style="margin-left: 1vw;"
      :list-data="dataList" />

    <div style="width: 80%; padding-left: 1vw;">
      <Echart v-if="activeTab === '高危作业'" style="height: 30vh" :options="barChartOption" class="bar-chart" />
    </div>

    <div ref="riskChart" class="risk-chart" v-if="activeTab === '应急预案及演练'"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import AlertList from './AlertList.vue'
import { rgbToHex } from '@/utils/color'
import * as echarts from 'echarts'
import { getDrillSum, getExamSum, getZBDangerSum } from '../report'
type TabType = '高危作业' | '安全培训考试' | '应急预案及演练'
const activeTab = ref<TabType>('高危作业')
const emit = defineEmits<{
  tabChange: [tab: TabType]
}>()
interface AlertItem {
  description: string
  alarm_level_code: string
  alarm_status: string
  alarm_biz_id: string
}
interface Props {
  riskStatistics?: any
  dangerDetail?: AlertItem[]
  park?: string
  campus_id?: string
}

const tableTitle = [
  {
    name: '园区名称',
    key: 'campus_name'
  },
  {
    name: '累计培训次数',
    key: 'examtimes'
  },
  {
    name: '参与总人次',
    key: 'exampeoplenum'
  },
  {
    name: '累计培训时长',
    key: 'examduration'
  },
  {
    name: '平均通过率',
    key: 'exampassrate'
  }
]

// 图表引用
const barChartOption = ref({
  legend: {
    top: '10%',
    right: '12%',
    orient: 'vertical' as const,
    textStyle: {
      color: '#ffffff',
      fontSize: '11px'
    }
  },
  grid: {
    left: '5%',
    right: '30%',
    top: '10%',
    bottom: '15%'
  },
  xAxis: {
    type: 'category' as const,
    data: [],
    axisLabel: {
      color: '#ffffff',
      fontSize: 10
    },
    axisLine: {
      lineStyle: { color: '#334155' }
    }
  },
  yAxis: {
    type: 'value' as const,
    axisLabel: {
      color: '#ffffff',
      fontSize: 10
    },
    axisLine: {
      lineStyle: { color: '#334155' }
    },
    splitLine: {
      lineStyle: { color: '#334155' }
    }
  },
  series: [
    {
      name: '未开始数量',
      type: 'bar' as const,
      data: [],
      itemStyle: { color: rgbToHex(99, 196, 251) },
      barWidth: '8%',
      label: {
        show: true,
        position: 'top' as const,
        color: '#ffffff',
        fontSize: 12,
        fontWeight: 'bold' as const,
        formatter: '{c}'
      }
    },
    {
      name: '进行中数量',
      type: 'bar' as const,
      data: [],
      itemStyle: { color: rgbToHex(251, 246, 85) },
      barWidth: '8%',
      label: {
        show: true,
        position: 'top' as const,
        color: '#ffffff',
        fontSize: 12,
        fontWeight: 'bold' as const,
        formatter: '{c}'
      }
    },
    {
      name: '已完成数量',
      type: 'bar' as const,
      data: [],
      itemStyle: { color: rgbToHex(200, 69, 237) },
      barWidth: '8%',
      label: {
        show: true,
        position: 'top' as const,
        color: '#ffffff',
        fontSize: 12,
        fontWeight: 'bold' as const,
        formatter: '{c}'
      }
    }
  ]
})

const dataList = ref<AlertItem[]>([
])

const props = defineProps<Props>()

// 图表引用
const riskChart = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null



// 初始化饼图
const initPieChart = async () => {
  if (!riskChart.value) return

  chartInstance = echarts.init(riskChart.value)

  const colors = [
    [
      { offset: 0, color: '#ffb74d' },
      { offset: 0.3, color: '#ff9800' },
      { offset: 0.7, color: '#f57c00' },
      { offset: 1, color: '#e65100' }
    ],
    [
      { offset: 0, color: '#64b5f6' },
      { offset: 0.3, color: '#42a5f5' },
      { offset: 0.7, color: '#2196f3' },
      { offset: 1, color: '#1976d2' }
    ],
    [
      { offset: 0, color: '#81c784' },
      { offset: 0.3, color: '#66bb6a' },
      { offset: 0.7, color: '#4caf50' },
      { offset: 1, color: '#388e3c' }
    ]

  ]

  const res = await getDrillSum(props.campus_id || '')

  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#4a9eff',
      borderWidth: 1,
      textStyle: {
        color: '#ffffff'
      },
      formatter: function (params: any) {
        return `${params.data.name}<br/>完成率: ${params.data.value}%`
      }
    },
    series: [
      {
        name: '园区演练完成率',
        type: 'pie',
        radius: ['30%', '70%'],
        center: ['50%', '50%'],
        data: res.records.map((item, index) => (
          {
            value: item.rate,
            name: item.campus_name,
            itemStyle: {
              color: {
                type: 'radial',
                x: 0.5,
                y: 0.5,
                r: 0.8,
                colorStops: colors[index % 3]
              }
            }
          }
        ))
        // [
        //   {
        //     value: 100,
        //     name: '西安创新院',
        //     itemStyle: {
        //       color: {
        //         type: 'radial',
        //         x: 0.5,
        //         y: 0.5,
        //         r: 0.8,
        //         colorStops: [
        //           { offset: 0, color: '#ffb74d' },
        //           { offset: 0.3, color: '#ff9800' },
        //           { offset: 0.7, color: '#f57c00' },
        //           { offset: 1, color: '#e65100' }
        //         ]
        //       }
        //     }
        //   },
        //   {
        //     value: 63,
        //     name: '北京横毅大厦',
        //     itemStyle: {
        //       color: {
        //         type: 'radial',
        //         x: 0.5,
        //         y: 0.5,
        //         r: 0.8,
        //         colorStops: [
        //           { offset: 0, color: '#64b5f6' },
        //           { offset: 0.3, color: '#42a5f5' },
        //           { offset: 0.7, color: '#2196f3' },
        //           { offset: 1, color: '#1976d2' }
        //         ]
        //       }
        //     }
        //   },
        //   {
        //     value: 60,
        //     name: '重庆产业大厦',
        //     itemStyle: {
        //       color: {
        //         type: 'radial',
        //         x: 0.5,
        //         y: 0.5,
        //         r: 0.8,
        //         colorStops: [
        //           { offset: 0, color: '#81c784' },
        //           { offset: 0.3, color: '#66bb6a' },
        //           { offset: 0.7, color: '#4caf50' },
        //           { offset: 1, color: '#388e3c' }
        //         ]
        //       }
        //     }
        //   }
        // ]
        ,
        label: {
          show: true,
          position: 'inside',
          formatter: function (params: any) {
            return `${params.data.name}\n${params.data.value}%`
          },
          fontSize: 12,
          color: '#ffffff',
          fontWeight: 'bold',
          textShadowColor: 'rgba(0, 0, 0, 0.8)',
          textShadowBlur: 2
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

// 销毁图表
const destroyChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
}

const initBarChart = async () => {
  try {
    const res = await getZBDangerSum(props.campus_id || '')

    // 更新图表数据
    const newOption = {
      ...barChartOption.value,
      xAxis: {
        ...barChartOption.value.xAxis,
        data: res.records.map((item: any) => item.campus_name)
      },
      series: [
        {
          ...barChartOption.value.series[0],
          data: res.records.map((item: any) => item.ywc)
        },
        {
          ...barChartOption.value.series[1],
          data: res.records.map((item: any) => item.jxz)
        },
        {
          ...barChartOption.value.series[2],
          data: res.records.map((item: any) => item.wks)
        }
      ]
    }

    barChartOption.value = newOption

    console.log('Bar chart data updated:', {
      xAxis: barChartOption.value.xAxis.data,
      series: barChartOption.value.series.map(s => ({ name: s.name, data: s.data }))
    })
  } catch (error) {
    console.error('Failed to load bar chart data:', error)
  }
}

// 监听标签页切换
watchEffect(async () => {
  if (activeTab.value === '应急预案及演练') {
    initPieChart()
  } else {
    destroyChart()
  }

  if (activeTab.value === '高危作业') {
    initBarChart()
  }

  if (activeTab.value === '安全培训考试') {
    const res = await getExamSum(props.campus_id || '')

    dataList.value = res.records
  }
})

// 监听数据变化，更新图表
watch(() => props.riskStatistics, (newVal) => {
  console.log('riskStatistics changed:', { newVal })
  if (newVal) {
    refreshCharts(newVal)
  }
}, { deep: true })

// 监听数据变化，更新图表
watch(() => props.dangerDetail, (newVal) => {
  console.log('dangerDetail changed:', { newVal })

}, { deep: true })

// 监听数据变化，更新图表
watch(() => props.dangerDetail, (newVal) => {
  console.log('dangerDetail changed:', { newVal })
  if (newVal) {
    dataList.value = newVal
  }
}, { deep: true })

// 更新图表数据
const refreshCharts = (riskStatistics: any): void => {
  if (!riskStatistics || !Array.isArray(riskStatistics)) {
    console.warn('riskStatistics is undefined, null, or not an array')
    return
  }

  // 计算各园区的完成率
  const chartData = riskStatistics.map((item: any, index: number) => {
    const finishCount = Number(item.finishCount) || 0
    const participateCount = Number(item.participateCount) || 0
    const completionRate = participateCount > 0 ? Math.round((finishCount / participateCount) * 100) : 0

    // 为每个园区分配不同的颜色
    const colors = ['#ef4444', '#10b981', '#eab308', '#3b82f6', '#8b5cf6', '#f59e0b', '#06b6d4', '#84cc16']
    const color = colors[index % colors.length]

    return {
      value: completionRate,
      name: item.csmpus_name || `园区${index + 1}`,
      finishCount: finishCount,
      participateCount: participateCount,
      itemStyle: { color: color }
    }
  })

  console.log("Updated chart data:", chartData)
}

const handleTabClick = async (tab: TabType) => {
  activeTab.value = tab
  emit('tabChange', tab)
}

onMounted(() => {
  // 如果没有传入数据，设置默认数据
  if (!props.riskStatistics) {
    const defaultData = [
      {
        csmpus_name: "雄安新区总部",
        finishCount: "234",
        participateCount: "300"
      },
      {
        csmpus_name: "雄安二区总部",
        finishCount: "180",
        participateCount: "250"
      },
      {
        csmpus_name: "雄安三区总部",
        finishCount: "156",
        participateCount: "200"
      }
    ]
    refreshCharts(defaultData)
  }

  // 如果当前是高危作业标签页，初始化柱状图
  if (activeTab.value === '高危作业') {
    nextTick(() => {
      initBarChart()
    })
  }
})

// 组件卸载时销毁图表
onUnmounted(() => {
  destroyChart()
})
</script>

<style scoped lang="scss">
.left-bottom {
  background-image: url('@/assets/images/screen/left_top_2_img.png'), url('@/assets/images/screen/left_center_img.png'), url('@/assets/images/screen/left_bottom_img.png');
  background-position: top center, left center, bottom center;
  background-repeat: no-repeat, no-repeat, no-repeat;
  background-size: 100% 90px, cover, 100% 68px;
  flex: 1;

  .panel-title {
    margin: 4px 20px 0;
    font-size: 0.8rem;
    font-weight: bold;
    color: #fff;
  }

  .tabs {
    display: inline-flex;
    align-items: center;
    column-gap: 8px;
  }

  .tab {
    padding: 2px 10px;
    color: #fff;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.2s ease-in-out;
    user-select: none;
  }

  .tab:hover {
    color: #1afb8f;
  }

  .tab.active {
    color: #1afb8f;
    background: rgb(26 251 143 / 12%);
    border: 1px solid rgb(26 251 143 / 35%);
  }

  .divider {
    margin: 0 2px;
    color: #94a3b8;
  }

  .bottom-card-risk {
    display: flex;
    flex-direction: column;

    .bottom-card-title {
      display: flex;
      margin-top: 5px;
      margin-left: -15%;
      flex-direction: column;
      align-items: center;
    }
  }

  .donut-chart-with-labels {
    width: 30vw;
    height: 30vh;
    margin-left: 2vw;
  }

  .risk-chart {
    width: 30vw;
    height: 30vh;
    margin-left: 2vw;
  }
}

@media (width <=1024px) {

  .left-bottom .donut-chart-with-labels,
  .left-bottom .risk-chart {
    width: 35vw;
    height: 35vh;
  }
}

@media (width <=768px) {
  .left-bottom {
    .tabs .tab {
      padding: 1px 8px;
      font-size: 0.7rem;
    }

    .donut-chart-with-labels,
    .risk-chart {
      width: 40vw;
      height: 40vh;
      margin-left: 1vw;
    }
  }
}

@media (width <=480px) {

  .left-bottom .donut-chart-with-labels,
  .left-bottom .risk-chart {
    width: 45vw;
    height: 45vh;
    margin-left: 0.5vw;
  }
}
</style>
