<template>
  <div class="screen-root" ref="screen" @click="handleScreenClick">
    <div class="screen-wrapper">
      <Header @change="handleMonthChange"/>

      <!-- 顶部整行：计划完成情况 -->
      <div class="top-row">
        <!-- 左：总体态势 -->
        <div class="plan-overview">
          <div class="rate">
            <div class="num">{{ planOverview.rate }}%</div>
            <div class="label">计划完成率</div>
          </div>

          <div class="summary">
            <div class="item danger">
              <span class="label">异常计划 </span>
              <span class="value">{{ planOverview.abnormalCount }}</span>
            </div>
            <div class="item">
              <span class="label">计划总数 </span>
              <span class="value">{{ planOverview.planTotal }}</span>
            </div>
            <div class="item success">
              <span class="label">已完成 </span>
              <span class="value">{{ planOverview.execTotal }}</span>
            </div>
          </div>
        </div>

        <!-- 右：RepairPlanChart（缩小） -->
        <div class="plan-list">
          <RepairPlanChart :data="data.repairPlan" />
        </div>
      </div>

      <!-- 底部区域 -->
      <div class="bottom-grid">

        <!-- 第一行左：送检工具 -->
        <div class="cell tool-check" :class="{ 'danger-card': isToolCheckDanger }">
          <ToolCheckWarning :list="toolCheckList" />
        </div>

        <!-- 第一行右：右侧组合区 -->
        <div class="right-grid">
          <!-- 工具 TOP -->
          <div class="cell screen-card tool">
            <RankBar title="工具借用 TOP10" :data="data.toolTop" />
          </div>

          <!-- 员工工单完成排行（贯穿两行） -->
          <div class="cell screen-card staff">
            <RankBar title="员工工单完成排行" :data="data.staffWorkOrderRank" :nameWidth="90"/>
          </div>

          <!-- 物料 TOP -->
          <div class="cell screen-card material">
            <RankBar title="物料消耗 TOP10" :data="data.materialTop" />
          </div>
        </div>

        <!-- 第二行左：工单统计 -->
        <div class="cell screen-card" :class="{ 'danger-card': isWorkOrderDanger }">
          <WorkOrderPanel :data="data.workOrder" />
        </div>

        <!-- 第二行中：设备故障 -->
        <div class="cell screen-card device-heatmap" :class="{ 'danger-card': isDeviceFaultDanger }">
          <DeviceFaultHeatmap :data="data.deviceFaultStats" />
          <!--          <DeviceRiskRadar :data="data.deviceFaultStats"/>-->
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import Header from './components/Header'
import RepairPlanChart from './components/RepairPlanChart'
import WorkOrderPanel from './components/WorkOrderPanel'
import RankBar from './components/RankBar'
import ToolCheckWarning from './components/ToolCheckWarning'
import { getDashboardData, getToolCheckList } from './api/screen'
import DeviceFaultHeatmap from './components/DeviceFaultHeatmap.vue'

