<template>
  <div class="opLoginOverlayRoot">
    <div v-if="isInShowWindow && hasOffline" class="opLoginOverlay">
      <div class="opLoginPanel">
        <div class="panelTitle">工位实时登录状态</div>
        <div class="panelSubTitle">
          <span class="summaryLabel">产品型号：</span>
          <span class="summaryValue modelValue">{{ displayModelName }}</span>
          <span class="summarySplit">｜</span>
          <span class="summaryLabel">总工位：</span>
          <span class="summaryValue totalValue">{{ totalCount }}</span>
          <span class="summarySplit">｜</span>
          <span class="summaryLabel">已登录：</span>
          <span class="summaryValue onlineValue">{{ onlineCount }}</span>
          <span class="summarySplit">｜</span>
          <span class="summaryLabel">未登录：</span>
          <span class="summaryValue offlineValue">{{ offlineCount }}</span>
        </div>
        <div class="stationGrid">
          <div
            v-for="item in stationRows"
            :key="item.工位号"
            :class="['stationItem', item.登录状态值 === 1 ? 'online' : 'offline']">
            <div class="stationNo">{{ item.工位号 }}</div>
            <div class="stationName">{{ item.工位名称 || '--' }}</div>
            <div :class="['stationStatus', item.登录状态值 === 1 ? 'statusOnline' : 'statusOffline']">
              {{ displayStationStatus(item) }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else-if="isInShowWindow && totalCount > 0 && allLoggedIn" class="readyText">工位已登录就绪</div>
  </div>
</template>

<script>
export default {
  name: 'OpLoginStatusOverlay',
  props: {
    currentTimeTick: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      opLoginBoxShowStartTime: '',
      opLoginBoxShowEndTime: '',
      currentProductModel: '',
      modelNameMap: {},
      stationRows: [],
      refreshTimer: null,
      configTimer: null,
      refreshing: false
    }
  },
  computed: {
    totalCount() {
      return this.stationRows.length
    },
    onlineCount() {
      let count = 0
      for (let i = 0; i < this.stationRows.length; i++) {
        if (Number(this.stationRows[i].登录状态值) === 1) {
          count++
        }
      }
      return count
    },
    offlineCount() {
      return this.totalCount - this.onlineCount
    },
    hasOffline() {
      return this.offlineCount > 0
    },
    allLoggedIn() {
      return this.totalCount > 0 && this.offlineCount === 0
    },
    displayModelName() {
      if (!this.currentProductModel) {
        return '--'
      }
      return this.modelNameMap[this.currentProductModel] || this.currentProductModel
    },
    isInShowWindow() {
      const start = this.parseTimeToSeconds(this.opLoginBoxShowStartTime)
      const end = this.parseTimeToSeconds(this.opLoginBoxShowEndTime)
      if (start === null || end === null || !this.currentTimeTick) {
        return false
      }
      const now = new Date(this.currentTimeTick)
      const nowSec = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds()
      if (start <= end) {
        return nowSec >= start && nowSec <= end
      }
      return nowSec >= start || nowSec <= end
    }
  },
  mounted() {
    this.loadProductTypeMap().finally(() => {
      this.loadOverlayTimeWindow().finally(() => {
        this.refreshStatus()
      })
    })
    this.refreshTimer = setInterval(() => {
      this.refreshStatus()
    }, 5000)
    this.configTimer = setInterval(() => {
      this.loadOverlayTimeWindow()
    }, 2 * 60 * 1000)
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
      this.refreshTimer = null
    }
    if (this.configTimer) {
      clearInterval(this.configTimer)
      this.configTimer = null
    }
  },
  methods: {
    displayStationStatus(item) {
      if (Number(item.登录状态值) !== 1) {
        return '未登录'
      }
      const loginUser = item.姓名 === null || item.姓名 === undefined
        ? ''
        : String(item.姓名).trim()
      const operatorNo = item.操作者工号 === null || item.操作者工号 === undefined
        ? ''
        : String(item.操作者工号).trim()
      return `${loginUser || operatorNo || '--'} 已登录`
    },
    parseTimeToSeconds(value) {
      if (!value || typeof value !== 'string') {
        return null
      }
      const parts = value.split(':')
      if (parts.length !== 3) {
        return null
      }
      const hour = Number(parts[0])
      const minute = Number(parts[1])
      const second = Number(parts[2])
      if ([hour, minute, second].some(item => Number.isNaN(item))) {
        return null
      }
      return hour * 3600 + minute * 60 + second
    },
    refreshStatus() {
      if (this.refreshing) {
        return
      }
      this.refreshing = true
      const mapTask = Object.keys(this.modelNameMap).length > 0
        ? Promise.resolve()
        : this.loadProductTypeMap()
      mapTask.then(() => {
        return this.loadStationRows()
      }).finally(() => {
        this.refreshing = false
      })
    },
    loadPersistentValue(name) {
      const param = []
      param[0] = ['工位号', 'PLCS']
      param[1] = ['名称', name]
      const data = this.CreateData1('11', 'MES_持久化变量_读取', param)
      return this.ExecDatabase(data).then(res => {
        const row = res.data && res.data.length ? res.data[0] : null
        return row && row.值 ? String(row.值).trim() : ''
      }).catch(() => '')
    },
    loadOverlayTimeWindow() {
      return Promise.all([
        this.loadPersistentValue('看板工位登录状态弹窗开始时间'),
        this.loadPersistentValue('看板工位登录状态弹窗结束时间'),
        this.loadCurrentProductModel()
      ]).then(values => {
        this.opLoginBoxShowStartTime = values[0] || ''
        this.opLoginBoxShowEndTime = values[1] || ''
      })
    },
    loadProductTypeMap() {
      const param = []
      const data = this.CreateData1('11', 'MES_基本变量_机型代码_查询', param)
      return this.ExecDatabase(data).then(res => {
        const rows = res.data || []
        const modelMap = {}
        for (let i = 0; i < rows.length; i++) {
          const flag = rows[i].发动机机型标志 === null || rows[i].发动机机型标志 === undefined
            ? ''
            : String(rows[i].发动机机型标志).trim()
          const name = rows[i].发动机型号 === null || rows[i].发动机型号 === undefined
            ? ''
            : String(rows[i].发动机型号).trim()
          if (flag) {
            modelMap[flag] = name || flag
          }
        }
        this.modelNameMap = modelMap
      }).catch(() => {
        this.modelNameMap = {}
      })
    },
    loadCurrentProductModel() {
      return this.loadPersistentValue('生产产品型号').then(value => {
        this.currentProductModel = value || ''
      }).catch(() => {
        this.currentProductModel = ''
      })
    },
    loadStationRows() {
      const param = []
      param[0] = ['产品型号', this.currentProductModel || '']
      const data = this.CreateData1('11', '测量数据工位_监控系统_操作者工号_视图_查询', param)
      return this.ExecDatabase(data).then(res => {
        const rows = res.data || []
        this.stationRows = rows.map(item => {
          const operatorNo = item.操作者工号 === null || item.操作者工号 === undefined
            ? ''
            : String(item.操作者工号).trim()
          return {
            ...item,
            登录状态值: operatorNo ? 1 : 0
          }
        })
      }).catch(() => {
        this.stationRows = []
      })
    }
  }
}
</script>

