<template>
  <div class="dimension-item">
    <h4 class="detection-title">房住得安全</h4>

    <!-- 第一行：统计数字 -->
    <div class="stats-row">
      <div class="stat-item">
        <div class="stat-value">
          <NumberAnimation
            :value="houseSafetyStats.fireMonitors"
            unit="个"
            :unit-style="{ fontSize: '30px' }"
          />
        </div>
        <div class="stat-label">消防监控</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">
          <NumberAnimation
            :value="houseSafetyStats.fireMonitorCoverage"
            :decimals="1"
            unit="%"
            :unit-style="{ fontSize: '30px' }"
          />
        </div>
        <div class="stat-label">消防监控覆盖率</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">
          <NumberAnimation
            :value="houseSafetyStats.fireFacilityOnlineRate"
            :decimals="1"
            unit="%"
            :unit-style="{ fontSize: '30px' }"
          />
        </div>
        <div class="stat-label">消防设施在线率</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">
          <NumberAnimation
            :value="houseSafetyStats.continuousMonitoring"
            unit="天"
            :unit-style="{ fontSize: '30px' }"
          />
        </div>
        <div class="stat-label">持续监控</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">
          <NumberAnimation
            :value="houseSafetyStats.houseSafetyCompliance"
            :decimals="1"
            unit="%"
            :unit-style="{ fontSize: '30px' }"
          />
        </div>
        <div class="stat-label">房屋安全合规率</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">
          <NumberAnimation
            :value="houseSafetyStats.dutyCompliance"
            :decimals="1"
            unit="%"
            :unit-style="{ fontSize: '30px' }"
          />
        </div>
        <div class="stat-label">24小时值班达标率</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">
          <NumberAnimation
            :value="houseSafetyStats.hiddenDangersFound"
            unit="处"
            :unit-style="{ fontSize: '30px' }"
          />
        </div>
        <div class="stat-label">隐患发现</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">
          <NumberAnimation
            :value="houseSafetyStats.rectificationRate"
            unit="%"
            :unit-style="{ fontSize: '30px' }"
          />
        </div>
        <div class="stat-label">安全隐患整改率</div>
      </div>
    </div>

    <!-- 第二行：图表和安全隐患展示 -->
    <div class="charts-section">
      <div class="chart-item fire-safety-issue-chart">
        <div class="chart-title">消防安全问题类型分布</div>
        <div id="fireSafetyIssueChart" class="chart-container"></div>
      </div>
      <div class="chart-item safety-trend-chart">
        <div class="chart-title">安全隐患趋势</div>
        <div id="safetyTrendChart" class="chart-container"></div>
      </div>
      <div class="chart-item duty-status-chart">
        <div class="chart-title">24小时值班达成率情况</div>
        <div id="dutyStatusChart" class="chart-container"></div>
      </div>
      <div class="chart-item safety-hazard-display">
        <div class="chart-title">安全隐患</div>
        <div class="safety-hazard-images-grid">
          <div class="safety-hazard-image-item" v-for="i in 4" :key="i">
            <div class="safety-hazard-image-placeholder"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 第三行：智能巡检情况和问题数据 -->
    <div class="menu-container">
      <!-- 智能巡检情况表格 -->
      <div class="table-section">
        <div class="table-title">智能巡检情况：</div>
        <DataTable
          :columns="smartInspectionTableColumns"
          :data="smartInspectionTableData"
          :border="true"
          :large-font="true"
        />
      </div>

      <!-- 机器人和问题数据部分 -->
      <div class="robot-section">
        <!-- 机器人 -->
        <div class="robot-items">
          <div class="robot-item">
            <el-image
              :src="robotSafetyInspector"
              :alt="'AI安全巡查员'"
              class="robot-image"
            ></el-image>
            <div class="robot-name">AI安全巡查员</div>
          </div>
          <div class="robot-item">
            <el-image
              :src="robotWarningSupervisor"
              :alt="'AI预警与督办员'"
              class="robot-image"
            ></el-image>
            <div class="robot-name">AI预警与督办员</div>
          </div>
        </div>

        <!-- 数据统计 -->
        <div class="data-stats">
          <div class="stat-item">
            <img src="../assets/icons/icon-checked.png" alt="已审核" class="stat-icon" />
            <span>
              实时监控点位{{ houseSafetyStatistics.realTimeMonitoringPoints }}个，已巡检{{
                houseSafetyStatistics.inspectionTimes
              }}次，分析监控视频{{ houseSafetyStatistics.videoAnalysisMinutes }}分钟；
            </span>
          </div>
          <div class="stat-item">
            <img src="../assets/icons/icon-checkedRate.png" alt="审核通过率" class="stat-icon" />
            <span>
              实时识别异常墙皮脱落{{
                houseSafetyStatistics.abnormalBehaviorsDetected
              }}处、通道杂物占用{{ houseSafetyStatistics.blockedCorridors }}处、值班脱岗{{
                houseSafetyStatistics.monitoringIssues
              }}起，覆盖在院老人{{ houseSafetyStatistics.affectedSeniors }}人，涉及房间{{
                houseSafetyStatistics.affectedRooms
              }}间；
            </span>
          </div>
          <div class="stat-item">
            <img src="../assets/icons/icon-checking.png" alt="待审核" class="stat-icon" />
            <span>
              待处置预警{{ houseSafetyStatistics.pendingAlerts }}条，直接反馈{{
                houseSafetyStatistics.directFeedback
              }}条，发布廉政令要求整改{{
                houseSafetyStatistics.rectificationRequirements
              }}条，整改完成率{{ houseSafetyStatistics.rectificationRate }}%。
            </span>
          </div>
        </div>
      </div>

      <!-- 问题数据表格 -->
      <div class="table-section" style="margin-top: 30px">
        <DataTable
          :columns="houseSafetyProblemTableColumns"
          :data="houseSafetyProblemTableData"
          :border="true"
          :large-font="true"
        >
          <template #riskLevel="{ row }">
            <div class="risk-icon" :class="row.riskLevel"></div>
          </template>

          <template #operation="{ row }">
            <i v-if="row.status === '未处置'" class="iconfont icon-command"></i>
            <el-link
              v-else-if="row.status === '处置中'"
              type="primary"
              underline="always"
              class="operation-link"
            >
              催促
            </el-link>
            <el-link v-else type="primary" underline="always" class="operation-link">
              查看详情
            </el-link>
          </template>
        </DataTable>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import NumberAnimation from './NumberAnimation.vue'
