<template>
  <div class='production-report-container'>
    <!-- 顶部标题栏 -->
    <div class='header-bar'>
      <div class='header-left'>
        <el-icon class='back-icon' @click='handleBack'>
          <ArrowLeft />
        </el-icon>
        <span class='user-info'>用户: {{ userInfo.userName || 'admin' }}</span>
        <span class='shift-info'>班次: {{ currentShift || '白班' }}</span>
        <span class='line-info'>生产线: {{ productionLine || 'DJ01' }}</span>
        <span class='workstation-info'>
          工位:
          <el-select
            v-model='workstationId'
            placeholder='请选择或搜索工位'
            :disabled='activeTab !== "pending"'
            filterable
            clearable
            @change='handleWorkstationChange'
          >
            <el-option
              v-for='item in filteredWorkstationList'
              :key='item.stationId'
              :label='item.stationName'
              :value='item.stationId'
            >
            </el-option>
          </el-select>
        </span>

      </div>
      <div class='header-center'>
        <h2 class='page-title'>生产报工</h2>
      </div>
      <div class='header-right'>
        <span class='current-time'>{{ currentTime }}</span>
        <el-icon class='menu-icon'>
          <Menu />
        </el-icon>
      </div>
    </div>

    <!-- Tab导航 - 显示在页面上方 -->
    <div class='tabs-header-wrapper'>
      <el-tabs v-model='activeTab' class='report-tabs' @tab-change='handleTabChange'>
        <el-tab-pane label='待处理任务' name='pending' />
        <el-tab-pane label='当前任务' name='current' />
        <el-tab-pane label='报工记录' name='record' />
        <el-tab-pane label='质检记录' name='inspection' />
        <el-tab-pane label='工艺文件查看' name='document' />
      </el-tabs>
    </div>

    <!-- Tab内容区域 -->
    <div class='tabs-content-wrapper'>
      <div v-show='activeTab === "pending"' class='tab-content'>
        <PendingTasks ref='pendingTasksRef' :workstationId='workstationId' @issue='handleIssue' />
      </div>
      <div v-show='activeTab === "current"' class='tab-content'>
        <CurrentTask ref='currentTaskRef' :workstationId='workstationId' @report-success='handleReportSuccess' />
      </div>
      <div v-show='activeTab === "record"' class='tab-content'>
        <WorkReportRecord ref='recordRef' :workstationId='workstationId' />
      </div>
      <div v-show='activeTab === "inspection"' class='tab-content'>
        <InspectionRecord ref='inspectionRef' :workstation='workstation' />
      </div>
      <div v-show='activeTab === "document"' class='tab-content'>
        <ProcessDocuments ref='documentRef' :workstationId='workstationId' />
      </div>
    </div>

    <!-- 消息提醒 -->
    <el-alert
      v-if='messageText'
      :title='messageText'
      type='success'
      :closable='false'
      show-icon
      class='message-alert'
    />
  </div>
</template>

<script setup name='ProductionReport' lang='ts'>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowLeft, Menu } from '@element-plus/icons-vue';
import PendingTasks from './components/PendingTasks.vue';
import CurrentTask from './components/CurrentTask.vue';
import WorkReportRecord from './components/WorkReportRecord.vue';
import InspectionRecord from './components/InspectionRecord.vue';
import ProcessDocuments from './components/ProcessDocuments.vue';
import { parseTime } from '@/utils/ruoyi';
import useUserStore from '@/store/modules/user';
import { getStationInfoList } from '@/api/mes/baseStationInfo';
import { BaseStationInfoVO } from '@/api/mes/baseStationInfo/types';

const router = useRouter();
const userStore = useUserStore();

// 用户信息
const userInfo = computed(() => userStore.userInfo || {});
// Tab相关
const activeTab = ref('pending');
const pendingTasksRef = ref();
const currentTaskRef = ref();
const recordRef = ref();
const inspectionRef = ref();
const documentRef = ref();

// 工位信息（可以从路由参数或用户信息中获取）
const productionLine = ref('DJ01');
const workstation = ref(''); // 工位名称
const workstationId = ref<string | number>(''); // 工位ID，用于查询
const currentShift = ref('白班');
const workstationList = ref<BaseStationInfoVO[]>([]);
const filteredWorkstationList = ref<BaseStationInfoVO[]>([]);
const workstationSearchText = ref('');

// 当前时间
const currentTime = ref('');
let timeInterval: any = null;

// 消息提醒
const messageText = ref('');

// 更新时间
const updateTime = () => {
  currentTime.value = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
};

// 返回
const handleBack = () => {
  router.back();
};

// Tab切换
const handleTabChange = (tabName: string) => {
  if (tabName === 'pending') {
    // 切换到待处理任务时刷新数据
    pendingTasksRef.value?.refresh?.();
  } else if (tabName === 'current') {
    // 切换到当前任务时刷新数据
    currentTaskRef.value?.refresh?.();
  } else if (tabName === 'record') {
    // 切换到报工记录时刷新数据
    recordRef.value?.refresh?.();
  } else if (tabName === 'inspection') {
    // 切换到质检记录时刷新数据
    inspectionRef.value?.refresh?.();
  }
};

// 获取工位列表
const getWorkstationList = async () => {
  try {
    const res = await getStationInfoList({});
    const data = res?.data || res;
    if (data && Array.isArray(data)) {
      workstationList.value = data;
      filteredWorkstationList.value = data;
      // 如果列表不为空且当前工位不在列表中，设置默认工位
      if (data.length > 0) {
        const foundWorkstation = data.find(item => item.stationName === workstation.value);
        if (foundWorkstation) {
          // 如果找到匹配的工位编码，设置对应的工位ID（watch会自动触发刷新）
          workstationId.value = foundWorkstation.stationId;
        } else {
          // 如果找不到匹配的工位，设置第一个工位为默认值（watch会自动触发刷新）
          workstation.value = data[0].stationName;
          workstationId.value = data[0].stationId;
        }
      }
    }
  } catch (error) {
    console.error('获取工位列表失败:', error);
  }
};