<style scoped>
.opLoginOverlayRoot {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 999;
}

.opLoginOverlay {
  position: absolute;
  left: 24px;
  right: 24px;
  top: 92px;
  bottom: 55px;
  border-radius: 16px;
  border: 1px solid #3b6f99;
  background:
    linear-gradient(180deg, rgba(19, 48, 79, 0.97) 0%, rgba(9, 25, 51, 0.97) 100%),
    repeating-linear-gradient(
      -45deg,
      rgba(130, 192, 255, 0.06) 0px,
      rgba(130, 192, 255, 0.06) 8px,
      rgba(10, 24, 49, 0.06) 8px,
      rgba(10, 24, 49, 0.06) 16px
    );
  box-shadow:
    0 0 0 1px rgba(116, 178, 224, 0.22) inset,
    0 18px 42px rgba(0, 0, 0, 0.5),
    0 0 30px rgba(46, 121, 174, 0.22);
  overflow: hidden;
}

.opLoginPanel {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 22px 24px 28px;
}

.opLoginPanel::before,
.opLoginPanel::after {
  content: '';
  position: absolute;
  width: 24px;
  height: 24px;
  border: 2px solid rgba(109, 196, 255, 0.75);
}

.opLoginPanel::before {
  left: 10px;
  top: 10px;
  border-right: none;
  border-bottom: none;
}

