<script setup lang="ts">
import { onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import inIcon from '@/assets/imgs/空闲.png';
import inIcon2 from '@/assets/imgs/无货.png';
import inIcon3 from '@/assets/imgs/禁用.png';
import inIcon4 from '@/assets/imgs/普通物资.png';
import { fetchGetAllCell, fetchGetAllInv } from '@/service/api/taskmg';

// 缩放和拖拽
const scale = ref(1);
const pan = reactive({ x: 0, y: 0 });
const isPanning = ref(false);
const startPos = reactive({ x: 0, y: 0 });

const gridData = ref<Api.InventoryTask.WhCellList[]>([]);
const showModal = ref(false);
const expandedIndex = ref(-1);

const cellList2 = ref<Api.InventoryTask.WhCell[]>([]);
const cellList3 = ref<Api.Exploitation.Inventory[]>([]);

function toggleRow(index: number) {
  expandedIndex.value = expandedIndex.value === index ? -1 : index;
}
async function generateData() {
  const response = await fetchGetAllCell();
  gridData.value = response.data?.data as Api.InventoryTask.WhCellList[];
}

const hoveredCell = ref<Api.InventoryTask.WhCellList | null>(null);
const hoverPos = reactive({ x: 0, y: 0 });
function onCellMouseEnter(cell: Api.InventoryTask.WhCellList, e: MouseEvent) {
  hoveredCell.value = cell;
  hoverPos.x = e.clientX + 10;
  hoverPos.y = e.clientY + 10;
}
function onCellMouseLeave() {
  hoveredCell.value = null;
}
const getCellDetails = (cellCode: string) => {
  return cellList3.value.filter(item => item.CellNo === cellCode);
};
// 选中
async function onCellClick(cell: Api.InventoryTask.WhCellList) {
  hoveredCell.value = null;
  showModal.value = true;
  cellList2.value = cell.layers;
}
function onWheel(e: WheelEvent) {
  e.preventDefault();
  const delta = e.deltaY < 0 ? 0.1 : -0.1;
  scale.value = Math.min(Math.max(scale.value + delta, 0.5), 3);
}

function onMouseDown(e: MouseEvent) {
  isPanning.value = true;
  startPos.x = e.clientX;
  startPos.y = e.clientY;
}
function onMouseMove(e: MouseEvent) {
  if (!isPanning.value) return;
  const dx = e.clientX - startPos.x;
  const dy = e.clientY - startPos.y;
  pan.x += dx;
  pan.y += dy;
  startPos.x = e.clientX;
  startPos.y = e.clientY;
}
function onMouseUp() {
  isPanning.value = false;
}

async function getInv() {
  const info = await fetchGetAllInv();
  cellList3.value = info.data?.data ?? [];
}

onMounted(() => {
  getInv();
  generateData();
  window.addEventListener('mousemove', onMouseMove);
  window.addEventListener('mouseup', onMouseUp);
});
onBeforeUnmount(() => {
  window.removeEventListener('mousemove', onMouseMove);
  window.removeEventListener('mouseup', onMouseUp);
});
const getCellIcon = (cell: Api.InventoryTask.WhCell) => {
  if (cell.CELL_STATUS === 'Disable') {
    return inIcon3; // 禁用状态优先
  }
  if (cell.CELL_TYPE === 'Special' && cell.HAVE_GOODS) {
    return inIcon4; // 特殊货位 + 有货
  }
  if (cell.HAVE_GOODS) {
    return inIcon; // 普通有货
  }
  return inIcon2; // 默认空闲
};
// 👇 监听 showModal 变化，重置折叠状态
watch(showModal, val => {
  if (val) {
    expandedIndex.value = -1;
  }
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard>
      <div class="legend-container">
        <div class="legend-item">
          <NAvatar :src="inIcon2" />
          <span>货位空闲</span>
        </div>
        <div class="legend-item">
          <NAvatar :src="inIcon" />
          <span>货位有货</span>
        </div>
        <div class="legend-item">
          <NAvatar :src="inIcon3" />
          <span>货位禁用</span>
        </div>
        <div class="legend-item">
          <NAvatar :src="inIcon4" />
          <span>普通物资</span>
        </div>
      </div>
    </NCard>

    <div class="inventory-view">
      <div class="canvas-container" @wheel="onWheel" @mousedown="onMouseDown">
        <div
          class="grid-wrapper"
          :style="{ transform: `translate(-50%, -50%) translate(${pan.x}px, ${pan.y}px) scale(${scale})` }"
        >
          <NAvatar
            v-for="cell in gridData"
            :key="`${cell.row}-${cell.col}`"
            class="grid-cell"
            :src="cell.layers?.some(l => l.HAVE_GOODS) ? inIcon : inIcon2"
            @click="onCellClick(cell)"
            @mouseenter="e => onCellMouseEnter(cell, e)"
            @mouseleave="onCellMouseLeave"
          />
        </div>
      </div>
      <div v-if="hoveredCell" class="tooltip" :style="{ top: hoverPos.y + 'px', left: hoverPos.x + 'px' }">
        <ul>
          <li v-for="layer in hoveredCell.layers" :key="layer.CELL_ID" class="tooltip-item">
            <div class="status-dot" :class="layer.HAVE_GOODS ? 'dot-filled' : 'dot-empty'"></div>
            <span>[{{ layer.CELL_NAME }}]&nbsp;&nbsp;{{ layer.HAVE_GOODS ? '有货' : '空闲' }}</span>
          </li>
        </ul>
      </div>
    </div>
    <NModal v-model:show="showModal">
      <NCard class="showModal" title="货位信息" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <div v-for="(cell, index) in cellList2" :key="index" class="cell-wrapper">
          <div class="cell-row" @click="cell.HAVE_GOODS && toggleRow(index)">
            <NAvatar :src="getCellIcon(cell)" />
            <span class="cell-code">{{ cell.CELL_NAME }}</span>
            <span class="cell-status2">
              货位状态：
              <span :class="cell.CELL_STATUS === 'Enable' ? 'status-green' : 'status-red'">
                {{ cell.CELL_STATUS === 'Enable' ? '正常' : '禁用' }}
              </span>
            </span>

            <span class="cell-status2">
              货位运行状态：
              <span :class="cell.RUN_STATUS === 'Enable' ? 'status-green' : 'status-orange'">
                {{ cell.RUN_STATUS === 'Enable' ? '空闲' : '运行' }}
              </span>
            </span>
            <span class="cell-status">{{ cell.HAVE_GOODS ? '有货' : '无货' }}</span>
            <div class="expand-arrow">
              <span v-if="cell.HAVE_GOODS">{{ expandedIndex === index ? '▲' : '▼' }}</span>
            </div>
          </div>
          <div v-if="expandedIndex === index" class="cell-detail">
            <p v-for="item in getCellDetails(cell.CELL_CODE)" :key="item.CellNo">
              RFID编号：{{ item.RFID }} &nbsp;&nbsp;物资类型：{{ item.MaterialType }} &nbsp;&nbsp;物资名称：{{
                item.MaterialName
              }}
              &nbsp;&nbsp;数量：{{ item.OrderQuantity }}
            </p>
          </div>
        </div>
      </NCard>
    </NModal>
  </div>
</template>

<style scoped>
.showModal {
  width: 60vw;
}
.inventory-view {
  position: relative;
  width: 100%;
  height: 100%;
}
.canvas-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  cursor: grab;
}
.canvas-container:active {
  cursor: grabbing;
}
.grid-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  display: grid;
  grid-template-columns: repeat(20, 70px);
  grid-template-rows: repeat(4, 60px);
  gap: 30px 10px; /* 15px 行间距，10px 列间距 */
  transform-origin: center center;
}
.grid-cell {
  width: 70px;
  height: 70px;
  background-color: #91caff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  user-select: none;
  font-size: 14px;
}
.tooltip {
  position: fixed;
  background: rgba(255, 255, 255, 0.95);
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  pointer-events: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  max-width: 240px;
}

.tooltip ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.tooltip-item {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 6px;
  padding: 6px 10px;
  margin-bottom: 8px;
  font-size: 14px;
}

.tooltip-item:last-child {
  margin-bottom: 0;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 8px;
  flex-shrink: 0;
}

.dot-filled {
  background-color: #28a745; /* 绿色表示有货 */
}

.dot-empty {
  background-color: #aaa; /* 灰色表示空闲 */
}
.legend-container {
  display: flex;
  flex-wrap: nowrap; /* 所有项目在一行展示，不换行 */
  align-items: center; /* 垂直居中 */
  gap: 24px; /* 每组之间的左右间距 */
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px; /* 图标与文字之间的间距 */
  font-size: 14px;
}

.cell-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f9f9f9;
  border-radius: 6px;
  margin-bottom: 12px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s;
}

.cell-row:hover {
  background: #f0f0f0;
}

.cell-icon {
  width: 20px;
  height: 20px;
  background: #4caf50;
  border-radius: 4px;
  margin-right: 12px;
}

.cell-code {
  flex: 1;
  margin-left: 12px;
}
.cell-status2 {
  text-align: center;
  color: #333;
  margin-right: 25px;
}
.status-green {
  color: green;
}

.status-red {
  color: red;
}

.status-orange {
  color: orange;
}

.cell-status {
  width: 60px;
  text-align: center;
  color: #333;
}

.expand-arrow {
  width: 30px;
  text-align: center;
  font-size: 18px;
  color: #666;
  user-select: none;
}

.cell-detail {
  padding: 8px 20px;
  background: #ffffff;
  /* margin: 0 0 15px 0; */
  border-left: 3px solid #4caf50;
  font-size: 13px;
  color: #666;
}
.cell-detail p {
  margin: 15px 0 15px 0;
}
</style>
