<template>
  <div class='p-2'>
    <transition :enter-active-class='proxy?.animate.searchAnimate.enter'
                :leave-active-class='proxy?.animate.searchAnimate.leave'>
      <div v-show='showSearch' class='mb-[10px]'>
        <el-card shadow='hover'>
          <el-form ref='queryFormRef' :model='queryParams' :inline='true'>
            <el-form-item label='机台名称' prop='releaseId'>
              <el-select v-model='queryParams.releaseId' placeholder='请选择机台名称' clearable>
                <el-option
                  v-for='item in releaseList'
                  :key='item.machineId'
                  :label='item.machineName'
                  :value='item.machineId'
                />
              </el-select>
            </el-form-item>

            <el-form-item label='计划时间区间' prop='planTimeRange' label-width="120px">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleDateRangeChange"
              />
            </el-form-item>

            <el-form-item label="班次" prop="shiftId">
              <el-select v-model="queryParams.shiftId" placeholder="请选择班次" clearable>
                <el-option
                  v-for="item in shiftList"
                  :key="item.shiftId"
                  :label="item.shiftName"
                  :value="item.shiftId"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type='primary' icon='Search' @click='handleQuery'>搜索</el-button>
              <el-button icon='Refresh' @click='resetQuery'>重置</el-button>
              <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow='hover' v-loading="loading">
      <el-table :data="planInfoList" style="width: 100%" border>
        <!-- 机台列 -->
        <el-table-column prop="machineName" label="机台" align="center" width="120" />

        <!-- 动态班次列 -->
        <template v-for="shift in uniqueShifts" :key="shift.shiftId">
          <el-table-column :label="shift.shiftName" align="center">
            <!-- 物料列 -->
            <el-table-column label="物料" align="left" min-width="300">
              <template #default="{ row }">
                <div class="cell-content">
                  <div v-for="plan in getPlansForShift(row, shift.shiftId)" :key="plan.planId" class="cell-item material-item">
                    <el-tooltip
                      :content="plan.materialName"
                      placement="top"
                      :show-after="500">
                      <span class="material-name">{{ plan.materialName }}</span>
                    </el-tooltip>
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- 计划数列 -->
            <el-table-column label="计划数" align="center" width="100">
              <template #default="{ row }">
                <div class="cell-content">
                  <div v-for="plan in getPlansForShift(row, shift.shiftId)" :key="plan.planId" class="cell-item">
                    {{ plan.planAmount }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- 完成数列 -->
            <el-table-column label="完成数" align="center" width="100">
              <template #default="{ row }">
                <div class="cell-content">
                  <div v-for="plan in getPlansForShift(row, shift.shiftId)" :key="plan.planId" class="cell-item">
                    {{ plan.completeAmount || 0 }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- 计划监控列 -->
            <el-table-column label="计划监控" align="center" width="120">
              <template #default="{ row }">
                <div class="cell-content">
                  <div v-for="plan in getPlansForShift(row, shift.shiftId)" :key="plan.planId" class="cell-item monitor-item">
                    <span class="completion-rate" :style="{ backgroundColor: getCompletionBgColor(plan), color: getCompletionTextColor(plan) }">
                      {{ getCompletionPercentage(plan) }}%
                    </span>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </el-table>

      <pagination v-show='total > 0' :total='total' v-model:page='queryParams.pageNum'
                  v-model:limit='queryParams.pageSize' @pagination='getList' />
    </el-card>

  </div>
</template>

<script setup name='PlanInfo' lang='ts'>
import {
  listPlanInfo,
  getPlanInfo,
  delPlanInfo,
  addPlanInfo,
  updatePlanInfo,
  orderAddProductPlanList, issuePlanInfo, queryMoritorList
} from '@/api/mes/planInfo';
import { PlanInfoVO, PlanInfoQuery, PlanInfoForm } from '@/api/mes/planInfo/types';
import { getBaseShiftInfoList } from '@/api/mes/baseShiftInfo';
import { getBaseClassTeamInfoList } from '@/api/mes/baseClassTeamInfo';
import BomSelect from '@/views/mes/materialBom/addBom.vue';
import MaterialSelect from '@/views/mes/baseMaterialInfo/addMaterial.vue';
import { getProcessInfoList } from '@/api/mes/baseProcessInfo';
import { getStationInfoList } from '@/api/mes/baseStationInfo';
import { getProdBaseMachineInfoList } from '@/api/mes/prodBaseMachineInfo';
import { ProdBaseMachineInfoVO } from '@/api/mes/prodBaseMachineInfo/types';
import type { PlanMonitorVO, ShiftGroupVO } from '@/api/mes/planInfo/types';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  mes_import_flag,
  active_flag,
  mes_plan_status,
  mes_release_type,
  mes_finish_flag,
  mes_model_code
} = toRefs<any>(proxy?.useDict('mes_import_flag', 'active_flag', 'mes_plan_status', 'mes_release_type', 'mes_finish_flag', 'mes_model_code'));

const planInfoList = ref<PlanInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const planInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const sfpBatchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const formingBatchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const vulBatchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const shiftList = ref([]);
const classTeamList = ref([]);
const processList = ref([]);
let releaseList = ref([]);
const materialBomOpen = ref(false);
const bomSelectRef = ref();
const materialOpen = ref(false);
const materialSelectRef = ref();
const materialIdForm = ref();

const workshopId = ref();

const prodBaseMachineInfoList = ref<ProdBaseMachineInfoVO[]>([]);

const machineIds = ref<Array<string | number>>([]);

const machineQueryParams = ref({});

const initFormData: PlanInfoForm = {
  planId: undefined,
  productOrderId: undefined,
  saleOrderId: undefined,
  saleorderCode: undefined,
  planCode: undefined,
  dispatchCode: undefined,
  materialId: undefined,
  materialBomId: undefined,
  processId: undefined,
  processOrder: undefined,
  lastProcessId: undefined,
  finalProcessFlag: undefined,
  releaseType: '1',
  releaseId: undefined,
  productionTime: undefined,
  planAmount: 1,
  dispatchAmount: undefined,
  completeAmount: undefined,
  planBeginTime: undefined,
  planEndTime: undefined,
  realBeginTime: undefined,
  realEndTime: undefined,
  attachId: undefined,
  planStatus: undefined,
  importFlag: undefined,
  finishFlag: [],
  priority: 1,
  shiftId: undefined,
  classTeamId: undefined,
  modelCode: undefined,
  remark: undefined,
  materialBoMName: undefined,
  workshopId: undefined,
  shifitId: undefined,
  shiftName: undefined,
};
const data = reactive<PageData<PlanInfoForm, PlanInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: undefined,
    pageSize: undefined,
    planId: undefined,
    productOrderId: undefined,
    saleOrderId: undefined,
    saleorderCode: undefined,
    planCode: undefined,
    dispatchCode: undefined,
    materialId: undefined,
    materialBomId: undefined,
    processId: undefined,
    processOrder: undefined,
    lastProcessId: undefined,
    finalProcessFlag: undefined,
    releaseType: undefined,
    releaseId: undefined,
    productionTime: undefined,
    planAmount: undefined,
    dispatchAmount: undefined,
    completeAmount: undefined,
    planBeginTime: undefined,
    planEndTime: undefined,
    realBeginTime: undefined,
    realEndTime: undefined,
    attachId: undefined,
    planStatus: undefined,
    importFlag: undefined,
    finishFlag: undefined,
    priority: undefined,
    shiftId: undefined,
    classTeamId: undefined,
    modelCode: undefined,
    workshopId: undefined,
    params: {},

    shiftName: undefined,
    shifitId: undefined,
  },
  rules: {},
});