.opLoginPanel::after {
  right: 10px;
  bottom: 10px;
  border-left: none;
  border-top: none;
}

.panelTitle {
  color: #e3f7ff;
  font-size: 40px;
  font-weight: 700;
  line-height: 1.2;
  letter-spacing: 2px;
  text-shadow: 0 0 16px rgba(84, 188, 255, 0.35);
}

.panelSubTitle {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 8px;
  margin-bottom: 18px;
  color: #a9d7f3;
  font-size: 25px;
  letter-spacing: 1px;
}

.summaryLabel {
  color: #b4dcf4;
  font-weight: 600;
}

.summarySplit {
  color: rgba(153, 204, 237, 0.8);
  margin: 0 4px;
}

.summaryValue {
  font-size: 38px;
  font-weight: 800;
  line-height: 1;
  letter-spacing: 0.5px;
}

.modelValue {
  color: #ffd76a;
  text-shadow: 0 0 14px rgba(255, 215, 106, 0.45);
}

.totalValue {
  color: #7cd7ff;
  text-shadow: 0 0 14px rgba(124, 215, 255, 0.45);
}

.onlineValue {
  color: #68ff97;
  text-shadow: 0 0 14px rgba(104, 255, 151, 0.45);
}

.offlineValue {
  color: #ff7d7d;
  text-shadow: 0 0 14px rgba(255, 125, 125, 0.5);
}

.stationGrid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 14px;
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  box-sizing: border-box;
  padding: 0 4px 30px 0;
}

.stationItem {
  border-radius: 12px;
  border: 1px solid transparent;
  padding: 12px 14px;
  background: rgba(15, 33, 63, 0.55);
  box-shadow: 0 0 0 1px rgba(133, 188, 229, 0.12) inset;
}

.stationItem.online {
  background: linear-gradient(180deg, rgba(28, 91, 60, 0.62) 0%, rgba(18, 52, 38, 0.62) 100%);
  border-color: rgba(83, 201, 126, 0.62);
}

.stationItem.offline {
  background: linear-gradient(180deg, rgba(126, 32, 32, 0.7) 0%, rgba(74, 18, 18, 0.7) 100%);
  border-color: rgba(255, 126, 126, 0.75);
  animation: offlinePulse 1.8s infinite;
}

.stationNo {
  color: #ffffff;
  font-size: 30px;
  font-weight: 700;
  letter-spacing: 1px;
}

.stationName,
.stationStatus {
  margin-top: 6px;
  font-size: 24px;
  color: #dbefff;
}

.statusOnline {
  color: #98f0b5;
}

.statusOffline {
  color: #ffd2d2;
  font-weight: 700;
}

.readyText {
  position: absolute;
  right: 30px;
  bottom: 18px;
  padding: 8px 16px;
  border-radius: 8px;
  border: 1px solid rgba(75, 201, 122, 0.55);
  background: rgba(8, 40, 20, 0.55);
  color: #68ff97;
  font-size: 46px;
  font-weight: 700;
  letter-spacing: 2px;
  text-shadow: 0 0 14px rgba(43, 202, 9, 0.65);
}

@keyframes offlinePulse {
  0% {
    box-shadow: 0 0 0 1px rgba(255, 145, 145, 0.22) inset;
  }
  50% {
    box-shadow: 0 0 0 1px rgba(255, 145, 145, 0.6) inset, 0 0 16px rgba(212, 67, 67, 0.38);
  }
  100% {
    box-shadow: 0 0 0 1px rgba(255, 145, 145, 0.22) inset;
  }
}
</style>