// 刷新所有组件数据
const refreshAllData = () => {
  // 刷新待处理任务
  pendingTasksRef.value?.refresh?.();
  // 刷新当前任务
  currentTaskRef.value?.refresh?.();
  // 刷新报工记录
  recordRef.value?.refresh?.();
  // 刷新质检记录
  inspectionRef.value?.refresh?.();
  // 刷新工艺文件（如果需要）
  documentRef.value?.refresh?.();
};

// 工位改变处理
const handleWorkstationChange = (stationId: string | number) => {
  // 根据工位ID找到对应的工位编码
  const selectedWorkstation = workstationList.value.find(item => item.stationId === stationId);
  if (selectedWorkstation) {
    workstation.value = selectedWorkstation.stationName;
  }
  // 更新工位ID（不在这里刷新，由watch统一处理，避免重复调用）
  workstationId.value = stationId;
};

// 处理下发工单
const handleIssue = (planId: string | number) => {
  // 显示成功消息
  messageText.value = `消息提醒: 工单号: ${planId} 开工成功!`;
  // 3秒后清除消息
  setTimeout(() => {
    messageText.value = '';
  }, 3000);
  // 切换到当前任务Tab
  activeTab.value = 'current';
  // 刷新当前任务数据
  setTimeout(() => {
    currentTaskRef.value?.refresh?.();
  }, 500);
};

// 处理报工成功
const handleReportSuccess = () => {
  // 刷新待处理任务列表（报工后可能影响待处理任务）
  pendingTasksRef.value?.refresh?.();
  // 刷新报工记录（新增了报工记录）
  recordRef.value?.refresh?.();
};

onMounted(() => {
  updateTime();
  timeInterval = setInterval(updateTime, 1000);

  // 从路由参数获取工位信息
  const route = router.currentRoute.value;
  if (route.query.workstation) {
    workstation.value = route.query.workstation as string;
  }
  if (route.query.productionLine) {
    productionLine.value = route.query.productionLine as string;
  }
  if (route.query.workstationId) {
    workstationId.value = route.query.workstationId as string | number;
  }

  // 获取工位列表
  getWorkstationList();
});

// 监听工位ID变化，自动刷新数据（统一在这里处理，避免重复调用）
watch(
  () => workstationId.value,
  (newVal, oldVal) => {
    // 只有在工位ID真正改变且不是初始值时才刷新
    if (newVal && newVal !== oldVal && oldVal !== undefined && oldVal !== '') {
      // 使用 nextTick 确保所有子组件都已接收到新的 prop
      setTimeout(() => {
        refreshAllData();
      }, 0);
    }
  }
);

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval);
  }
});
</script>

<style scoped lang='scss'>
.production-report-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;

  .header-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 20px;
    background: #fff;
    border-bottom: 1px solid #e4e7ed;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .header-left {
      display: flex;
      align-items: center;
      gap: 20px;
      flex: 1;

      .back-icon {
        font-size: 20px;
        cursor: pointer;
        color: #409eff;

        &:hover {
          color: #66b1ff;
        }
      }

      .user-info,
      .shift-info,
      .line-info {
        font-size: 14px;
      }

      .workstation-info {
        font-size: 14px;
        display: flex;
        align-items: center;
      }
    }

    .header-center {
      flex: 1;
      text-align: center;

      .page-title {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 15px;
      flex: 1;
      justify-content: flex-end;

      .current-time {
        font-size: 14px;
      }

      .menu-icon {
        font-size: 20px;
        cursor: pointer;
        color: #606266;

        &:hover {
          color: #409eff;
        }
      }
    }
  }

  .tabs-header-wrapper {
    background: #fff;
    margin: 0 10px;
    border-radius: 4px 4px 0 0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    flex-shrink: 0;
  }

  .report-tabs {
    width: 100%;

    :deep(.el-tabs__header) {
      margin: 0;
      padding: 0;
      background: #fff;
      border-bottom: 2px solid #e4e7ed;
    }

    :deep(.el-tabs__nav-wrap) {
      padding: 0 20px;

      &::after {
        display: none;
      }
    }

    :deep(.el-tabs__nav) {
      display: flex;
      border: none;
    }

    :deep(.el-tabs__item) {
      height: 56px;
      line-height: 56px;
      font-size: 16px;
      padding: 0 32px;
      margin-right: 8px;
      cursor: pointer;
      transition: all 0.3s;
      border: none;
      color: #606266;
      position: relative;
      background: transparent;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: transparent;
        transition: all 0.3s;
      }

      &.is-active {
        color: #409eff;
        font-weight: 600;

        &::after {
          background: #409eff;
        }
      }

      &:hover:not(.is-active) {
        color: #409eff;
        background: #f5f7fa;
      }
    }

    :deep(.el-tabs__active-bar) {
      display: none;
    }

    :deep(.el-tabs__content) {
      display: none;
    }
  }

  .tabs-content-wrapper {
    flex: 1;
    overflow: hidden;
    background: #fff;
    margin: 0 10px 10px 10px;
    border-radius: 0 0 4px 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    min-height: 0;
  }

  .tab-content {
    width: 100%;
    height: 100%;
    overflow: auto;
    padding: 20px;
  }

  .message-alert {
    position: fixed;
    top: 120px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 2000;
    min-width: 400px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}
</style>