const { queryParams, form } = toRefs(data);
// const machineNameTags = ref([]);

const getWorkshopId = async () => {
  // 获取当前路由实例
  const router = useRouter();
  // 从当前路由的查询参数中提取workshopId，并赋值给workshopId变量
  workshopId.value = router.currentRoute._rawValue.query && router.currentRoute._rawValue.query.workshopId;
  // 将提取到的workshopId赋值给queryParams对象的workshopId属性
  queryParams.value.workshopId = workshopId.value;
};

/** 查询生产计划信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await queryMoritorList(queryParams.value);
  planInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  form.value.workshopId = workshopId.value;
  planInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = async () => {
  try {
    loading.value = true;
    // 校验时间区间
    if (!dateRange.value || dateRange.value.length !== 2) {
      ElMessage.warning('请选择时间区间');
      return;
    }

    // 设置查询参数
    queryParams.value.params = {
      monitorBeginTime: dateRange.value[0],
      monitorEndTime: dateRange.value[1]
    };

    const res = await queryMoritorList(queryParams.value);
    if (res.code === 200) {
      planInfoList.value = res.data;
      console.log('查询结果:', planInfoList.value);
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败');
  } finally {
    loading.value = false;
  }
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  queryParams.value.params.monitorBeginTime = undefined;
  queryParams.value.params.monitorEndTime = undefined;
  queryFormRef.value?.resetFields();
};


/*获取班次下拉框*/
const getShiftSelect = async () => {
  let res = await getBaseShiftInfoList(null);
  shiftList.value = res.data;
};