export default {
  components: {
    Header,
    RepairPlanChart,
    WorkOrderPanel,
    RankBar,
    DeviceFaultHeatmap,
    ToolCheckWarning
  },
  data() {
    return {
      data: {
        repairPlan: [],
        toolTop: [],
        staffWorkOrderRank: [],
        materialTop: [],
        workOrder: {},
        deviceFaultStats: []
      },
      toolCheckList: [],
      overdueList: [],
      warningList: [],
      fullscreenEntered: false,
      currentMonth: null,
    }
  },
  mounted() {
    this.resize()
    window.addEventListener('resize', this.resize)
    this.loadData()
    this.timer = setInterval(this.loadData, 60000)
    document.addEventListener('fullscreenchange', this.onFullscreenChange)
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    window.removeEventListener('resize', this.resize)
    document.removeEventListener('fullscreenchange', this.onFullscreenChange)
  },
  computed: {
    planOverview() {
      const list = this.data.repairPlan || []

      const planTotal = list.reduce((sum, i) => sum + (i.planCount || 0), 0)
      const execTotal = list.reduce((sum, i) => sum + (i.execCount || 0), 0)

      const abnormalCount = list.filter(
        i => (i.execCount || 0) < (i.planCount || 0)
      ).length

      return {
        planTotal,
        execTotal,
        abnormalCount,
        rate: planTotal
          ? Math.round((execTotal / planTotal) * 100)
          : 0
      }
    },
    isToolCheckDanger() {
      return this.overdueList.length > 0
    },
    isWorkOrderDanger() {
      const wo = this.data.workOrder || {}
      return (wo.todoNum || 0) > 0 || (wo.processing || 0) > 0
    },
    isDeviceFaultDanger() {
      const list = this.data.deviceFaultStats || []
      return list.some(item => (item.unfinishedCount || 0) > 0)
    }
  },
  methods: {
    resize: _.throttle(function () {
      const scaleX = window.innerWidth / 1920
      const scaleY = window.innerHeight / 1080
      const scale = Math.min(scaleX, scaleY)
      this.$refs.screen.style.transform = `scale(${scale})`
      this.$refs.screen.style.transformOrigin = 'left top'
    }, 200),
    handleMonthChange(month) {
      this.currentMonth = month
      this.loadData()
    },
    loadData() {
      getDashboardData({ month: this.currentMonth }).then(res => {
        const r = res.result || {}
        this.data.repairPlan = r.repairPlan || []
        this.data.toolTop = r.toolTop || []
        this.data.staffWorkOrderRank = r.staffWorkOrderRank || []
        this.data.materialTop = r.materialTop || []
        this.data.workOrder = r.workOrder || {}
        this.data.deviceFaultStats = r.deviceFaultStats || []
      })
      getToolCheckList().then(res => {
        const data = res.result || {}
        this.overdueList = data.overdue || []
        this.warningList = data.warning || []

        // 合并列表（超期排前面）
        this.toolCheckList = [
          ...this.overdueList.map(i => ({ ...i, level: 'danger' })),
          ...this.warningList.map(i => ({ ...i, level: 'warning' }))
        ]
      })
    },
    handleScreenClick() {
      if (this.fullscreenEntered) return
      const el = this.$el
      el.requestFullscreen && el.requestFullscreen()
      this.fullscreenEntered = true
    },
    onFullscreenChange() {
      this.$nextTick(this.resize)
      if (!document.fullscreenElement) {
        this.fullscreenEntered = false
      }
    }
  }
}
</script>

<style scoped>
.screen-root {
  width: 100vw;
  height: 100vh;
  /* 主背景 */
  background:
    radial-gradient(circle at 50% 20%, rgba(79,210,255,0.08), transparent 45%),
    linear-gradient(180deg, rgba(6,22,38,0.95), rgba(11,40,75,0.95));
  overflow: hidden;
}