import DataTable from './DataTable.vue'
import * as echarts from 'echarts'
import { institutionDetailData } from '../data/institutionDetail'

import robotSafetyInspector from '@/assets/images/robot_safetyInspector.png'
import robotWarningSupervisor from '@/assets/images/robot_warningSupervisor.png'

interface Props {
  visible?: boolean
}

const props = defineProps<Props>()

const houseSafetyStats = institutionDetailData.houseSafetyStats
const houseSafetyProblemTableColumns = institutionDetailData.houseSafetyProblemTableColumns
const houseSafetyProblemTableData = institutionDetailData.houseSafetyProblemTableData
const smartInspectionTableColumns = institutionDetailData.smartInspectionTableColumns
const smartInspectionTableData = institutionDetailData.smartInspectionTableData
const houseSafetyStatistics = institutionDetailData.houseSafetyStatistics

const initCharts = () => {
  // 消防安全问题类型分布图表
  const fireSafetyIssueDom = document.getElementById('fireSafetyIssueChart')
  if (!fireSafetyIssueDom) return
  const fireSafetyIssueChart = echarts.init(fireSafetyIssueDom)
  fireSafetyIssueChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },

    series: [
      {
        name: '消防安全问题',
        type: 'pie',
        roseType: 'radius',
        radius: ['30%', '80%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderWidth: 0,
        },
        label: {
          position: 'outside',
          formatter: '{b}',
          fontSize: 22,
          distance: 50,
          color: '#06BBAD',
        },
        labelLine: {
          show: true,
          length: 20,
          length2: 10,
          lineStyle: {
            width: 2,
            color: '#00FFE6',
          },
        },
        data: institutionDetailData.fireSafetyIssueTypeData,
        color: ['#00FFE6', '#1E90FF', '#FFD700', '#FF8C00', '#FF6347'],
      },
      {
        name: '中心圆环',
        type: 'pie',
        radius: ['30%', '38%'],
        center: ['50%', '50%'],
        itemStyle: {
          color: 'rgba(0, 0, 0, 0.3)',
        },
        data: [{ value: 1, name: '' }],
        label: {
          show: false,
        },
        labelLine: {
          show: false,
        },
        tooltip: {
          show: false,
        },
        emphasis: {
          disabled: true,
        },
      },
    ],
  })

  // 安全隐患趋势图表
  const safetyTrendDom = document.getElementById('safetyTrendChart')
  if (!safetyTrendDom) return
  const safetyTrendChart = echarts.init(safetyTrendDom)
  safetyTrendChart.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: '{a} <br/>{b}: {c}',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: institutionDetailData.safetyTrendData.months,
      boundaryGap: true,
      axisLine: {
        lineStyle: {
          color: '#066462',
        },
      },
      axisLabel: {
        color: '#4E9A96',
        fontSize: 22,
        margin: 16,
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#00FFE6',
        },
      },
      axisLabel: {
        color: '#4E9A96',
        fontSize: 22,
        margin: 16,
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: 'rgba(0, 255, 230, 0.1)',
        },
      },
    },
    series: [
      {
        name: '安全隐患',
        type: 'line',
        data: institutionDetailData.safetyTrendData.values,
        smooth: true,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#00FFE6' },
            { offset: 1, color: '#1E90FF' },
          ]),
          borderColor: 'rgba(0, 209, 189, 0.30)',
          borderWidth: 6,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 255, 230, 0.3)' },
            { offset: 1, color: 'rgba(30, 144, 255, 0.1)' },
          ]),
        },
        lineStyle: {
          width: 4,
        },
        symbol: 'circle',
        symbolSize: 20,
      },
    ],
  })

  // 24小时值班达成率情况图表 - 使用自定义图形实现伪3D效果
  const dutyStatusDom = document.getElementById('dutyStatusChart')
  if (!dutyStatusDom) return
  const dutyStatusChart = echarts.init(dutyStatusDom)

  // 定义偏移量
  const offsetX = 18
  const offsetY = 10

  // 绘制左侧面
  const CubeLeft = echarts.graphic.extendShape({
    shape: {
      x: 0,
      y: 0,
    },
    buildPath: function (ctx: any, shape: any) {
      const xAxisPoint = shape.xAxisPoint
      const c0 = [shape.x, shape.y]
      const c1 = [shape.x - offsetX, shape.y - offsetY]
      const c2 = [xAxisPoint[0] - offsetX, xAxisPoint[1] - offsetY]
      const c3 = [xAxisPoint[0], xAxisPoint[1]]
      ctx
        .moveTo(c0[0], c0[1])
        .lineTo(c1[0], c1[1])
        .lineTo(c2[0], c2[1])
        .lineTo(c3[0], c3[1])
        .closePath()
    },
  })

  // 绘制右侧面
  const CubeRight = echarts.graphic.extendShape({
    shape: {
      x: 0,
      y: 0,
    },
    buildPath: function (ctx: any, shape: any) {
      const xAxisPoint = shape.xAxisPoint
      const c1 = [shape.x, shape.y]
      const c2 = [xAxisPoint[0], xAxisPoint[1]]
      const c3 = [xAxisPoint[0] + offsetX, xAxisPoint[1] - offsetY]
      const c4 = [shape.x + offsetX, shape.y - offsetY]
      ctx
        .moveTo(c1[0], c1[1])
        .lineTo(c2[0], c2[1])
        .lineTo(c3[0], c3[1])
        .lineTo(c4[0], c4[1])
        .closePath()
    },
  })

  // 绘制顶面
  const CubeTop = echarts.graphic.extendShape({
    shape: {
      x: 0,
      y: 0,
    },
    buildPath: function (ctx: any, shape: any) {
      const c1 = [shape.x, shape.y]
      const c2 = [shape.x + offsetX, shape.y - offsetY]
      const c3 = [shape.x, shape.y - offsetY * 2]
      const c4 = [shape.x - offsetX, shape.y - offsetY]
      ctx
        .moveTo(c1[0], c1[1])
        .lineTo(c2[0], c2[1])
        .lineTo(c3[0], c3[1])
        .lineTo(c4[0], c4[1])
        .closePath()
    },
  })

  // 注册三个面图形
  echarts.graphic.registerShape('CubeLeft', CubeLeft)
  echarts.graphic.registerShape('CubeRight', CubeRight)
  echarts.graphic.registerShape('CubeTop', CubeTop)

  dutyStatusChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter: function (params: any) {
        const data = params[0]
        const month = institutionDetailData.dutyStatusData.months[data.data[0]]
        const value = data.data[1]
        return `${month}: ${value}%`
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: institutionDetailData.dutyStatusData.months,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#066462',
        },
      },
      axisLabel: {
        color: '#4E9A96',
        fontSize: 22,
        textStyle: {
          color: '#4E9A96',
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      name: '达成率(%)',
      nameGap: 26,
      nameTextStyle: {
        color: '#4E9A96',
        fontSize: 22,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#00FFE6',
        },
      },
      axisLabel: {
        color: '#4E9A96',
        fontSize: 22,
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(0, 255, 230, 0.1)',
          type: 'dashed',
        },
      },
    },
    series: [
      {
        type: 'custom',
        yAxisIndex: 0,
        renderItem: function (_: any, api: any) {
          const location = api.coord([api.value(0), api.value(1)])
          return {
            type: 'group',
            children: [
              {
                type: 'CubeLeft',
                shape: {
                  api,
                  xValue: api.value(0),
                  yValue: api.value(1),
                  x: location[0],
                  y: location[1],
                  xAxisPoint: api.coord([api.value(0), 0]),
                },
                style: {
                  fill: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#008080' },
                    { offset: 1, color: '#004d4d' },
                  ]),
                },
              },
              {
                type: 'CubeRight',
                shape: {
                  api,
                  xValue: api.value(0),
                  yValue: api.value(1),
                  x: location[0],
                  y: location[1],
                  xAxisPoint: api.coord([api.value(0), 0]),
                },
                style: {
                  fill: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#00FFE6' },
                    { offset: 1, color: '#009999' },
                  ]),
                },
              },
              {
                type: 'CubeTop',
                shape: {
                  api,
                  xValue: api.value(0),
                  yValue: api.value(1),
                  x: location[0],
                  y: location[1],
                },
                style: {
                  fill: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    { offset: 0, color: '#00CCCC' },
                    { offset: 1, color: '#00FFE6' },
                  ]),
                },
              },
            ],
          }
        },
        data: institutionDetailData.dutyStatusData.values.map((value: number, index: number) => [
          index,
          value,
        ]),
      },
    ],
  })

  window.addEventListener('resize', () => {
    fireSafetyIssueChart.resize()
    safetyTrendChart.resize()
    dutyStatusChart.resize()
  })
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style lang="scss" scoped>
$neon-cyan: #00ffe6;

