<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="issuingstate" placeholder="请选择">
        <el-option
            v-for="item in issuingoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select> -->
        <br></br>
        <span class="show-text">同步状态:</span>
        <el-select v-model="workstate" placeholder="请选择">
          <el-option
            v-for="item in workstateoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <span class="show-text">状态:</span>
        <el-select v-model="orderstate" placeholder="请选择">
          <el-option
            v-for="item in stateoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <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
          >
          <el-button icon="el-icon-update" type="primary" plain size="small" style="margin-left: 10px;padding: 8px 15px; width: 150px;" @click="updatesap" >派工并同步SAP</el-button>
          <el-button icon="el-icon-printer" type="primary" plain size="small" style="margin-left: 10px;padding: 8px 15px;" @click="searchTable1" >打印</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="80" /> -->
        <el-table-column  label="物料名称" align="center" prop="产品名称" width="120"/>
        <el-table-column  label="工序名称" align="center" prop="工序名称" width="100"/>
        <el-table-column  label="物料编码" align="center" prop="产品编码"  width="150"/>
        <el-table-column  label="计划开始时间" align="center" prop="计划开始时间" width="60">
          <template slot-scope="scope">
            {{formatDate(scope.row.计划开始时间)}}
          </template>
        </el-table-column>
        <el-table-column  label="计划完成时间" align="center" prop="计划完成时间" width="60">
          <template slot-scope="scope">
            {{formatDate(scope.row.计划完成时间)}}
          </template>
        </el-table-column>
        
        <!-- <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="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="500px" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="receive(scope.row)">发料
            </el-button>
            <el-button
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="doreceive(scope.row)">收货
            </el-button>
            <el-button
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="updatedata(scope.row)">更新
            </el-button>
            <!-- <el-button
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="edittext(scope.row)">编辑
            </el-button> -->
            <!-- <el-button
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="history(scope.row)">历史记录
            </el-button> -->
            <el-button v-if="scope.row.worker !=0"
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="getitemdraw(scope.row)">查看图纸
            </el-button>
            <el-button 
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="getitemdraw2(scope.row)">工艺图纸
            </el-button>
            <el-button 
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="getdetail(scope.row)">收发记录
            </el-button>
            <el-button 
              type="text"
              size="mini"
              style="margin-right: 5px; padding:0; width:auto"
              @click="getQulityInspectiondetail(scope.row)">质检记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div v-for="(printData, index) in printDataList" :key="index" class="print-page" style="display: none; width: 20cm;height: 11.5cm;background-color: #fff; page-break-after: always;" >
        <div style="margin-bottom: 20px;">
          <div style="display: flex;">
            <div style="width: 30%;
              height: 40px;
              background: url(/static/img/logo.6454a812.png);
              background-size: contain;
              background-repeat: no-repeat;
              "></div>
            <div style="width: 40%;text-align: center;font-size: 25px;line-height: 40px;">大连元利流体生产工票</div>
            <div style="width: 30%;">
              <img 
                  :src="printData.qrCodeDataUrl" 
                  style="width: 60px; height: 60px; margin: 0 auto; display: block;" />
            </div>
          </div>
        </div>
        <div class="field-container">
            <div class="field-row">
                <div class="field-group">
                    <span class="field-label">生产订单</span>
                    <span class="field-value">{{ printData.订单号 }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">工序名称</span>
                    <span class="field-value">{{ printData.工序名称 }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">数量</span>
                    <span class="field-value">{{ printData.打印数量 > 0 ? printData.打印数量 : printData.上序合格数 }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">销售订单</span>
                    <span class="field-value">{{ printData.合同号}}</span>
                </div>
            </div>
            <div class="field-row">
                <div class="field-group">
                    <span class="field-label">物料编码</span>
                    <span class="field-value">{{ printData.产品编码}}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">物料名称</span>
                    <span class="field-value">{{ printData.产品名称}}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">单重</span>
                    <span class="field-value">{{ printData.单重}}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">打印次数</span>
                    <span class="field-value">{{ printData.外协打印次数}}</span>
                </div>
            </div>
            <div class="field-row">
              <div class="field-group" style="width: 100%;">
                  <span class="field-label" style="width: 10%;">备注</span>
                  <span class="field-value" style="width: 90%;">{{printData.外协备注}}</span>
              </div>
            </div>
            <div class="field-row">
                <div class="field-group">
                    <span class="field-label">制单人</span>
                    <span class="field-value">{{printData.最后编辑人}}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">制单日期</span>
                    <span class="field-value">{{formatDate(printData.最后编辑时间) }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">操作者</span>
                    <span class="field-value">{{ numname }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">计划完工</span>
                    <span class="field-value">{{ formatDate(printData.计划完成时间)  }}</span>
                </div>
            </div>
            <div class="field-row">
                <div class="field-group">
                    <span class="field-label">操作者</span>
                    <span class="field-value"></span>
                </div>
                <div class="field-group">
                    <span class="field-label">受单日期</span>
                    <span class="field-value"></span>
                </div>
                <div class="field-group">
                    <span class="field-label">检验员</span>
                    <span class="field-value"></span>
                </div>
                <div class="field-group">
                    <span class="field-label">检验日期</span>
                    <span class="field-value"></span>
                </div>
            </div>
            
        </div>
        <div style="width: 100%;text-align: center; font-size: 80px;font-weight: bolder;letter-spacing: 100px;">
          {{ printData.订单号 }}
        </div>
      </div>
    <div v-for="(printData, index) in printDataList2" :key="index" class="print-page2" style="display: none; width: 20cm;height: 11.5cm;background-color: #fff; page-break-after: always;" >
        <div style="margin-bottom: 20px;">
          <div style="display: flex;">
            <div style="width: 30%;
              height: 40px;
              background: url(/static/img/logo.6454a812.png);
              background-size: contain;
              background-repeat: no-repeat;
              "></div>
            <div style="width: 40%;text-align: center;font-size: 25px;line-height: 40px;">大连元利流体生产工票</div>
            <div style="width: 30%;">
              <img 
                  :src="qrCodeDataUrl" 
                  style="width: 60px; height: 60px; margin: 0 auto; display: block;" />
            </div>
          </div>
        </div>
        <div class="field-container">
            <div class="field-row">
                <div class="field-group">
                    <span class="field-label">生产订单</span>
                    <span class="field-value">{{ printData.订单号 }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">工序名称</span>
                    <span class="field-value">{{ printData.工序名称 }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">数量</span>
                    <span class="field-value">{{ printdata2.操作数值 }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">销售订单</span>
                    <span class="field-value">{{ printData.合同号}}</span>
                </div>
            </div>
            <div class="field-row">
                <div class="field-group">
                    <span class="field-label">物料编码</span>
                    <span class="field-value">{{ printData.产品编码}}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">物料名称</span>
                    <span class="field-value">{{ printData.产品名称}}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">单重</span>
                    <span class="field-value">{{ printData.单重}}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">打印次数</span>
                    <span class="field-value">{{ printData.外协打印次数}}</span>
                </div>
            </div>
            <div class="field-row">
              <div class="field-group" style="width: 100%;">
                  <span class="field-label" style="width: 10%;">备注</span>
                  <span class="field-value" style="width: 90%;">{{printdata2.操作描述}}</span>
              </div>
            </div>
            <div class="field-row">
                <div class="field-group">
                    <span class="field-label">制单人</span>
                    <span class="field-value">{{printData.最后编辑人}}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">制单日期</span>
                    <span class="field-value">{{formatDate(printdata2.最后编辑时间) }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">操作者</span>
                    <span class="field-value">{{ numname }}</span>
                </div>
                <div class="field-group">
                    <span class="field-label">计划完工</span>
                    <span class="field-value">{{ formatDate(printData.计划完成时间)  }}</span>
                </div>
            </div>
            <div class="field-row">
                <div class="field-group">
                    <span class="field-label">操作者</span>
                    <span class="field-value"></span>
                </div>
                <div class="field-group">
                    <span class="field-label">受单日期</span>
                    <span class="field-value"></span>
                </div>
                <div class="field-group">
                    <span class="field-label">检验员</span>
                    <span class="field-value"></span>
                </div>
                <div class="field-group">
                    <span class="field-label">检验日期</span>
                    <span class="field-value"></span>
                </div>
            </div>
            
        </div>
        <div style="width: 100%;text-align: center; font-size: 80px;font-weight: bolder;letter-spacing: 100px;">
          {{ printData.订单号 }}
        </div>
      </div>
    <el-dialog :visible.sync="receiveVisible" title="发料" width="600px" center>
      <el-form
        ref="receiveForm"
        :model="receiveData"
        label-width="140px"
        size="mini"
      >
        <el-form-item label="生产订单">
          <el-input v-model="receiveData.订单编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="销售订单">
          <el-input v-model="receiveData.销售订单" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="物料编号">
          <el-input v-model="receiveData.物料编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="分配数">
          <el-input v-model="receiveData.指派数量" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="上序合格数">
          <el-input v-model="receiveData.上序合格数" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="已发料">
          <el-input v-model="receiveData.收料数量" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="发料工位">
          <el-input v-model="receiveData.指派对象" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="本次发料">
          <el-input
            v-model="receiveNum"
            type="number"
            @change="funreceiveNum"
          />
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="this.$store.state.user.name" :rows="2" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="receiveVisible = false">取 消</el-button>
        <el-button type="primary" @click="receiveForm()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="doVisible" title="收货" width="600px" center>
      <el-form
        ref="doForm"
        :model="doData"
        label-width="140px"
        size="mini"
      >
        <el-form-item label="生产订单">
          <el-input v-model="doData.订单编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="销售订单">
          <el-input v-model="doData.销售订单" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="物料编号">
          <el-input v-model="doData.物料编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="发料数">
          <el-input v-model="doData.收料数量" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="已收货">
          <el-input v-model="doData.完成数量" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="发料工位">
          <el-input v-model="doData.指派对象" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="本次收货">
          <el-input
            v-model="doNum"
            type="number"
            @change="fundoNum"
          />
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="this.$store.state.user.name" :rows="2" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="doVisible = false">取 消</el-button>
        <el-button type="primary" @click="doForm()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="textVisible" title="编辑" width="600px" center>
      <el-form
        ref="editform"
        :model="textData"
        label-width="140px"
        size="mini"
      >
        <el-form-item label="打印数量">
          <el-input
            v-model="textsum"
            type="text"
            @change="funtextsum"
          />
        </el-form-item>
        <el-form-item label="单重">
          <el-input
            v-model="textweight"
            type="text"
            @change="funtextweight"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="textcontent"
            type="text"
            @change="funtextcontent"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="textVisible = false">取 消</el-button>
        <el-button type="primary" @click="textForm()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dohistoryVisible" title="收发记录" width="800px" center>
      <el-table
        :data="dohistoryData"
        highlight-current-row
        border
        size="small"
        style="margin-top: 10px"
        height="300px"
        >
        <el-table-column  label="类型" align="center" prop="操作类别" width="200">
          <template slot-scope="scope">
            {{scope.row.操作类别 === '报工'?'收料':'发料'}}
          </template>
        </el-table-column>
        <el-table-column  label="时间" align="center" prop="开始时间" width="200"/>
        <el-table-column  label="数量" align="center" prop="操作数值" width="100"/>
        <el-table-column  label="操作人" align="center" prop="操作人" width="100"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dohistoryVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="QulityInspectionVisible" title="质检记录" width="800px" center>
      <el-table
        :data="QulityInspectionData"
        highlight-current-row
        border
        size="small"
        style="margin-top: 10px"
        height="300px"
        >
        <el-table-column  label="质检类型" align="center" prop="质检类型" width="100"/>
        
        <el-table-column  label="检验数量" align="center" prop="检验数量" width="100"/>
        <el-table-column  label="合格数" align="center" prop="合格数" width="100"/>
        <el-table-column  label="不合格数" align="center" prop="不合格数" width="100"/>
        <el-table-column  label="操作人" align="center" prop="检测人" width="100"/>
        <el-table-column  label="时间" align="center" prop="检测时间" width="200"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="QulityInspectionVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="seeVisible" title="图纸" center width="1200px" overflow="scroll" >
      <div id="el-dialog__body" style="min-height: 500px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="seeVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </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,
      issuingstate:2,
      orderstate:0,
      dostate:1,
      workstateoptions:[{
        value: 0,
        label: '未同步'
      }, {
        value: 1,
        label: '已同步',
        disabled: true
      }],
      stateoptions:[{
        value: 0,
        label: '未完成',
        disabled: true
      }, {
        value: 1,
        label: '已完成',
        
      }],
      issuingoptions:[{
        value: 0,
        label: '未发料',
        disabled: true
      }, {
        value: 1,
        label: '已发料',
        
      }, {
        value: 2,
        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: '',
      dohistoryData:'',
      dohistoryVisible:false,
      QulityInspectionVisible:false,
      QulityInspectionData:'',
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ]),
  },
  created() {
    this.searchTable()
    setInterval(this.getCurrentTime, 1000);
  },
  methods: {
    updatedata(row){
      var param = []
      console.log(row.TaskAID)
      param.push(["TaskAID", row.TaskAID]);
      var Data = this.CreateData('11', '计划排产_重置派工状态',param)
      this.ExecDatabase(Data).then(response => {
        this.$message.success('修改成功')
        this.searchTable()
      })
    },
    print(row){
      this.printdata2 = row
      this.numname = this.$store.state.user.name
      this.preparePrintData2(row)
      this.printDataList = []

      try {
        this.$nextTick(() => {
          setTimeout(() => {
            this.executePrint2()
          }, 500)
        })
      } catch (error) {
        console.error('获取打印数据失败:', error)
        this.$message.error('获取打印数据失败')
      } finally {
        this.loading = false
      }
    },
    history(row){
      var param = []
      const maxTaskAID = this.getMaxOrderLineTaskAID(row);
      const minTaskAID = this.getMinOrderLineTaskAID(row);
      // param.push(["minTaskAID", minTaskAID]);
      param.push(["TaskAID", maxTaskAID]);
      var Data = this.CreateData('11', '生产管理_外协管理_外协历史查询',param)
      this.ExecDatabase(Data).then(response => {
        this.historydata = response.data
        this.historyVisible = true
      })
    },
    async generateQRCode(text) {
      if (!text) return ''
      
      const cacheKey = String(text)
      
      if (this.qrCodeCache.has(cacheKey)) {
        return this.qrCodeCache.get(cacheKey)
      }
      
      try {
        const qrCodeDataUrl = await QRCode.toDataURL(cacheKey, {
          width: 120,
          margin: 1,
          color: {
            dark: '#000000',
            light: '#FFFFFF'
          },
          errorCorrectionLevel: 'M'
        })
        
        this.qrCodeCache.set(cacheKey, qrCodeDataUrl)
        console.log(this.qrCodeCache)
        return qrCodeDataUrl
        
      } catch (err) {
        console.error('二维码生成失败:', err)
        return ''
      }
    },
    edittext(row){
      this.textVisible = true
      this.textcontent = row.外协备注
      this.textweight = row.单重
      this.textsum = row.打印数量
    },
    async searchTable1() {
      // var row = this.selectedRow
      // if (row.length === 0) {
      //   this.$message.warning('请选择要打印的数据')
      //   return
      // }

      this.loading = true
      
      // 清空之前的打印数据
      this.printDataList = []

      try {
        this.$nextTick(() => {
          setTimeout(() => {
            this.handlePrint()
          }, 500)
        })
        
      this.numname = this.$store.state.user.name
      } catch (error) {
        console.error('获取打印数据失败:', error)
        this.$message.error('获取打印数据失败')
      } finally {
        this.loading = false
      }
    },
    // 修改：整合打印流程
    updatesap(){
      this.clickadjust()
    },
    async handlePrint() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要打印的数据')
        return
      }

      if (this.isPrinting) {
        this.$message.warning('正在打印中，请稍候...')
        return
      }

      this.isPrinting = true
      this.loading = true

      try {
        // 1. 获取打印数据
        await this.preparePrintData()
        
        // 2. 执行打印
     
        await this.executePrint()
        
        // 3. 更新打印次数
        await this.recordPrintCount()
        // 4. 派工
        

        this.$message.success('打印完成')
        
      } catch (error) {
        console.error('打印流程失败:', error)
        this.$message.error('打印失败: ' + error.message)
      } finally {
        this.loading = false
        this.isPrinting = false
      }
    },

    // 准备打印数据
    async preparePrintData() {
      this.printDataList = []
     
      for (const item of this.multipleSelection) {
          item.qrCodeDataUrl = await this.generateQRCode(item.订单号)
          this.printDataList.push(item)
          
      }
    },
    async preparePrintData2() {
      this.printDataList2 = []
      this.qrCodeDataUrl = await this.generateQRCode(this.selectedRow.订单号)
      this.printDataList2.push(this.selectedRow)


      console.log(this.printDataList2)  
      
    },

    // 执行打印
    executePrint() {
      
      return new Promise((resolve, reject) => {
        try {
          // 保存原始样式
          const originalStyles = {}
          $('.print-page').each(function(index) {
            originalStyles[index] = $(this).attr('style')
          })
          
          const body = $('body')
          
          // 隐藏原始内容
          body.children().hide()
          
          // 创建打印容器
          const printContainer = $('<div class="print-container"></div>')
          
          // 复制所有打印页面到打印容器
          $('.print-page').each(function() {
            const pageClone = $(this).clone()
            pageClone.css({
              display: 'block',
              width: '20cm',
              height: '11.5cm',
              'background-color': '#fff',
              'page-break-after': 'always',
              margin: '0',
              padding: '0'
            })
            printContainer.append(pageClone)
          })
          
          // 添加到body
          body.append(printContainer)
          
          // 打印后恢复
          const restorePage = () => {
            try {
              printContainer.remove()
              body.children().show()
              
              // 恢复原始样式
              $('.print-page').each(function(index) {
                if (originalStyles[index]) {
                  $(this).attr('style', originalStyles[index])
                } else {
                  $(this).css('display', 'none')
                }
              })
              
              if (window.matchMedia) {
                window.matchMedia('print').removeListener(handlePrintChange)
              }
              
              resolve()
            } catch (error) {
              reject(error)
            }
          }
          
          const handlePrintChange = (mql) => {
            if (!mql.matches) {
              restorePage()
            }
          }
          
          // 添加打印状态监听
          if (window.matchMedia) {
            window.matchMedia('print').addListener(handlePrintChange)
          }
          
          // 设置超时恢复（备用）
          setTimeout(restorePage, 5000)
          
          // 触发打印
          setTimeout(() => {
            window.print()
          }, 500);
          
          
        } catch (error) {
          reject(error)
        }
      })
    },
    executePrint2() {
       console.log('找到的 .print-page2 数量:', $('.print-page2').length)
      return new Promise((resolve, reject) => {
        this.historyVisible = false
        try {
          const originalStyles = {}
          $('.print-page2').each(function(index) {
            originalStyles[index] = $(this).attr('style')
          })
          
          const body = $('body')
          
          // 隐藏原始内容
          body.children().hide()
          
          // 创建打印容器
          const printContainer = $('<div class="print-container"></div>')
          
          // 复制所有打印页面到打印容器
          $('.print-page2').each(function() {
            const pageClone = $(this).clone()
            pageClone.css({
              display: 'block',
              width: '20cm',
              height: '11.5cm',
              'background-color': '#fff',
              'page-break-after': 'always',
              margin: '0',
              padding: '0'
            })
            printContainer.append(pageClone)
          })
          
          // 添加到body
          body.append(printContainer)
          
          // 打印后恢复
          const restorePage = () => {
            try {
              printContainer.remove()
              body.children().show()
              
              // 恢复原始样式
              $('.print-page2').each(function(index) {
                if (originalStyles[index]) {
                  $(this).attr('style', originalStyles[index])
                } else {
                  $(this).css('display', 'none')
                }
              })
              
              if (window.matchMedia) {
                window.matchMedia('print').removeListener(handlePrintChange)
              }
              
              resolve()
            } catch (error) {
              reject(error)
            }
          }
          
          const handlePrintChange = (mql) => {
            if (!mql.matches) {
              restorePage()
            }
          }
          
          // 添加打印状态监听
          if (window.matchMedia) {
            window.matchMedia('print').addListener(handlePrintChange)
          }
          
          // 设置超时恢复（备用）
          setTimeout(restorePage, 5000)
          
          // 触发打印
          setTimeout(() => {
            window.print()
          }, 1000);
          
          
        } catch (error) {
          reject(error)
        }
      })
    },
    // 记录打印次数
    clickadjust(){
      const orderNumbers = this.multipleSelection.map(item => item.TaskAID)
        
        if (orderNumbers.length === 0) {
          return
        }

        const params = [
          ['订单编号列表', orderNumbers.join(',')],
          ['派工操作人', this.$store.state.user.name]
        ]
        const Data = this.CreateData('12', '计划排产_派工', params)
        const response = this.ExecDatabase(Data)
        console.log(this.multipleSelection)
        this.multipleSelection.forEach(item => {
          var arr = item.工序名称.split(',')
          var lastprocess = arr[arr.length - 1] 
          var arrid= item.TaskAID.split(',')
          var lastprocessid = arrid[arrid.length - 1] 
          console.log(item.派工状态)
          if(item.派工状态 < 1){
          console.log(111)
            postB1(
              "/PurchaseRequests",
              {
                "ReqType": 12,
                "Requester": "SAPJK001",
                "PriceMode":"G",
                "RequesterBranch": -2,
                "RequesterDepartment": -2,
                "DocDate": this.formatDate(this.currentTime),
                "DocDueDate": this.formatDate(this.currentTime),
                "TaxDate": this.formatDate(this.currentTime),
                "RequriedDate":this.formatDate(this.currentTime),
                "Comments": " ",
                "DocumentLines": [
                    {
                        "ItemCode": '108-001',
                        "Quantity": 1,
                        "WarehouseCode": "W03",
                        "U_WWOworID":item.订单号,
                        "U_WWOrst":item.工序名称,
                        "Quantity":item.指派数量,
                        "U_WWOrstHS":lastprocess,
                        "U_WWOrstID":lastprocessid
                    }
                ]
              }
            )
              this.$message.success("同步成功");
              this.searchTable()
          }
        });
        
    },
    async recordPrintCount() {
      try {
        const orderNumbers = this.multipleSelection.map(item => item.TaskAID)
        
        if (orderNumbers.length === 0) {
          return
        }

        const param = [
          ['订单编号列表', orderNumbers.join(',')]
        ]
        
        const Data = this.CreateData('11', '生产管理_外协管理_更新打印次数', param)
        const response = await this.ExecDatabase(Data)
        this.searchTable()
        if (response && response.success) {
          console.log(`成功更新${orderNumbers.length}个订单的打印次数`)
          // 刷新表格数据
          
        } else {
          console.warn('更新打印次数失败', response)
        }
      } catch (error) {
        console.error('记录打印次数失败:', error)
        // 这里不显示错误消息，避免影响用户体验
      }
    },
    textForm(){
      var row = this.selectedRow
      try {
        const param = [['订单编号列表', row.TaskAID]]
        param.push(["外协备注",this.textcontent])
        param.push(["单重",this.textweight])
        param.push(["打印数量",this.textsum])
        const Data = this.CreateData('11', '生产管理_外协管理_更新备注', param)
        const response =  this.ExecDatabase(Data)
        this.searchTable()
        this.textVisible = false
        this.$message.success("操作成功");
      } catch (error) {
        console.error('记录失败:', error)
        // 这里不显示错误消息，避免影响用户体验
      }
    },
    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
    },
    getitemdraw(row) {
      var param = []
      param[0] = ['物料编号',row.产品编码]
      var Data = this.CreateData('11', '工艺管理_图纸维护_查看图纸', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response)
        if (response.data.length > 0) {
          var pdfSrc =""+this.downPDF+""+ response.data[0].uid+".pdf"
            window.open(pdfSrc,'_blank')
            // this.seeVisible = true
            // this.$nextTick(() => {
            //     seepdf(pdfSrc,'see')
                    
            // })
        }else{
          this.$message.error('未上传图纸')
        }
      })
    },
    getitemdraw2(row) {
      var param = []
      param[0] = ['物料编号',row.产品编码]
      var Data = this.CreateData('11', '工艺管理_工艺维护_查看图纸', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response)
        if (response.data.length > 0) {
          var pdfSrc =""+this.downPDF+""+ response.data[0].uid+".pdf"
            window.open(pdfSrc,'_blank')
            // this.seeVisible = true
            // this.$nextTick(() => {
            //     seepdf(pdfSrc,'see')
                    
            // })
        }else{
          this.$message.error('未上传图纸')
        }
      })
    },
    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.workstate])
      param.push(["发料状态",this.issuingstate])
      param.push(["订单状态",this.orderstate])
      // param.push(["执行状态",this.dostate])
      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 orderNo = item.订单号;
  //   if (!groupedByOrder[orderNo]) {
  //     groupedByOrder[orderNo] = [];
  //   }
  //   groupedByOrder[orderNo].push(item);
  // });
  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.外协分组) {
        currentGroup.push(currentItem);
      } else {
        // 不连续，处理当前组并开始新组
        const mergedItem = this.mergeGroup(currentGroup);
        // 应用执行状态筛选
        if (this.shouldIncludeByExecutionStatus(mergedItem)) {
          mergedData.push(mergedItem);
          // 存储合并数据对应的原始数据组
          this.mergedDataMap.set(mergedItem.uniqueKey, currentGroup);
        }
        currentGroup = [currentItem];
      }
    }
    
    // 处理最后一组
    if (currentGroup.length > 0) {
      const mergedItem = this.mergeGroup(currentGroup);
      // 应用执行状态筛选
      if (this.shouldIncludeByExecutionStatus(mergedItem)) {
        mergedData.push(mergedItem);
        // 存储合并数据对应的原始数据组
        this.mergedDataMap.set(mergedItem.uniqueKey, currentGroup);
      }
    }
  });

  this.mergedTableData = mergedData;
},