/*获取班组下拉框*/
const getClassTeamSelect = async () => {
  let res = await getBaseClassTeamInfoList(null);
  classTeamList.value = res.data;
};

/*获取半制品工序下拉框*/
const getProcessSelect = async () => {
  let res = await getProcessInfoList({ processType: 1 });
  processList.value = res.data.filter(item => item.processId !== 17 && item.processId !== 18);
};

/*获取机台下拉框*/
const getReleaseSelect = async () => {
  // machineQueryParams.value.processId = form.value.processId;
  let res = await getProdBaseMachineInfoList(machineQueryParams.value);
  releaseList.value = res.data;
  prodBaseMachineInfoList.value = res.data;
};

/*在菜单管理中关闭了keep-alive，并且增加了watch监听workshopId*/
/** 监听路由参数变化 */
watch(
  () => useRouter().currentRoute.value.query.workshopId,
  (newWorkshopId) => {
    if (newWorkshopId !== undefined) {
      workshopId.value = Number(newWorkshopId);
      queryParams.value.workshopId = Number(newWorkshopId);
      // 重新加载数据
      getList();
    }
  }
);

onMounted(() => {
  getWorkshopId();//从路由参数中获取车间ID
  getShiftSelect();
  // getClassTeamSelect();
  // getProcessSelect();
  getReleaseSelect();
  // getList();
  handleQuery();
});

/*在模板中，使用 v-for 指令来动态生成班次列。对于每个班次，再生成多个子列（如物料、计划数、实际数、计划监控）。
v-for="shift in uniqueShifts"：遍历 uniqueShifts，为每个班次生成一列。
。*/
// 计算属性：提取所有唯一的机台
const uniqueMachines = computed(() => {
  const machines = [];
  const machineIds = new Set();

  planInfoList.value.forEach(item => {
    if (item.releaseId && !machineIds.has(item.releaseId)) {
      machineIds.add(item.releaseId);
      machines.push({
        machineId: item.releaseId,
        machineName: item.releaseName
      });
    }
  });

  return machines;
});

// 修改计算属性：提取所有唯一的班次，不要依赖于选择的查询条件
const uniqueShifts = computed(() => {
  const shiftsMap = new Map();

  planInfoList.value.forEach((machine: any) => {
    machine.shifts.forEach((shift: any) => {
      if (!shiftsMap.has(shift.shiftId)) {
        shiftsMap.set(shift.shiftId, {
          shiftId: shift.shiftId,
          shiftName: shift.shiftName
        });
      }
    });
  });

  // 转换为数组并按shiftId排序
  return Array.from(shiftsMap.values()).sort((a, b) => a.shiftId - b.shiftId);
});

// 获取指定机台和班次的计划列表
const getPlansForShift = (machine: PlanMonitorVO, shiftId: number) => {
  const shift = machine.shifts.find((s: any) => s.shiftId === shiftId);
  return shift?.plans || [];
};

// 获取完成率背景颜色
const getCompletionBgColor = (plan: any) => {
  const percentage = getCompletionPercentage(plan);
  if (percentage >= 100) return '#f0f9eb';
  if (percentage >= 60) return '#fdf6ec';
  return '#fef0f0';
};

// 获取完成率文字颜色
const getCompletionTextColor = (plan: any) => {
  const percentage = getCompletionPercentage(plan);
  if (percentage >= 100) return '#67C23A';
  if (percentage >= 60) return '#E6A23C';
  return '#F56C6C';
};

