<template>
  <div>
    <el-form label-width="80px" :model="formLabelAlign">
      <el-row>
        <!-- 新增查询条件 -->
        <el-col :span="4">
          <el-form-item label="班组:">
            <el-select v-model="formLabelAlign.teamName" filterable placeholder="请选择">
              <el-option
                v-for="(item, index) in selectTeamOptions"
                :label="item"
                :value="item"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="设备:">
            <el-select v-model="formLabelAlign.equipName" filterable placeholder="请选择">
              <el-option
                v-for="(item, index) in selectEquipOptions"
                :label="item"
                :value="item"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="工序:">
            <el-input v-model="formLabelAlign.processName" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="时间:">
            <el-date-picker
              v-model="formLabelAlign.startTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <div style="float: right">
            <el-button type="primary" icon="el-icon-search" @click="handleSubmit"> 搜索 </el-button>
            <el-button icon="el-icon-delete" @click="handleReset"> 清空 </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <div class="gantt-container">
      <!-- 头部标题和图例 -->
      <div class="gantt-header">
        <div class="status-legend">
          <div class="legend-item">
            <span class="legend-color completed"></span>
            <span>已完成</span>
          </div>
          <div class="legend-item">
            <span class="legend-color processing"></span>
            <span>进行中</span>
          </div>
          <div class="legend-item">
            <span class="legend-color pending"></span>
            <span>未开始</span>
          </div>
        </div>
      </div>

      <!-- 甘特图主体 -->
      <div class="gantt-wrapper">
        <!-- 左侧信息列表 - 展示车间订单号等信息 -->
        <div class="info-list">
          <div class="info-item-title">
            <div class="info-title-cell">车间订单号</div>
            <div class="info-title-cell">零件号</div>
            <div class="info-title-cell">批次号</div>
            <div class="info-title-cell">数量</div>
          </div>
          <div
            v-for="(order, index) in currentPageOrders"
            :key="index"
            :style="{
              height: getRowHeight(order.woCode) + 'px',
              borderBottom: '1px solid #ccc',
              lineHeight:getRowHeight(order.woCode) + 'px',
            }"
          >
            <div class="info-item">
              <div class="info-cell">{{ order.woCode }}</div>
              <div class="info-cell">{{ order.partCode }}</div>
              <div class="info-cell">{{ order.batchNo }}</div>
              <div class="info-cell">{{ order.makeQty }}</div>
            </div>
          </div>
        </div>

        <!-- 右侧时间轴 @wheel.prevent="handleWheel"-->
        <div class="timeline-container" ref="timelineContainer">
          <!-- 图表X轴区域 -->
          <div class="chart-axis">
            <div class="time-labels" :style="{ width: `${timelineWidth}%` }">
              <div
                v-for="(time, index) in majorTickLabels"
                :key="index"
                class="major-label"
                :style="{ left: `${(index / 24) * 100}%` }"
              >
                {{ time }}
              </div>
              <div v-if="zoomLevel >= 2" class="minor-labels">
                <div
                  v-for="(time, index) in minorTickLabels"
                  :key="index"
                  class="minor-label"
                  :style="{ left: `${(index / (24 * 2)) * 100}%` }"
                >
                  {{ time }}
                </div>
              </div>
            </div>
            <div class="tick-lines" :style="{ width: `${timelineWidth}%` }">
              <div
                v-for="(time, index) in majorTickLabels"
                :key="index"
                class="major-tick-line"
                :style="{ left: `${(index / 24) * 100}%` }"
              ></div>
              <div v-if="zoomLevel >= 2" class="minor-tick-lines">
                <div
                  v-for="(time, index) in minorTickLabels"
                  :key="index"
                  class="minor-tick-line"
                  :style="{ left: `${(index / (24 * 2)) * 100}%` }"
                ></div>
              </div>
              <div class="axis-base-line"></div>
              <!-- 当前时间线 -->
              <div class="current-time-line" :style="{ left: `${currentTimePosition}%` }"></div>
            </div>
          </div>

          <!-- 甘特图内容区域 -->
          <div class="chart-content" :style="{ width: `${timelineWidth}%` }">
            <div class="grid-lines">
              <div
                v-for="(time, index) in majorTickLabels"
                :key="index"
                class="grid-line"
                :style="{ left: `${(index / 24) * 100}%` }"
              ></div>
            </div>

            <div class="tasks-container">
              <div
                v-for="(order, index) in currentPageOrders"
                :key="index"
                class="device-task-row"
                :style="{ height: getRowHeight(order.woCode) + 'px' }"
              >
                <template
                  v-for="(layer, layerIndex) in getLayeredTasks(order.woCode)"
                  :key="layerIndex"
                >
                  <div
                    v-for="(task, taskIndex) in layer"
                    :key="taskIndex"
                    class="task-bar"
                    :style="{
                      left: `${getPositionPercent(task.startTime)}%`,
                      width: `${getWidthPercent(task.startTime, task.endTime)}%`,
                      backgroundColor: getStatusColor(task),
                      top: `${getLayerOffset(
                        layerIndex,
                        getLayeredTasks(order.woCode).length,
                        order.woCode
                      )}px`,
                      height: `${getLayerTaskHeight(
                        getLayeredTasks(order.woCode).length,
                        order.woCode
                      )}px`,
                    }"
                    @mouseenter="showTooltip($event, task, order.woCode)"
                    @mouseleave="hideTooltip()"
                  >
                    <span class="task-label">{{ task.processName }}</span>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页控件 sizes  :page-sizes="[10, 20, 50]"-->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="totalOrders"
        ></el-pagination>
      </div>

      <!-- 悬浮提示框 -->
      <div
        v-if="tooltipVisible"
        class="tooltip"
        :style="{
          left: `${tooltipX}px`,
          top: `${tooltipY}px`,
        }"
      >
        <div class="tooltip-content">
          <div class="wo-code-title">{{ tooltipData.woCode }}</div>
          <ul class="detail-list">
            <li class="detail-item">
              <span class="label">工序：</span>
              <span class="value">{{ tooltipData.processName || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">班组：</span>
              <span class="value">{{ tooltipData.teamName || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">设备：</span>
              <span class="value">{{ tooltipData.equipName || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">零件号：</span>
              <span class="value">{{ tooltipData.partCode || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">批次号：</span>
              <span class="value">{{ tooltipData.batchNo || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">数量：</span>
              <span class="value">{{ tooltipData.makeQty || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">计划开始时间：</span>
              <span class="value">{{ tooltipData.planStartTime || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">实际开始时间：</span>
              <span class="value">{{ tooltipData.factStartTime || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">计划完成时间：</span>
              <span class="value">{{ tooltipData.planEndTime || '-' }}</span>
            </li>
             <li class="detail-item">
              <span class="label">实际完成时间：</span>
              <span class="value">{{ tooltipData.factEndTime || '-' }}</span>
            </li>
            <li class="detail-item">
              <span class="label">状态：</span>
              <span class="value">
                <el-tag :type="getStatusTagType(tooltipData)">
                  <i v-if="tooltipData.planStatus == '1'">未开始</i>
                  <i v-if="tooltipData.planStatus == '2'">加工中</i>
                  <i v-if="tooltipData.planStatus == '3'">报工完成</i>
                  <i v-if="tooltipData.planStatus == '5'">已完成</i>
                  <i v-if="tooltipData.planStatus == '6'">已返工</i>
                </el-tag>
              </span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getData, selectEquip, selectTeam } from '@/api/productionSchedulingPlan/scheduling';

export default {
  name: 'GanttChart',
  data() {
    return {
      formLabelAlign: {
        startTime: null, //时间
        teamName: '', //班组
        equipName: '', //设备
        processName: '', //工序
        woCode: '', //车间订单号
      },
      zoomLevel: 3, // 缩放级别 (1-4)
      minZoom: 1,
      maxZoom: 4,

      // 订单列表和任务数据
      allOrders: [], // 所有订单信息
      currentPageOrders: [], // 当前页订单
      taskData: [],
      totalOrders: 0,

      // 分页参数
      currentPage: 1,
      pageSize: 6,

      // 提示框相关
      tooltipVisible: false,
      tooltipData: {},
      tooltipX: 0,
      tooltipY: 0,

      // 样式相关
      baseRowHeight: 36,
      rowHeights: {},
      selectTeamOptions: [],
      selectEquipOptions: [],

      // 当前时间位置
      currentTimePosition: 0,
    };
  },
  computed: {
    timelineWidth() {
      return 100 * this.zoomLevel;
    },
    majorTickLabels() {
      return Array.from({ length: 24 }, (_, i) => `${i}:00`);
    },
    minorTickLabels() {
      const labels = [];
      for (let hour = 0; hour < 24; hour++) {
        labels.push('');
        labels.push(`${hour}:30`);
      }
      return labels;
    },
  },
  mounted() {
    this.formLabelAlign.startTime = new Date().toISOString().substr(0, 10);
    this.getSelectTeam();
    this.getSelectEquip();
    this.getData();
    this.calcCurrentTimePosition();
    // 定时更新当前时间线位置
    setInterval(() => {
      this.calcCurrentTimePosition();
    }, 60000); // 每分钟更新一次
  },
  methods: {
    // 计算当前时间在时间轴上的位置百分比
    calcCurrentTimePosition() {
      const now = new Date();
      const hours = now.getHours();
      const minutes = now.getMinutes();
      const totalMinutes = hours * 60 + minutes;
      this.currentTimePosition = (totalMinutes / (24 * 60)) * 100;

      // 自动滚动到当前时间位置
      this.scrollToCurrentTime();
    },

    // 滚动到当前时间位置
    scrollToCurrentTime() {
      const container = this.$refs.timelineContainer;
      if (container) {
        const scrollPosition =
          (this.currentTimePosition / 100) * container.scrollWidth - container.clientWidth / 2;
        container.scrollLeft = scrollPosition;
      }
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.updateCurrentPageOrders();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.updateCurrentPageOrders();
    },
    updateCurrentPageOrders() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.currentPageOrders = this.allOrders.slice(start, end);
    },

    // 数据获取
    getData() {
      getData(this.formLabelAlign).then(res => {
        this.processData(res.data.data);
      });
    },
    getSelectEquip() {
      selectEquip().then(res => {
        this.selectEquipOptions = res.data.data;
      });
    },
    getSelectTeam() {
      selectTeam().then(res => {
        this.selectTeamOptions = res.data.data;
      });
    },

    // 数据处理
    processData(rawData) {
      const tasks = [];
      const orders = [];
      const workOrders = Object.keys(rawData);

      workOrders.forEach(woCode => {
        const woTasks = rawData[woCode] || [];
        // 提取订单信息（取第一个任务的基础信息）
        if (woTasks.length > 0) {
          const firstTask = woTasks[0];
          orders.push({
            woCode,
            partCode: firstTask.partCode,
            batchNo: firstTask.batchNo,
            makeQty: firstTask.makeQty,
          });
        }
        // 处理任务数据
        woTasks.forEach(task => {
          tasks.push({
            ...task,
            status: this.calcTaskStatus(task.startTime, task.endTime),
          });
        });
      });

      this.allOrders = orders;
      this.totalOrders = orders.length;
      this.taskData = tasks;
      this.updateCurrentPageOrders();
    },

    // 任务状态计算
    calcTaskStatus(startTime, endTime) {
      const now = new Date();
      const current = now.getHours() * 60 + now.getMinutes();
      const start = this.timeToMinutes(startTime);
      let end = this.timeToMinutes(endTime);

      if (end < start) end += 24 * 60;

      if (current >= end) return '已完成';
      else if (current >= start) return '进行中';
      else return '未开始';
    },

    // 事件处理
    handleSubmit() {
      this.getData();
    },
    handleReset() {
      this.formLabelAlign = {
        startTime: new Date().toISOString().substr(0, 10),
        teamName: '',
        equipName: '',
        processName: '',
        woCode: '',
      };
      this.getData();
    },

    // 任务数据过滤
    getDeviceTasks(device) {
      return this.taskData.filter(task => task.woCode === device);
    },

    // 时间转换工具
    timeToMinutes(timeStr) {
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    },

    // 甘特图位置计算
    getPositionPercent(startTime) {
      const totalMinutes = 24 * 60;
      const startMinutes = this.timeToMinutes(startTime);
      return (startMinutes / totalMinutes) * 100;
    },
    getWidthPercent(startTime, endTime) {
      const startMinutes = this.timeToMinutes(startTime);
      let endMinutes = this.timeToMinutes(endTime);
      if (endMinutes < startMinutes) endMinutes += 24 * 60;
      const duration = endMinutes - startMinutes;
      return (duration / (24 * 60)) * 100;
    },

    // 样式计算
    getStatusColor(row) {
      switch (row.planStatus) {
        case '3':
        case '5':
          return '#28a745';
        case '2':
          return '#007bff';
        case '1':
          return '#6c757d';
        case '6':
          return '#dc3545';
        default:
          return '#ccc';
      }
    },
    getStatusTagType(row) {
      switch (row.planStatus) {
        case '3':
        case '5':
          return 'success';
        case '2':
          return 'primary';
        case '1':
          return 'info';
        case '6':
          return 'danger';
        default:
          return 'default';
      }
    },

    // 缩放控制
    handleWheel(e) {
      if (e.deltaY < 0 && this.zoomLevel < this.maxZoom) {
        this.zoomLevel += 0.5;
      } else if (e.deltaY > 0 && this.zoomLevel > this.minZoom) {
        this.zoomLevel -= 0.5;
      }
    },

    // 提示框控制
    showTooltip(e, task, device) {
      this.tooltipData = { ...task, device };
      this.tooltipVisible = true;

      this.$nextTick(() => {
        const tooltipEl = document.querySelector('.tooltip');
        if (!tooltipEl) return;

        const tooltipWidth = tooltipEl.offsetWidth;
        const tooltipHeight = tooltipEl.offsetHeight;
        const padding = 5;
        let x = e.pageX + 8;
        let y = e.pageY + 8;

        if (x + tooltipWidth > document.documentElement.clientWidth) {
          x = e.pageX - tooltipWidth - 8;
        }
        if (y + tooltipHeight > document.documentElement.clientHeight) {
          y = e.pageY - tooltipHeight - 8;
        }

        this.tooltipX = Math.max(padding, x);
        this.tooltipY = Math.max(padding, y);
      });
    },
    hideTooltip() {
      this.tooltipVisible = false;
    },

    // 行高计算
    getRowHeight(device) {
      const layers = this.getLayeredTasks(device);
      const layerCount = layers.length;
      const height = Math.max(this.baseRowHeight, layerCount * this.baseRowHeight);
      this.rowHeights[device] = height;
      return height;
    },
    getLayerOffset(layerIndex, totalLayers, device) {
      const rowHeight = this.getRowHeight(device);
      if (totalLayers <= 1) return 2;

      const totalSpacing = totalLayers * 4;
      const availableHeight = rowHeight - totalSpacing;
      const layerHeight = availableHeight / totalLayers;
      return layerIndex * (layerHeight + 4) + 2;
    },
    getLayerTaskHeight(totalLayers, device) {
      const rowHeight = this.getRowHeight(device);
      if (totalLayers <= 1) {
        return rowHeight - 4;
      } else {
        const totalSpacing = totalLayers * 4;
        const availableHeight = rowHeight - totalSpacing;
        return availableHeight / totalLayers;
      }
    },

    // 任务分层
    getLayeredTasks(device) {
      const tasks = this.getDeviceTasks(device);
      if (!tasks.length) return [];

      const sortedTasks = [...tasks].sort((a, b) => {
        const aStart = this.timeToMinutes(a.startTime);
        const bStart = this.timeToMinutes(b.startTime);
        if (this.timeToMinutes(a.endTime) < aStart && this.timeToMinutes(b.endTime) >= bStart) {
          return -1;
        }
        return aStart - bStart;
      });

      const layers = [];
      sortedTasks.forEach(task => {
        let placed = false;
        const taskStart = this.timeToMinutes(task.startTime);
        const taskEnd = this.timeToMinutes(task.endTime);
        const adjustedEnd = taskEnd < taskStart ? taskEnd + 24 * 60 : taskEnd;

        for (let i = 0; i < layers.length; i++) {
          const lastTask = layers[i][layers[i].length - 1];
          const lastEnd = this.timeToMinutes(lastTask.endTime);
          const lastAdjustedEnd =
            lastEnd < this.timeToMinutes(lastTask.startTime) ? lastEnd + 24 * 60 : lastEnd;

          if (taskStart >= lastAdjustedEnd) {
            layers[i].push(task);
            placed = true;
            break;
          }
        }
        if (!placed) {
          layers.push([task]);
        }
      });

      return layers;
    },
  },
};
</script>

<style scoped>
.gantt-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  font-family: Arial, sans-serif;
}

.gantt-header {
  height: 40px;
  margin-bottom: 10px;
}

.status-legend {
  display: flex;
  gap: 20px;
  float: right;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.legend-color {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.completed {
  background-color: #28a745;
}
.legend-color.processing {
  background-color: #007bff;
}
.legend-color.pending {
  background-color: #6c757d;
}

.gantt-wrapper {
  display: flex;
  height: calc(100% - 120px);
  border: 1px solid #eee;
  overflow: hidden;
}

/* 左侧信息列表样式 */
.info-list {
  width: 400px;
  background-color: #f8f9fa;
  border-right: 1px solid #eee;
  flex-shrink: 0;
}

.info-item-title {
  display: flex;
  background: #284c89;
  color: #fff;
  font-weight: bold;
  height: 36px;
}

.info-title-cell {
  flex: 1;
  text-align: center;
  line-height: 36px;
  border-right: 1px solid #eee;
}

.info-item {
  display: flex;
  height: 100%;
}

.info-cell {
  flex: 1;
  text-align: center;
  padding: 5px;
  box-sizing: border-box;
  border-right: 1px solid #eee;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size:13px;
}

.timeline-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
}

/* 图表X轴区域样式 */
.chart-axis {
  height: 36px;
  position: relative;
}

.time-labels {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 30px;
  display: flex;
  background-color: #284c89;
}

.major-label {
  position: absolute;
  top: 0;
  left: 0;
  font-size: 16px;
  color: #fff;
  font-weight: 500;
  white-space: nowrap;
  line-height: 30px;
}

.minor-labels {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.minor-label {
  position: absolute;
  top: 0;
  left: 0;
  font-size: 13px;
  color: #fff;
  white-space: nowrap;
  line-height: 30px;
  padding: 0 2px;
}

.tick-lines {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 6px;
  background-color: #284c89;
}

.major-tick-line {
  position: absolute;
  bottom: 0;
  width: 1px;
  height: 4px;
  background-color: #fff;
  transform: translateX(-50%);
}

.minor-tick-lines {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.minor-tick-line {
  position: absolute;
  bottom: 0;
  width: 1px;
  height: 4px;
  background-color: #fff;
  transform: translateX(-50%);
}

.axis-base-line {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 1px;
  background-color: #dee2e6;
}

/* 当前时间线样式 */
.current-time-line {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 2px;
  /* background-color: #ff4d4f; */
  transform: translateX(-50%);
  z-index: 10;
  height:100vh;
  border-left:1px dashed #ccc
}

/* 图表内容区域 */
.chart-content {
  flex: 1;
  position: relative;
  overflow-y: auto;
}

.grid-lines {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.grid-line {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 0px;
  background-color: #e9ecef;
}

.tasks-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.device-task-row {
  position: relative;
  border-bottom: 1px solid #e9ecef;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.task-bar {
  position: absolute;
  border-radius: 18px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  box-sizing: border-box;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.2s;
  white-space: nowrap;
}

.task-bar:hover {
  transform: translateY(-2px);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}

.task-label {
  font-size: 13px;
  color: white;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 提示框样式 */
.tooltip {
  position: fixed;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  font-size: 12px;
  pointer-events: none;
}

.tooltip-content div {
  margin: 3px 0;
}
.wo-code-title {
  font-size: 18px;
  font-weight: bold;
  color: #1f2d3d;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.detail-list {
  list-style: none;
  padding: 0;
  margin: 0;

  .detail-item {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    line-height: 20px;

    .label {
      width: 100px;
      color: #666;
      font-weight: 500;
    }

    .value {
      flex: 1;
      color: #333;
    }
  }
}

/* 分页样式 */
.pagination-container {
  position: fixed;  /* 固定定位 */
  right: 20px;      /* 距离右侧20px */
  bottom: 20px;     /* 距离底部20px */
  margin-top: 15px;
  background-color: #fff;  /* 增加背景色避免与内容重叠时看不清 */
  padding: 10px;     /* 增加内边距 */
  z-index: 10; 
}

:deep(.el-button--primary) {
  background-color: #284c89 !important;
  color: #fff;
}
</style>
