<template>
  <div class="app-container">
    <el-card style="height: 850px">
      <div style="margin-top: 7px; margin-bottom: 7px">
        <span class="show-text">生产订单:</span>
        <el-input
          v-model="orderNo"
          placeholder="请输入生产订单"
          clearable
          style="width: 150px; margin-right: 10px"
          @change="searchTable()"
        />
        <span class="show-text">计划号:</span>
        <el-input
          v-model="plannum"
          placeholder="请输入生产订单"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">物料编码:</span>
        <el-input
          v-model="productCode"
          placeholder="请输入物料编码"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">物料名称:</span>
        <el-input
          v-model="itemName"
          placeholder="请输入物料名称"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">工序名称:</span>
        <el-input
          v-model="processName"
          placeholder="请输入工序名称"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">执行状态:</span>
        <el-select v-model="dostate" placeholder="请选择">
          <el-option
            v-for="item in dostateoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
          <el-button
            icon="el-icon-search"
            plain
            type="primary"
            @click="searchTable()"
            >查询</el-button
          >
          
      </div>
      <el-table
        :data="mergedTableData"
        highlight-current-row
        border
        size="small"
        style="margin-top: 10px"
        height="75vh"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column  label="序号" type="index" align="center"  width="50"/>
        <el-table-column  label="生产订单" align="center" prop="订单号"  width="80" />
        <el-table-column  label="计划号" align="center" prop="计划号"  width="80" />
        <el-table-column  label="工序名称" align="center" prop="工序名称" width="120"/>
        <el-table-column  label="物料名称" align="center" prop="产品名称" width="200"/>
        <el-table-column  label="同步状态" align="center" width="100">
          <template slot-scope="scope">
            {{scope.row.派工状态 === 1 ? '已同步':'未同步'}}
          </template>
        </el-table-column>
        <el-table-column  label="上序合格数" align="center" prop="上序合格数"  width="100"/>
        <el-table-column  label="指派数量" align="center" prop="指派数量" width="80"/>
        <el-table-column  label="打印数量" align="center" prop="打印数量" width="80"/>
        <el-table-column  label="发料数量" align="center" prop="收料数量" width="80"/>
        <el-table-column  label="收货数量" align="center" prop="完成数量" width="80"/>
        <el-table-column  label="备注" align="center" prop="外协备注" width="200"/>
        <el-table-column  label="单重" align="center" prop="单重" width="80"/>
        <el-table-column  label="物料编码" align="center" prop="产品编码"  width="200"/>
        
        <el-table-column  label="打印次数" align="center" prop="外协打印次数" width="120"/>
        <el-table-column  label="计划开始时间" align="center" prop="计划开始时间" width="120">
          <template slot-scope="scope">
            {{formatDate(scope.row.计划开始时间)}}
          </template>
        </el-table-column>
        <el-table-column  label="计划完成时间" align="center" prop="计划完成时间" width="120">
          <template slot-scope="scope">
            {{formatDate(scope.row.计划完成时间)}}
          </template>
        </el-table-column>

      </el-table>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { postB1 } from '@/api/b1s';