.dimension-item {
  padding: 0 20px;
  border: 1px solid $neon-cyan;
  border-left-color: #086f6a;
  border-right-color: #086f6a;

  .detection-title {
    width: calc(100% + 40px);
    margin-left: -20px;
    font-size: 32px;
    font-weight: 500;
    color: $neon-cyan;
    line-height: 72px;
    letter-spacing: 1px;
    text-align: center;
    background: linear-gradient(to right, rgba(0, 255, 230, 0.1) 0%, rgba(255, 255, 255, 0) 180%);
  }
}

.stats-row {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 90%;
  margin: 60px auto 100px;

  .stat-item {
    position: relative;
    width: calc(100% / 8);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;

    &:not(:last-child) {
      padding-right: 38px;
    }

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      right: 0;
      top: 0;
      height: 100%;
      width: 2px;
      margin: 0 18px;
      background: url('@/assets/images/vertical_line.png') center no-repeat;
      background-size: 100% 100%;
    }

    .stat-value {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 48px;
      font-weight: 500;
      color: $neon-cyan;
      line-height: 56px;
      letter-spacing: 2px;
      margin-bottom: 8px;
    }

    .stat-label {
      font-size: 26px;
      color: rgba(1, 255, 230, 0.7);
      text-align: center;
      white-space: nowrap;
    }
  }
}