// 新增：根据执行状态筛选数据（纯前端筛选）
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
    },
    funreceiveNum(num) {
      this.receiveNum = num;
    },
    funtextcontent(num) {
      this.textcontent = num;
    },
    funtextweight(num) {
      this.textweight = num;
    },
    funtextsum(num) {
      this.textsum = num;
    },
    fundoNum(num) {
      this.doNum = num;
    },
    receive(row) {
      if(!row){
        this.$message.warning("请先选择一行数据");
        return;
      }
      this.receiveVisible = true;
      const param = [];
      // 获取订单行号最大的TaskAID
      const maxTaskAID = this.getMaxOrderLineTaskAID(row);
      const minTaskAID = this.getMinOrderLineTaskAID(row);
      param.push(["minTaskAID", minTaskAID]);
      param.push(["maxTaskAID", maxTaskAID]);
      
      var Data = this.CreateData("11", "生产管理_外协管理_外协发料查询", param);
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.receiveData = response.data[0];
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getdetail(row) {
      if(!row){
        this.$message.warning("请先选择一行数据");
        return;
      }
      
      this.dohistoryVisible = true;
      const param = [];
      
      // 获取订单行号最大的TaskAID
      const maxTaskAID = this.getMaxOrderLineTaskAID(row);
      param.push(["maxTaskAID", maxTaskAID]);
      var Data = this.CreateData("11", "生产管理_外协管理_查询外协历史记录", param);
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.dohistoryData = response.data;
          }
          console.log(this.dohistoryData)
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getQulityInspectiondetail(row) {
      if(!row){
        this.$message.warning("请先选择一行数据");
        return;
      }
      
      this.QulityInspectionVisible = true;
      const param = [];
      
      // 获取订单行号最大的TaskAID
      const maxTaskAID = this.getMaxOrderLineTaskAID(row);
      param.push(["maxTaskAID", maxTaskAID]);
      var Data = this.CreateData("11", "生产管理_外协管理_查询质检记录", param);
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.QulityInspectionData = response.data;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    doreceive(row) {
      if(!row){
        this.$message.warning("请先选择一行数据");
        return;
      }
      
      this.doVisible = true;
      const param = [];
      
      // 获取订单行号最大的TaskAID
      const maxTaskAID = this.getMaxOrderLineTaskAID(row);
      const minTaskAID = this.getMaxOrderLineTaskAID(row);
      param.push(["minTaskAID", minTaskAID]);
      param.push(["maxTaskAID", maxTaskAID]);
      
      var Data = this.CreateData("11", "生产管理_外协管理_外协发料查询", param);
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.doData = response.data[0];
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    receiveForm() {
      const params = [];
      var row = this.selectedRow;
      
      if (!this.receiveNum) {
        this.$message.error('数量输入错误1')
        return
      }
      if (this.receiveNum > this.receiveData.指派数量 - this.receiveData.收料数量) {
        this.$message.error('数量输入错误2')
        return
      }
      console.log(this.receiveData.上序订单行号)
      if (this.receiveNum > this.receiveData.上序合格数 & this.receiveData.上序订单行号>1) {
        this.$message.error('数量输入错误3')
        return
      }
      if (Number(this.receiveNum) + this.receiveData.收料数量 > this.receiveData.上序合格数 & this.receiveData.上序订单行号>1 ) {
        this.$message.error('数量输入错误4')
        return
      }
      this.receiveVisible = false;
      // 获取订单行号最大的TaskAID
      const maxTaskAID = this.getMaxOrderLineTaskAID(row);
      params.push(["TaskAID", maxTaskAID]);
      params.push(["optor", this.$store.state.user.name]);
      params.push(["recievCount", this.receiveNum]);
      params.push(["单重", row.单重]);
      params.push(["备注", row.外协备注]);
      console.log(params)
      const Data = this.CreateData(
        "11",
        "生产管理_外协管理_外协发料保存",
        params
      );
      this.ExecDatabase(Data)
        .then(() => {
          this.$message.success("发料操作成功");
          this.receiveVisible = false;
          this.receiveNum = 0;
          this.searchTable();
        })
        .catch(() => {
          this.$message.error("保存失败");
        })
        .finally(() => {});
    },
    doForm() {
      const params = [];
      var row = this.selectedRow;
      
      if (!this.doNum) {
        this.$message.error('数量输入错误')
        return
      }
      if (this.doNum > this.doData.收料数量 - this.doData.完成数量) {
        this.$message.error('数量输入错误')
        return
      }
      this.doVisible = false;
      // 获取订单行号最大的TaskAID
      const maxTaskAID = this.getMaxOrderLineTaskAID(row);
      params.push(["TaskAID", maxTaskAID]);
      params.push(["optor", this.$store.state.user.name]);
      params.push(["recievCount", this.doNum]);
      const Data = this.CreateData(
        "11",
        "生产管理_外协管理_外协收料保存",
        params
      );
      this.ExecDatabase(Data)
        .then(() => {
          this.$message.success("收货操作成功");
          this.doVisible = false;
          this.doNum = 0;
          this.searchTable();
        })
    },
    
    async updateload2(data){
      
    },
  }
}
</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>