import $ from 'jquery'
import QRCode from 'qrcode'
import { set } from 'nprogress';
import { MESDownFile } from '@/utils/request'
import { seepdf, initPDFKeyboardShortcuts, setZoom } from '@/utils/pdf';
export default {
  data() {
    return {
      downPDF:MESDownFile,
      seeVisible:false,
      qrCodeDataUrl:'',
      printDataList2:[],
      historyVisible:false,
      printdata2:[],
      historydata:[],
      dialogFormVisible1: false,
      tableData: [], // 原始数据
      mergedTableData: [], // 合并后的数据
      selectedRow:'',
      selectedRow2:'',
      productCode:'',
      orderNo:'',
      plannum:'',
      processName:'',
      itemName:'',
      sessionId:'',
      currentTime:'',
      receiveVisible:false,
      receiveData: {},
      receiveNum: 0,
      doVisible:false,
      doData: {},
      doNum: 0,
      // 新增：存储合并数据的原始信息
      mergedDataMap: new Map(), // 用于存储合并数据对应的原始数据组
      workstate:0,
      orderstate:0,
      dostate:1,
      workstateoptions:[{
        value: 0,
        label: '未同步'
      }, {
        value: 1,
        label: '已同步',
        disabled: true
      }],
      stateoptions:[{
        value: 0,
        label: '未完成',
        disabled: true
      }, {
        value: 1,
        label: '已完成',
        
      }],
      dostateoptions:[{
        value: 0,
        label: '全部',
        disabled: true
      }, {
        value: 1,
        label: '可执行',
        
      },{
        value: 2,
        label: '不可执行',
        
      }],
      multipleSelection: [],
      printDataList: [] ,// 新增：存储多个打印数据
      numname:'',
      textweight:'',
      textsum:'',
      textcontent:'',
      textData:{},
      textVisible:false,
      qrCodeCache: new Map(),
      qrCodeUrl: '',
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ]),
  },
  created() {
    this.searchTable()
    setInterval(this.getCurrentTime, 1000);
  },
  methods: {

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleRowClick(row) {
      this.selectedRow = row
    },
    handleRowClick2(row) {
      this.selectedRow2 = row
    },
    searchTable() {
      this.loading = true
      var param = []
      param.push(["订单号",this.orderNo])
      param.push(["产品编码",this.productCode])
      param.push(["产品名称",this.itemName])
      param.push(["工序名称",this.processName])
      param.push(["计划号",this.plannum])
      var Data = this.CreateData('11', '异常提醒_外协及时开工_查询',param)
      this.ExecDatabase(Data).then(response => {
          this.tableData = response.data
          this.mergeTableData() // 处理数据合并
      })
    },
    

    // 合并表格数据的方法
mergeTableData() {
  if (!this.tableData || this.tableData.length === 0) {
    this.mergedTableData = [];
    this.mergedDataMap.clear();
    return;
  }

  const groupedByOrder = {};
  this.tableData.forEach(item => {
    const groupKey = `${item.订单号}_${item.拆分内码}`;
    
    if (!groupedByOrder[groupKey]) {
      groupedByOrder[groupKey] = [];
    }
    groupedByOrder[groupKey].push(item);
  });

  const mergedData = [];
  this.mergedDataMap.clear();

  Object.keys(groupedByOrder).forEach(orderNo => {
    const orderItems = groupedByOrder[orderNo];
    orderItems.sort((a, b) => a.订单行号 - b.订单行号);
    
    let currentGroup = [orderItems[0]];
    
    for (let i = 1; i < orderItems.length; i++) {
      const currentItem = orderItems[i];
      const lastItem = orderItems[i - 1];
      
      if (currentItem.订单行号 === lastItem.订单行号 + 1 && currentItem.外协分组 === lastItem.外协分组 && currentItem.拆分内码 === lastItem.拆分内码) {
        currentGroup.push(currentItem);
      } else {
        // 检查组内最小计划开始时间是否小于今天
        if (this.checkGroupPlanStartValid(currentGroup)) {
          if (this.checkGroupAllZero(currentGroup)) {
            const mergedItem = this.mergeGroup(currentGroup);
            if (this.shouldIncludeByExecutionStatus(mergedItem)) {
              mergedData.push(mergedItem);
              this.mergedDataMap.set(mergedItem.uniqueKey, currentGroup);
            }
          }
        }
        currentGroup = [currentItem];
      }
    }
    
    // 处理最后一组
    if (currentGroup.length > 0) {
      if (this.checkGroupPlanStartValid(currentGroup)) {
        if (this.checkGroupAllZero(currentGroup)) {
          const mergedItem = this.mergeGroup(currentGroup);
          if (this.shouldIncludeByExecutionStatus(mergedItem)) {
            mergedData.push(mergedItem);
            this.mergedDataMap.set(mergedItem.uniqueKey, currentGroup);
          }
        }
      }
    }
  });

  this.mergedTableData = mergedData;
},

// 新增：检查组内最小计划开始时间是否小于今天
checkGroupPlanStartValid(group) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  // 获取组内最小的计划开始时间
  const minPlanStart = group.reduce((min, item) => {
    if (!item.计划开始时间) return min;
    const planDate = new Date(item.计划开始时间);
    planDate.setHours(0, 0, 0, 0);
    return planDate < min ? planDate : min;
  }, new Date('2099-12-31'));
  
  return minPlanStart < today;
},
// 新增：检查组内所有数据的收料数量是否都为0
checkGroupAllZero(group) {
  // 只有组内所有数据的收料数量都等于0，才返回true
  return group.every(item => {
    const 收料数量 = Number(item.收料数量) || 0;
    return 收料数量 === 0;
  });
},
    // 新增：根据执行状态筛选数据（纯前端筛选）
    shouldIncludeByExecutionStatus(mergedItem) {
      const 执行状态 = this.dostate; // 0=全部, 1=可执行, 2=不可执行
      
      if (执行状态 === 0) {
        return true; // 全部，不筛选
      }
      
      const itemExecutionStatus = mergedItem.执行状态 || 1; // 默认可执行
      
      if (执行状态 === 1) {
        return itemExecutionStatus === 1; // 只显示可执行
      } else if (执行状态 === 2) {
        return itemExecutionStatus === 2; // 只显示不可执行
      }
      
      return true;
    },
		
    // 合并单个组的数据
    mergeGroup(group) {
      if (group.length === 1) {
        const item = group[0];
        item.uniqueKey = `${item.订单号}_${item.订单行号}_${item.TaskAID}`;
        // 确保TaskAID是字符串类型
        item.TaskAID = String(item.TaskAID);
        
        // 计算单条记录的执行状态
        const 上序合格数 = item.上序合格数 || 0;
        const 订单行号 = item.订单行号;
        item.执行状态 = (订单行号 === 1 || 上序合格数 > 0) ? 1 : 2;
        
        return item;
      }
      
      const mergedItem = { ...group[0] };
      
      // 生成唯一标识key
      mergedItem.uniqueKey = group.map(item => `${item.订单号}_${item.订单行号}_${item.TaskAID}`).join('|');
      
      // 拼接工序名称（逗号间隔）
      const processNames = group.map(item => item.工序名称);
      mergedItem.工序名称 = processNames.join(',');
      
      // 拼接TaskAID（逗号间隔）
      const taskAIDs = [...new Set(group.map(item => String(item.TaskAID)))];
      mergedItem.TaskAID = taskAIDs.join(',');
      
      // 取计划开始时间的最小值
      const startTimes = group.map(item => new Date(item.计划开始时间));
      mergedItem.计划开始时间 = new Date(Math.min(...startTimes)).toISOString().slice(0, 19).replace('T', ' ');
      
      // 取计划完成时间的最大值
      const endTimes = group.map(item => new Date(item.计划完成时间));
      mergedItem.计划完成时间 = new Date(Math.max(...endTimes)).toISOString().slice(0, 19).replace('T', ' ');
      
      // 取最大值
      const wcnum = group.map(item => item.完成数量);
      mergedItem.完成数量 = Math.max(...wcnum);
      
      const printnum = group.map(item => item.外协打印次数);
      mergedItem.外协打印次数 = Math.max(...printnum);
      
      const slnum = group.map(item => item.收料数量);
      mergedItem.收料数量 = Math.max(...slnum);
      
      // 计算上序合格数（取组内最大值）
      const shxnum = group.map(item => item.上序合格数 || 0);
      mergedItem.上序合格数 = Math.max(...shxnum);
      
      // 计算执行状态：只要一组内包含订单行号=1 或者包含上序合格数>0，都属于可执行
      const hasFirstProcess = group.some(item => item.订单行号 === 1);
      const hasPreviousQualified = group.some(item => (item.上序合格数 || 0) > 0);
      mergedItem.执行状态 = (hasFirstProcess || hasPreviousQualified) ? 1 : 2;
      
      // 存储原始组数据引用
      mergedItem.originalGroup = group;
      
      return mergedItem;
    },
    
    // 获取订单行号最大的TaskAID
    getMaxOrderLineTaskAID(row) {
      // 如果是单条数据，直接返回TaskAID
      if (typeof row.TaskAID === 'number' || !row.TaskAID.includes(',')) {
        return String(row.TaskAID);
      }
      
      // 如果是合并数据，从原始数据组中找订单行号最大的TaskAID
      if (row.originalGroup) {
        const maxOrderLineItem = row.originalGroup.reduce((max, item) => {
          return item.订单行号 > max.订单行号 ? item : max;
        }, row.originalGroup[0]);
        return String(maxOrderLineItem.TaskAID);
      }
      
      // 如果没有原始组数据，从TaskAID字符串中取最后一个
      const taskAIDs = row.TaskAID.split(',');
      return taskAIDs[taskAIDs.length - 1];
    },
    // 获取订单行号最小的TaskAID
    getMinOrderLineTaskAID(row) {
      // 如果是单条数据，直接返回TaskAID
      if (typeof row.TaskAID === 'number' || !row.TaskAID.includes(',')) {
        return String(row.TaskAID);
      }
      // 如果是合并数据，从原始数据组中找订单行号最大的TaskAID
      console.log(row)
      if (row.originalGroup) {
        const minOrderLineItem = row.originalGroup.reduce((min, item) => {
          return item.订单行号 < min.订单行号 ? item : min;
        }, row.originalGroup[0]);
        
        return String(minOrderLineItem.TaskAID);
      }
      // 如果没有原始组数据，从TaskAID字符串中取最后一个
      const taskAIDs = row.TaskAID.split(',');
      return taskAIDs[taskAIDs.length - 1];
    },
    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },


  }
}
</script>
<style>
 .field-container {
      border: 1px solid #000;
      border-bottom:0px
  }
  .field-row {
      display: flex;
      width: 100%;
      border-bottom: 1px solid #000;
  }
  .field-group {
      display: flex;
      width: 25%;
      align-items: stretch;
      border-right: 1px solid #000;
  }
  .field-group:last-child {
      border-right: none;
  }
  .field-label {
      width: 40%;
      color: #000;
      text-align: right;
      padding: 12px 5px;
      border-right: 1px solid #000;
      display: flex;
      align-items: center;
      justify-content: flex-end;
  }
  .field-value {
      width: 60%;
      color: #303133;
      word-break: break-word;
      overflow-wrap: break-word;
      padding: 12px 10px;
      display: flex;
      align-items: center;
  }
</style>