.charts-section {
  display: flex;
  gap: 30px;
  margin-bottom: 40px;

  .chart-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 20px;

    .chart-title {
      font-size: 30px;
      color: $neon-cyan;
      margin-bottom: 20px;
      font-weight: 600;
      line-height: 1;
      letter-spacing: 1px;
    }

    .chart-container {
      width: 100%;
      height: 466px;
    }

    .safety-hazard-images-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
      height: 448px;

      .safety-hazard-image-item {
        width: 300px;
        height: 200px;
        background: rgba(0, 255, 230, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.menu-container {
  margin-top: 80px;
  margin-bottom: 30px;
  padding: 36px;

  .table-title {
    font-size: 36px;
    color: $neon-cyan;
    font-weight: 400;
    margin-bottom: 30px;
  }
}

.robot-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 100px;
  width: 80%;
  margin: 60px auto;

  .robot-items {
    display: flex;
    gap: 80px;
  }

  .robot-item {
    text-align: center;

    .robot-image {
      width: auto;
      height: 202px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10px;

      span {
        color: #00ffe6;
        font-size: 20px;
      }
    }

    .robot-name {
      color: #00ffe6;
      font-size: 30px;
    }
  }

  .data-stats {
    flex: 1;
    padding: 36px 60px;
    background: rgba(255, 255, 255, 0.01);
    box-shadow:
      inset 0px -2px 0px 0px rgba(0, 255, 230, 0.5),
      inset 0px 2px 0px 0px rgba(0, 255, 230, 0.5),
      inset 20px 20px 80px 0px rgba(0, 255, 230, 0.08),
      inset -20px -20px 80px 0px rgba(0, 255, 230, 0.08);
    border-radius: 20px 20px 20px 20px;
    border: 2px solid rgba(0, 255, 230, 0.3);

    .stat-item {
      display: flex;
      align-items: center;
      margin-bottom: 30px;
      color: #00d6c0;
      font-size: 32px;

      &:last-child {
        margin-bottom: 0;
      }

      .stat-icon {
        width: 76px;
        margin-right: 30px;
      }
    }
  }
}

.table-section {
  font-size: 32px;
  color: $neon-cyan;

  .empty-text {
    color: rgba(0, 255, 230, 0.7);
    padding: 0 20px 30px;
    text-align: center;
  }

  .icon-command {
    font-size: 50px;
    color: #cf311d;
    cursor: pointer;
  }

  .operation-link {
    font-weight: 400;
    font-size: 32px;
    color: #0099ff;
    letter-spacing: 1px;
  }
}

.risk-icon {
  width: 38px;
  height: 34px;
  margin: 0 auto;
  background-size: auto;
  background-repeat: no-repeat;
  background-position: center;
}

.risk-icon.high {
  background-image: url('@/assets/icons/icon-warning-red.png');
}

.risk-icon.medium {
  background-image: url('@/assets/icons/icon-warning-orange.png');
}

.risk-icon.low {
  background-image: url('@/assets/icons/icon-warning-orange.png');
}
</style>