// 计算完成百分比
const getCompletionPercentage = (plan: any) => {
  if (!plan.planAmount) return 0;
  const percentage = (plan.completeAmount || 0) / plan.planAmount * 100;
  return Math.round(percentage * 100) / 100;
};

//搜索计划时间区间
const dateRange = ref([]);
// 确保初始化queryParams.params
if (!data.queryParams.params) {
  data.queryParams.params = {};
}
// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    data.queryParams.params.monitorBeginTime = val[0];
    data.queryParams.params.monitorEndTime = val[1];
  } else {
    data.queryParams.params.monitorBeginTime = undefined;
    data.queryParams.params.monitorEndTime = undefined;
  }
};


// 导出按钮操作
function handleExport() {
  proxy.download('/mes/planInfo/exportMonitor', {
    ...queryParams.value
  }, `生产计划监控_${new Date().getTime()}.xlsx`)
}

</script>
<style>
/* 设置头部样式 */
.my-header {
  /* 宽度为100% */
  width: 100%;
  /* 文本居中对齐 */
  text-align: center;
}

/* 覆盖层对话框的头部样式 */
.el-overlay .el-overlay-dialog .el-dialog .el-dialog__header {
  /* 去除底部边框 */
  border-bottom: none;
}

/* 材料项样式 */
.material-item {
  padding: 0 12px;
  height: 36px;
  line-height: 36px;
  display: flex;
  align-items: center;
  overflow: hidden;
}

.material-name {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

/* 进度条样式 */
.progress-bar {
  /* 宽度100% */
  width: 100%;
  /* 高度20px */
  height: 20px;
  /* 背景色#f0f0f0 */
  background-color: #f0f0f0;
  /* 圆角半径4px */
  border-radius: 4px;
  /* 隐藏溢出内容 */
  overflow: hidden;
}

/* 进度条内部样式 */
.progress-bar-inner {
  /* 高度100% */
  height: 100%;
  /* 背景色#67C23A */
  background-color: #67C23A;
  /* 使用flex布局 */
  display: flex;
  /* 垂直居中对齐 */
  align-items: center;
  /* 水平居中对齐 */
  justify-content: center;
  /* 文字颜色白色 */
  color: white;
  /* 最小宽度30px */
  min-width: 30px;
  /* 宽度变化过渡效果 */
  transition: width 0.3s ease;
}

/* 新添加的样式 */
.material-row {
  margin-bottom: 12px;
  padding: 6px;
  border-bottom: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.material-row:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.material-count {
  text-align: left;
  margin-bottom: 2px;
}

.progress-container {
  margin-bottom: 12px;
  padding: 6px;
  display: flex;
  align-items: center;
  height: 55px; /* 与material-row的平均高度保持一致 */
  border-bottom: 1px solid #eee;
}

.progress-container:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

/* 每个单元格内容的通用样式 */
.cell-content {
  display: flex;
  flex-direction: column;
}

.cell-item {
  height: 36px;
  line-height: 36px;
  padding: 0 12px;
  border-bottom: 1px solid #EBEEF5;
  display: flex;
  align-items: center;
}

.cell-item:last-child {
  border-bottom: none;
}

/* 计划监控列的特殊样式 */
.monitor-item {
  justify-content: center; /* 水平居中 */
}

.completion-rate {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.5;
  min-width: 45px;
  text-align: center;
}

.completion-zero {
  background-color: #fef0f0;
  color: #f56c6c;
}

.completion-partial {
  background-color: #fef0f0;
  color: #f56c6c;
}

.completion-full {
  background-color: #f0f9eb;
  color: #67c23a;
}

:deep(.el-table) {
  font-size: 14px;
  table-layout: fixed; /* 使用固定表格布局 */
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}

:deep(.el-table td) {
  padding: 0;
}

:deep(.el-table .cell) {
  padding: 0;
  white-space: normal; /* 允许文本换行 */
}

/* 确保物料列文字左对齐 */
:deep(.el-table .cell-content .material-item) {
  justify-content: flex-start;
}

/* 调整其他列的宽度 */
:deep(.el-table .el-table__cell) {
  padding: 0;
}

/* 确保tooltip正常显示 */
:deep(.el-tooltip__trigger) {
  width: 100%;
}
</style>