.screen-wrapper {
  width: 1920px;
  height: 1080px;
  color: #fff;
  position: relative;

  /* 主背景 */
  background:
    radial-gradient(circle at 50% 20%, rgba(79,210,255,0.08), transparent 45%),
    linear-gradient(180deg, rgba(6,22,38,0.95), rgba(11,40,75,0.95));

  overflow: hidden;
  border-radius: 10px;
}
.screen-wrapper::before {
  content: '';
  position: absolute;
  inset: 0;
  border: 2px solid rgba(79,210,255,0.45);
  border-radius: 10px;
  pointer-events: none;

  box-shadow:
    0 0 40px rgba(79,210,255,0.25),
    inset 0 0 60px rgba(79,210,255,0.15);
}
.screen-wrapper::after {
  content: '';
  position: absolute;
  inset: 0;
  pointer-events: none;

  background:
    /* 左上角 */
    linear-gradient(#00eaff, #00eaff) left 8px top 8px / 40px 2px no-repeat,
    linear-gradient(#00eaff, #00eaff) left 8px top 8px / 2px 40px no-repeat,

      /* 右上角 */
    linear-gradient(#00eaff, #00eaff) right 8px top 8px / 40px 2px no-repeat,
    linear-gradient(#00eaff, #00eaff) right 8px top 8px / 2px 40px no-repeat,

      /* 左下角 */
    linear-gradient(#00eaff, #00eaff) left 8px bottom 8px / 40px 2px no-repeat,
    linear-gradient(#00eaff, #00eaff) left 8px bottom 8px / 2px 40px no-repeat,

      /* 右下角 */
    linear-gradient(#00eaff, #00eaff) right 8px bottom 8px / 40px 2px no-repeat,
    linear-gradient(#00eaff, #00eaff) right 8px bottom 8px / 2px 40px no-repeat;
}

/* 顶部 */
.top-row {
  height: 260px;
  padding: 16px;
  display: grid;
  grid-template-columns: 420px 1fr;
  gap: 20px;
}

/* 左侧主态势 */
.plan-overview {
  background: linear-gradient(180deg, rgba(0,160,255,.25), rgba(0,0,0,.2));
  border: 1px solid rgba(0,160,255,.4);
  border-radius: 10px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 完成率 */
.plan-overview .rate {
  text-align: center;
  margin-bottom: 20px;
}
.plan-overview .rate .num {
  font-size: 52px;
  font-weight: bold;
  color: #00eaff;
  text-shadow: 0 0 12px rgba(0,234,255,.6);
}
.plan-overview .rate .label {
  font-size: 18px;
  color: #9fdfff;
}

/* 指标条 */
.plan-overview .summary {
  display: flex;
  justify-content: space-between;
}
.plan-overview .item {
  text-align: center;
}
.plan-overview .item .label {
  font-size: 16px;
  color: #ccc;
}
.plan-overview .item .value {
  font-size: 22px;
  font-weight: bold;
  color: #fff;
}
.plan-overview .item.danger .value {
  color: #ff5c5c;
}
.plan-overview .item.success .value {
  color: #7CFF00;
}

/* 右侧计划卡片区缩紧 */
.plan-list {
  margin-left: 20px;
  display: flex;
  align-items: stretch;
}

/* 底部整体 */
.bottom-grid {
  height: calc(100% - 260px - 80px);
  display: grid;
  grid-template-columns: 1fr 1fr 2fr;
  grid-template-rows: 1fr 1fr;
  gap: 12px;
  padding: 0 16px 16px;
}

.cell {
  background: rgba(255, 255, 255, 0.03);
  border-radius: 6px;
  padding: 12px;

  min-height: 0; /* ⭐ 关键修复 */
}
.screen-card {
  position: relative;
  background:
    linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02));
  border: 1px solid rgba(79,210,255,0.18);
  border-radius: 10px;
  box-shadow:
    inset 0 0 30px rgba(79,210,255,0.08),
    0 0 40px rgba(0,0,0,0.6);
  overflow: hidden;
}

/* 顶部发光线 */
.screen-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 2px;
  width: 100%;
  background: linear-gradient(90deg, transparent, #00eaff, transparent);
  opacity: 0.8;
}

/* 送检工具 */
.tool-check {
  grid-column: 1 / 3;
  grid-row: 1;
}

/* 右侧组合区 */
.right-grid {
  grid-column: 3 / 4;
  grid-row: 1 / 3;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 12px;

  min-height: 0; /* ⭐ 关键修复 */
}

/* 工具 TOP */
.tool {
  grid-column: 1 / 2;
  grid-row: 1 / 2;
}

/* 物料 TOP */
.material {
  grid-column: 1 / 2;
  grid-row: 2 / 3;
}

/* 员工排行 */
.staff {
  grid-column: 2 / 3;
  grid-row: 1 / 3;
}

.device-heatmap {
  grid-column: 2 / 3;
  grid-row: 2;
}

@keyframes pulse-danger {
  0% { box-shadow: 0 0 0 rgba(255,77,79,0.0); }
  50% { box-shadow: 0 0 30px rgba(255,77,79,0.4); }
  100% { box-shadow: 0 0 0 rgba(255,77,79,0.0); }
}

.danger-card {
  animation: pulse-danger 2.5s infinite;
}

</style>
