<template>
  <div>
    <div class="headerbox">
      <!-- <div class="logo"></div> -->
      <!-- <div style="width: 80%; height: 70px; margin-top: 8px">
        <el-form
          ref="DoingDataForm"
          :model="DoingData"
          label-width="140px"
          size="mini"
          :inline="true"
        >
          <el-form-item label="工位名称">
            <el-select v-model="Doing" clearable @change="Doingform">
              <el-option
                v-for="item in Doingoptions"
                :key="item.指南工位号"
                :label="item.指南工位号"
                :value="item.工位号"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="当前订单号">
            <el-input v-model="DoingData.订单编号" :rows="2" readonly />
          </el-form-item>
          <el-form-item label="合同号">
            <el-input v-model="DoingData.合同号" :rows="2" readonly />
          </el-form-item>
          <el-form-item label="零件编号">
            <el-input v-model="DoingData.物料编号" :rows="2" readonly />
          </el-form-item>
          <el-form-item label="分配数">
            <el-input v-model="DoingData.指派数量" :rows="2" readonly />
          </el-form-item>
          <el-form-item label="已完成">
            <el-input v-model="DoingData.完成数量" :rows="2" readonly />
          </el-form-item>
        </el-form>
      </div> -->

      <!-- <div class="logname">操作人：{{ logusername() }}</div> -->
    </div>
    <div style="display: flex">
      <el-card style="width: 90%">
        <div class="search-container">
          <span class="show-text">任务ID:</span>
          <el-input
            v-model="TaskAID"
            placeholder="请输入任务ID"
            clearable
            style="width: 150px; margin-right: 10px"
            @change="searchTable()"
          />
          <span class="show-text">生产订单:</span>
          <el-input
            v-model="orderNo2"
            placeholder="请输入生产订单"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <span class="show-text">物料编码:</span>
          <el-input
            v-model="productCode2"
            placeholder="请输入零件编码"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <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="salenum"
            placeholder="请输入销售订单"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <!-- <span class="show-text">计划开工:</span>
          <el-date-picker
            v-model="completionTime"
            :clearable="false"
            end-placeholder="结束时间"
            format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始时间"
            style="width: 280px; vertical-align: top"
            type="datetimerange"
            value-format="yyyy-MM-dd"
          /> -->
          <span class="show-text">任务状态:</span>
          <el-select
            v-model="productionStatus2"
            clearable
            placeholder="请选择状态"
            style="width: 150px; margin-right: 10px"
          >
            <el-option label="全部" value="10" />
            <el-option label="待执行" value="0" />
            <el-option label="可执行" value="1" />
            <el-option label="已开工" value="2" />
            <el-option label="已完成" value="4" />
          </el-select>
          <el-button
            :disabled="loading"
            icon="el-icon-search"
            plain
            type="primary"
            @click="searchTable()"
            >查询</el-button
          >
          <el-checkbox-group v-model="Doing" @change = "Doingform" style="margin: 20px;">
            <el-checkbox  v-for="item in Doingoptions" :key="item.工位号" :label="item.指南工位号" :value="item.工位号"> </el-checkbox>
          </el-checkbox-group>
          
        </div>
        <el-table
          v-loading="loading"
          :data="tableData"
          :height="'52vh'"
          border
          element-loading-background="rgba(0, 0, 0, 0.2)"
          element-loading-spinner="el-icon-loading"
          highlight-current-row
          size="mini"
          style="width: 100%; margin-top: 20px"
          tooltip-effect="dark"
          @row-click="handleRowClick"
          :row-class-name="tableRowClassName"
        >
          <!-- <el-table-column
            align="center"
            label="序号"
            type="index"
            width="50"
            fixed
          /> -->
          <el-table-column
            align="center"
            prop="订单号"
            label="生产订单"
            width="80"
            fixed
          />
          
          <el-table-column
            align="center"
            prop="合同号"
            label="销售订单"
            width="80"
            fixed
          />
          <el-table-column
            align="center"
            prop="零件名称"
            label="物料名称"
            width="100"
          />
          <el-table-column
            align="center"
            prop="零件编码"
            label="物料编码"
            width="100"
          />
          <el-table-column align="center" label="顺序" width="50">
            <template slot-scope="scope">{{ scope.row.订单行号 }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="工序名称"
            label="工序名称"
            width="80"
          />
          
          
          <el-table-column
            align="center"
            prop="分配数"
            label="分配数"
            width="60"
          />
          <el-table-column
            align="center"
            prop="上序合格数"
            label="上序合格数"
            width="60"
          />
          
          <el-table-column align="center" label="加工状态" width="80">
            <template slot-scope="scope">
              <div
                :style="getScoreStyle(scope.row.加工状态)"
                class="score-cell"
              >
                {{ scope.row.加工状态 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="收料状态" width="80">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.收料 > 0
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="加急数量"
            width=" 120"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="Urgent(scope.row)">{{scope.row.加急总数}}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="下序名称"
            label="下序名称"
            width="80"
          />
          <!-- <el-table-column align="center" label="加急" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.加急 === '加急'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column> -->
          <el-table-column align="center" label="优先" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.优先 === '是'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="首检" label="首检" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.首检 === 'OK'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="序检" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.序检 === 'OK'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column>
          <!-- <el-table-column
            align="center"
            prop="订单拆分内码"
            label="内码"
            width="50"
          /> -->
          <el-table-column
            align="center"
            prop="派工特殊说明"
            label="备注"
            width="120"
          />
          <el-table-column
            align="center"
            prop="指派对象"
            label="指派对象"
            width="80"
          />
          
          
          <el-table-column
            align="center"
            prop="完成数量"
            label="完成数"
            width="60"
          />
          <el-table-column
            align="center"
            label="任务状态"
            width="80"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <div
                :style="getScoreStyle(scope.row.任务状态)"
                class="score-cell"
              >
                {{ scope.row.任务状态 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="计划号"
            label="计划号"
            width="80"
          />
          <el-table-column align="center" label="计划开始" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.计划开始)}}</template>
          </el-table-column>
          <el-table-column align="center" label="计划完成" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.计划完成)}}</template>
          </el-table-column>
          <el-table-column align="center" label="开工时间" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.开工时间)}}</template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="收料"
            label="收料数"
            width="60"
          />
        </el-table>
      </el-card>
      <div style="width: 10%">
        <!--     <div class="upbox">
          <el-radio
            class="workstatus"
            v-model="radio"
            label="1"
            @input="filterstate"
            size="medium "
            >全部</el-radio
          >
           <el-radio class="workstatus" v-model="radio" label="2" @input = "filterstate">加工状态</el-radio> 
          <el-radio
            class="workstatus"
            v-model="radio"
            label="2"
            @input="filterstate"
            >首检</el-radio
          >
          <el-radio
            class="workstatus"
            v-model="radio"
            label="3"
            @input="filterstate"
            >序检</el-radio
          >
          <el-radio
            class="workstatus"
            v-model="radio"
            label="4"
            @input="filterstate"
            >优先</el-radio
          >
          <el-radio
            class="workstatus"
            v-model="radio"
            label="5"
            @input="filterstate"
            >加急</el-radio
          >
        </div> -->
        
        <div class="bottombox">
          <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="assiststart()">
        辅助开始
      </div>
      <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="assistend()">
        辅助结束
      </div>
      <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="workStart()">
        开始加工
      </div>
      <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="pause()">
        暂停
      </div>
      <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="prodReport()">
        报工结束
      </div>
      <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="receive()">
        收料
      </div>
        </div>
        <!-- <div class="downbox">
          <div>加工进度：{{ this.taskprogress }}%</div>
          <div>累计用时：{{ this.startworktime }}</div>
          <div>当前状态：{{ this.taskstate }}</div>
        </div> -->
      </div>
    </div>
    <div class="footbox">
      <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="firstCheck()"
          >
            首检自检
          </div>
          <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="processCheck()"
          >
            序检自检
          </div>
          <div class="grid-btn" style="margin-left: 50px" @click="receiveCheck()">收检</div>
          <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="checkRecord()"
          >
            检验记录
          </div>
          <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="getprocessdraw()"
          >
            工艺图纸
          </div>
          <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="getitemdraw()"
          >
            零件图纸
          </div>
      
    </div>
    <div class="footbox">
      <div class="grid-btn" style="margin-left: 50px" @click="ReturnWarehouse()">退库</div>
      <div class="grid-btn" style="margin-left: 50px" @click="MaterialRequisition()">领料</div>
      <div class="grid-btn" style="margin-left: 50px" @click="Abnormalcontrol()">异常管控</div>
      <!-- <div class="grid-btn" style="margin-left: 50px">操作日志</div> -->
      <div class="grid-btn" style="margin-left: 50px" @click="abnormal()">
        异常工时
      </div>
    </div>
    <!-- 辅助结束弹框 -->
    <el-dialog
      :visible.sync="assistendVisible"
      title="辅助结束"
      width="600px"
      center
    >
      <el-form
        ref="assistendForm"
        :model="assistendData"
        label-width="140px"
        size="mini"
      >
        <el-form-item label="生产订单">
          <el-input v-model="assistendData.订单编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="销售订单">
          <el-input v-model="assistendData.合同号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="零件编码">
          <el-input v-model="assistendData.物料编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="当前时间">
          <el-input v-model="this.currentTime" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="辅助工件">
          <el-input
            v-model="assistNumber"
            type="number"
            @change="funassistNum"
          />
        </el-form-item>
        <el-form-item label="操作工位">
          <el-input v-model="assistendData.指派对象" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="this.$store.state.user.name" :rows="2" readonly />
        </el-form-item>
        
        <el-form-item label="调机人员">
          <el-select v-model="selectedOperators" placeholder="选择人员" 
                filterable style="width: 200px; margin-right: 10px;" @change='funreceiveperson'>
            <el-option v-for="user in userList" :key="user.id" 
                  :label="user.name" :value="user.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assistendVisible = false">取 消</el-button>
        <el-button type="primary" @click="assistendForm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 收料弹框 -->
    <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="workStartVisible"
      title="开始加工"
      width="600px"
      center
    >
      <el-form
        ref="workStartForm"
        :model="workStartData"
        label-width="140px"
        size="mini"
      >
        <el-form-item label="生产订单">
          <el-input v-model="workStartData.订单编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="销售订单">
          <el-input v-model="workStartData.销售订单" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="零件编码">
          <el-input v-model="workStartData.物料编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="当前时间">
          <el-input v-model="this.currentTime" :rows="2" readonly />
        </el-form-item>
        <!-- <el-form-item label="辅助工件">
          <el-input
            v-model="workStartData.指派数量"
            type="number"
            @change="funworkStartNum"
          />
        </el-form-item> -->
        <el-form-item label="操作工位">
          <el-input v-model="workStartData.指派对象" :rows="2" readonly />
        </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="workStartVisible = false">取 消</el-button>
        <el-button type="primary" @click="workStartForm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 首检自检弹框 -->
    <el-dialog
      :visible.sync="firstCheckVisible"
      ref="firstCheckForm"
      :model="firstCheckNumber"
      label-width="140px"
      title="首检自检"
      style="text-align: center"
      width="60%"
    >
      <el-form
        ref="checkForm"
        :model="firstCheckData"
        label-position="right"
        label-width="140px"
        size="mini"
      >
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料名称</span>
              <span class="info-value">{{ firstCheckData.物料描述 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">销售订单</span>
              <span class="info-value">{{ firstCheckData.合同号 }}</span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料编号</span>
              <span class="info-value">{{ firstCheckData.物料编号 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">生产订单</span>
              <span class="info-value">{{ firstCheckData.订单编号 }}</span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">工序名称</span>
              <span class="info-value">{{ firstCheckData.工序名称 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检测数量</span>
              <span class="info-value">
                <el-input
                  v-model="firstCheckData.检测数量"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">合格数</span>
              <span class="info-value">
                <el-input
                  v-model="firstCheckData.合格数"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">不合格数</span>
              <span class="info-value">
                <el-input
                  v-model="unqualifiedCount"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">计划生产数</span>
              <span class="info-value">
                {{ firstCheckData.计划数量 }}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label"></span>
              <span class="info-value"></span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">检验人</span>
              <span class="info-value">{{ firstCheckData.检验人 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检验时间</span>
              <span class="info-value">
                <el-date-picker
                  v-model="firstCheckData.检验时间"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <!-- 当前检测信息显示 -->
          <div style="margin: 10px 0; font-weight: bold">
            当前检测第 {{ currentPage }} 件 / 共
            {{ firstCheckData.检测数量 }} 件
          </div>

          <!-- 检验表格 -->
          <div v-if="tableData2.length > 0">
            <el-table
              v-loading="loading"
              :data="getCurrentPageData()"
              :height="'250px'"
              border
              element-loading-background="rgba(0, 0, 0, 0.2)"
              element-loading-spinner="el-icon-loading"
              highlight-current-row
              size="mini"
              style="width: 100%; margin-top: 20px"
              tooltip-effect="dark"
            >
              <el-table-column
                prop="检测项目"
                label="检测项目"
                width="150"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.检测项目 }}
                </template>
              </el-table-column>
              <el-table-column
                label="上限值"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.上限值 }}
                </template>
              </el-table-column>
              <el-table-column
                label="下限值"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.下限值 }}
                </template>
              </el-table-column>
              <el-table-column
                label="测量单位"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.测量单位 }}
                </template>
              </el-table-column>
              <el-table-column
                label="检验比例"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.检验比例 }}
                </template>
              </el-table-column>
              <el-table-column
                label="检具"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.检具 }}
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.备注 }}
                </template>
              </el-table-column>

              <el-table-column
                prop="实测值"
                label="实测值"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.实测值"
                    size="mini"
                    @input="
                      handleRealTimeInput(
                        scope.row,
                        scope.$index,
                        currentPage - 1
                      )
                    "
                    @blur="
                      handleInputBlur(scope.row, scope.$index, currentPage - 1)
                    "
                  />
                  <div style="font-size: 10px; color: #999">
                    {{ scope.row.检测项编号 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="判定"
                label="判定"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <el-radio-group
                    v-model="scope.row.检测结果"
                    size="mini"
                    @change="updateInspectionData(scope.row, currentPage - 1)"
                  >
                    <el-radio label="1">合格</el-radio>
                    <el-radio label="0">不合格</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>
      <div class="dialog-footer" style="padding: 10px">
        <div
          style="
            margin-bottom: 20px;
            display: flex;
            justify-self: center;
            align-items: center;
          "
        >
          <el-button
            type="primary"
            @click="prevPage"
            :disabled="currentPage <= 1"
            >上一个</el-button
          >
          <el-button type="primary" @click="nextPage">下一个</el-button>

          <el-button
            type="danger"
            @click="confirmDeleteCurrentPage"
            :disabled="firstCheckData.检测数量 <= 1"
            style="min-width: 120px"
            >删除当前记录</el-button
          >
          <el-button @click="firstCheckVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 序检自检弹框 -->
    <el-dialog
      :visible.sync="processCheckVisible"
      ref="processCheckForm"
      :model="processCheckData"
      label-width="140px"
      title="序检自检"
      style="text-align: center"
      width="60%"
    >
      <el-form
        ref="processCheckForm"
        :model="processCheckData"
        label-position="right"
        label-width="140px"
        size="mini"
      >
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料名称</span>
              <span class="info-value">{{ processCheckData.物料描述 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">销售订单</span>
              <span class="info-value">{{ processCheckData.合同号 }}</span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料编号</span>
              <span class="info-value">{{ processCheckData.物料编号 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">生产订单</span>
              <span class="info-value">{{ processCheckData.订单编号 }}</span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">工序名称</span>
              <span class="info-value">{{ processCheckData.工序名称 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检测数量</span>
              <span class="info-value">
                <el-input
                  v-model="processCheckData.检测数量"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">合格数</span>
              <span class="info-value">
                <el-input
                  v-model="processCheckData.合格数"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">不合格数</span>
              <span class="info-value">
                <el-input
                  v-model="betweenProcessUnqualifiedCount"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">计划生产数</span>
              <span class="info-value">
                {{ processCheckData.计划数量 }}
              </span>
            </div>
            <div class="info-item"></div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">检验人</span>
              <span class="info-value">{{ processCheckData.检验人 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检验时间</span>
              <span class="info-value">
                <el-date-picker
                  v-model="processCheckData.检验时间"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <!-- 当前检测信息显示 -->
          <div style="margin: 10px 0; font-weight: bold">
            当前检测第 {{ betweenProcessCurrentPage }} 件 / 共
            {{ processCheckData.检测数量 }} 件
          </div>

          <!-- 检验表格 -->
          <div v-if="betweenProcessTableData.length > 0">
            <el-table
              v-loading="loading"
              :data="getBetweenProcessCurrentPageData()"
              :height="'250px'"
              border
              element-loading-background="rgba(0, 0, 0, 0.2)"
              element-loading-spinner="el-icon-loading"
              highlight-current-row
              size="mini"
              style="width: 100%; margin-top: 20px"
              tooltip-effect="dark"
            >
              <el-table-column
                prop="检测项目"
                label="检测项目"
                width="150"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.检测项目 }}
                </template>
              </el-table-column>
              <el-table-column
                label="上限值"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.上限值 }}
                </template>
              </el-table-column>
              <el-table-column
                label="下限值"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.下限值 }}
                </template>
              </el-table-column>
              <el-table-column
                label="检验比例"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.检验比例 }}
                </template>
              </el-table-column>
              <el-table-column
                label="检具"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.检具 }}
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.备注 }}
                </template>
              </el-table-column>

              <el-table-column
                prop="实测值"
                label="实测值"
                width="100"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.实测值"
                    size="mini"
                    @input="
                      handleBetweenProcessRealTimeInput(
                        scope.row,
                        scope.$index,
                        betweenProcessCurrentPage - 1
                      )
                    "
                    @blur="
                      handleBetweenProcessRealTimeInput(
                        scope.row,
                        scope.$index,
                        betweenProcessCurrentPage - 1
                      )
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="判定"
                label="判定"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <el-radio-group
                    v-model="scope.row.检测结果"
                    size="mini"
                    @change="
                      updateBetweenProcessInspectionData(
                        scope.row,
                        betweenProcessCurrentPage - 1
                      )
                    "
                  >
                    <el-radio label="1">合格</el-radio>
                    <el-radio label="0">不合格</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>
      <div class="dialog-footer" style="padding: 10px">
        <div
          style="
            margin-bottom: 20px;
            display: flex;
            justify-self: center;
            align-items: center;
          "
        >
          <el-button
            type="primary"
            @click="betweenProcessPrevPage"
            :disabled="betweenProcessCurrentPage <= 1"
            >上一个</el-button
          >
          <el-button type="primary" @click="betweenProcessNextPage"
            >下一个</el-button
          >
          <el-button
            type="primary"
            @click="submitBetweenProcessQualityData"
            style="min-width: 120px"
            >保存当前记录</el-button
          >
          <el-button
            type="danger"
            @click="confirmDeleteBetweenProcessCurrentPage"
            :disabled="processCheckData.检测数量 <= 1"
            style="min-width: 120px"
            >删除当前记录</el-button
          >
          <el-button @click="processCheckVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 收检弹框 -->
    <el-dialog
      :visible.sync="receiveCheckVisible"
      ref="receiveCheckForm"
      :model="receiveCheckData"
      label-width="140px"
      title="收检"
      style="text-align: center"
      width="60%"
    >
      <el-form
        ref="receiveCheckForm"
        :model="receiveCheckData"
        label-position="right"
        label-width="140px"
        size="mini"
      >
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料名称</span>
              <span class="info-value">{{ receiveCheckData.零件名称 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">销售订单</span>
              <span class="info-value">{{ receiveCheckData.内部合同号 }}</span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料编号</span>
              <span class="info-value">{{ receiveCheckData.零件编码 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">生产订单</span>
              <span class="info-value">{{ receiveCheckData.计划号 }}</span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">工序名称</span>
              <span class="info-value">{{ receiveCheckData.工序名称 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检测数量</span>
              <span class="info-value">
                <el-input-number
                  v-model="receiveCheckData.检测数量"
                  size="mini"
                  :min="0"
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <!-- 合格数 -->
            <div class="info-item">
              <span class="info-label">合格数</span>
              <span class="info-value">
                <el-input-number
                  v-model="receiveCheckData.合格数"
                  size="mini"
                  :min="0"
                  style="width: 200px"
                />
              </span>
            </div>
            <!-- 不合格数 -->
            <div class="info-item">
              <span class="info-label">不合格数</span>
              <span class="info-value">
                <el-input-number
                  v-model="receiveCheckData.不合格数"
                  size="mini"
                  readonly
                  :min="0"
                  style="width: 200px"
                />
              </span>
            </div>
          </div>

          <div class="info-container">
            <div class="info-item">
              <span class="info-label">检验人</span>
              <span class="info-value">{{ receiveCheckData.检验人 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检验时间</span>
              <span class="info-value">
                <el-date-picker
                  v-model="receiveCheckData.检验时间"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">计划生产数</span>
              <span class="info-value">
                {{ receiveCheckData.计划生产数 }}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">已检验数量</span>
              <span class="info-value">
                {{ receiveCheckData.已检验数量 }}
              </span>
            </div>
          </div>
          <div class="info-container">
            <span class="info-label">备注</span>
            <span class="info-value">
              <el-input
                v-model="receiveCheckData.备注"
                type="textarea"
                :rows="1"
                resize="vertical"
                size="mini"
                style="width: 100%"
              />
            </span>
          </div>
        </div>
      </el-form>
      <div class="dialog-footer" style="padding: 10px">
        <div
          style="
            margin-bottom: 20px;
            display: flex;
            justify-self: center;
            align-items: center;
          "
        >
          <el-button
            type="primary"
            @click="submitReceiveCheckData"
            style="min-width: 120px"
            >确定</el-button
          >
          <el-button @click="receiveCheckVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 检验记录 -->
    <el-dialog
      :visible.sync="checkRecordVisible"
      label-width="140px"
      title="检验记录"
      width="60%"
    >
      <!-- <div style="margin-left: 0px">
        <span class="show-text">生产订单:</span>
        <el-input
          v-model="orderNo2"
          placeholder="请输入生产订单"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">零件编码:</span>
        <el-input
          v-model="productCode2"
          placeholder="请输入零件编码"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">工序名称:</span>
        <el-select
          v-model="process"
          placeholder="请选择工序"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in processList2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span class="show-text">质检类型:</span>
        <el-select
          v-model="type"
          placeholder="请选择类型"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            clearable
            filterable
          />
        </el-select>
        <br />
        <br />
        <span class="show-text">检验结果:</span>
        <el-select
          v-model="inspectionResult"
          placeholder="请选择检验结果"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in inspectionResultList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <span class="show-text">检测人:</span>
        <el-select v-model="operationPerson" clearable filterable>
          <el-option
            v-for="item in operationPersonList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <span class="show-text">操作日期:</span>
        <el-date-picker
          v-model="operationDate"
          :clearable="false"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始时间"
          style="width: 280px; vertical-align: top"
          type="datetimerange"
          value-format="yyyy-MM-dd"
        />
        <el-button
          :disabled="loading"
          icon="el-icon-search"
          plain
          type="primary"
          @click="loadCheckRecordData()"
          >查询</el-button
        >
      </div> -->
      <el-table
        v-loading="checkRecordLoading"
        :data="checkRecordTableData"
        :height="'58vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
        @row-click="handleCheckRecordRowClick"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="50"
          fixed
        />
        <el-table-column
          align="center"
          prop="计划号"
          label="生产订单"
          width="70"
          fixed
        />
        <el-table-column
          align="center"
          prop="零件编码"
          label="物料编码"
          width="200"
        />
        <el-table-column
          align="center"
          prop="零件名称"
          label="物料名称"
          width="220"
        />
        <el-table-column
          align="center"
          prop="工序名称"
          label="工序名称"
          width="100"
        />
        <el-table-column
          align="center"
          prop="质检类型"
          label="质检类型"
          width="90"
        />
        <el-table-column
          align="center"
          prop="计划生产数"
          label="计划生产数"
          width="90"
        />
        <el-table-column
          align="center"
          prop="检验数量"
          label="检验数量"
          width="90"
        />
        <el-table-column
          align="center"
          prop="检验结果"
          label="检验结果"
          width="90"
        />
        <el-table-column
          align="center"
          prop="合格数"
          label="合格数量"
          width="90"
        />
        <el-table-column
          align="center"
          prop="不合格数"
          label="不合格数量"
          width="90"
        />
        <el-table-column
          align="center"
          prop="检测人"
          label="检测人"
          width="90"
        />
        <el-table-column
          align="center"
          prop="检测时间"
          label="检测时间"
          width="200"
        />
        <el-table-column align="center" width="150" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="viewInspectionDetail(scope.row)"
              >检验详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 检验详情弹窗 -->
    <el-dialog
      :visible.sync="checkDetailedVisible"
      label-width="140px"
      :title="'生产订单检验详情  ' + currentInspectionRecord.计划号"
      width="60%"
      style="text-align: center"
    >
      <div class="inspection-info">
        <el-row :gutter="20">
          <el-col :span="8"
            ><strong>物料名称:</strong>
            {{ currentInspectionRecord.零件名称 }}</el-col
          >
          <el-col :span="8"
            ><strong>物料编码:</strong>
            {{ currentInspectionRecord.零件编码 }}</el-col
          >
          <el-col :span="8"
            ><strong>工序名称:</strong>
            {{ currentInspectionRecord.工序名称 }}</el-col
          >
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="8"
            ><strong>检验数量:</strong>
            {{ currentInspectionRecord.检验数量 }}</el-col
          >
          <el-col :span="8"
            ><strong>合格数:</strong>
            {{ currentInspectionRecord.合格数 }}</el-col
          >
          <el-col :span="8"
            ><strong>不合格数:</strong>
            {{ currentInspectionRecord.不合格数 }}</el-col
          >
        </el-row>
      </div>

      <el-table
        v-loading="loading"
        :data="checkDetailedTableData"
        :height="'50vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
        @row-click="handleInspectionPartRowClick"
      >
        <el-table-column align="center" label="序号" type="index" width="60" />
        <el-table-column
          align="center"
          prop="当前检测零件编号"
          label="检测零件编号"
          width="120"
        />
        <el-table-column
          align="center"
          prop="检测结果描述"
          label="检测结果"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.检测结果 === 1 ? 'success' : 'danger'"
              size="mini"
            >
              {{ scope.row.检测结果描述 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="检测人"
          label="检测人"
          width="100"
        />
        <el-table-column
          align="center"
          prop="检测时间"
          label="检测时间"
          width="180"
        />
        <el-table-column
          align="center"
          prop="零件编号"
          label="零件编号"
          width="200"
        />
        <el-table-column align="center" label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click.stop="Detailed(scope.row)"
            >
              检测详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 详情弹窗 -->
    <el-dialog
      :visible.sync="DetailedVisible"
      label-width="140px"
      title="检测详情"
      width="60%"
      style="text-align: center"
    >
      <el-table
        v-loading="loading"
        :data="inspectionDetailTableData"
        :height="'60vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
      >
        <el-table-column align="center" label="序号" type="index" width="60" />
        <el-table-column
          align="center"
          prop="检测项目"
          label="检测项目"
          width="200"
        />
        <el-table-column
          align="center"
          prop="理论值"
          label="理论值"
          width="100"
        />
        <el-table-column
          align="center"
          prop="上限值"
          label="上限值"
          width="100"
        />
        <el-table-column
          align="center"
          prop="下限值"
          label="下限值"
          width="100"
        />
        <el-table-column
          align="center"
          prop="实测值"
          label="实测值"
          width="100"
        />
        <el-table-column
          align="center"
          prop="测量单位"
          label="单位"
          width="80"
        />
        <el-table-column
          align="center"
          prop="检验比例"
          label="检验比例"
          width="100"
        />
        <el-table-column align="center" prop="检具" label="检具" width="100" />
        <el-table-column
          align="center"
          prop="检测结果描述"
          label="检测结果"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.检测结果 === 1 ? 'success' : 'danger'"
              size="mini"
            >
              {{ scope.row.检测结果描述 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="备注"
          label="备注"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="检测人"
          label="检测人"
          width="100"
        />
        <el-table-column
          align="center"
          prop="检测时间"
          label="检测时间"
          width="180"
        />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="DetailedVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 报工弹窗 -->
    <el-dialog
      :visible.sync="prodReportVisible"
      title="报工"
      width="62%"
      center
    >
      <el-form
        ref="fprodReportForm"
        :model="prodReportDataTop"
        label-width="140px"
        size="mini"
        :inline="true"
      >
        <el-form-item label="生产订单">
          <el-input v-model="prodReportDataTop.订单编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="销售订单">
          <el-input v-model="prodReportDataTop.合同号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="prodReportDataTop.物料编号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="prodReportDataTop.物料编号" :rows="2" readonly />
        </el-form-item>
        <el-table
          v-loading="loading"
          :data="prodReportData"
          :height="'40vh'"
          border
          element-loading-background="rgba(0, 0, 0, 0.2)"
          element-loading-spinner="el-icon-loading"
          size="mini"
          style="width: 100%; background-color: #e4e7ed"
          tooltip-effect="dark"
          ref="multipleTable"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="center" type="selection" width="50" :selectable="() => false" />
          <el-table-column
            align="center"
            label="序号"
            type="index"
            width="50"
          />
          <el-table-column
            align="center"
            prop="工序名称"
            label="工序名称"
            width="120"
          />
          <el-table-column
            align="center"
            prop="指派对象"
            label="指派对象"
            width="100"
          />
          <el-table-column align="center" label="计划完成" width="120">
            <template slot-scope="scope">
              {{ formatDate(scope.row.计划完成时间) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="开工时间" width="120">
            <template slot-scope="scope">
              {{ formatDate(scope.row.计划开始时间) }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="指派数量"
            label="分配数"
            width="80"
          />
          <!-- <el-table-column
            align="center"
            prop="收料数量"
            label="收料数"
            width="80"
          /> -->
          <el-table-column
            align="center"
            prop="完成数量"
            label="完成数"
            width="80"
          />
          <el-table-column
            align="center"
            prop="上序合格数"
            label="上序合格数"
            width="100"
          />
           <el-table-column
            align="center"
            prop="前序不合格数"
            label="前序不合格总数"
            width="120"
          />
           
          <!-- <el-table-column align="center" prop="进度" label="进度" width="80" /> -->
          <el-table-column
            align="center"
            prop="任务状态"
            label="任务状态"
            width="80"
          />
        </el-table>
        <el-form-item label="报工日期">
          <el-date-picker
            v-model="rptDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <!-- <el-form-item label="班次">
          <el-select v-model="shift" clearable>
            <el-option
              v-for="item in shiftoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="当前时间">
          <el-input v-model="currentTime" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="报工数量">
          <el-input
            v-model="proReportNum"
            type="number"
            @change="funproReportNum"
          />
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="this.$store.state.user.name" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="二级工序说明">
          <el-input
            v-model="prodReportDataTop.报工说明"
            type="textarea"
            @change="funrptDesc"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="prodReportVisible = false">取 消</el-button>
        <el-button type="primary" @click="proReportForm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 异常工时 -->
    <el-dialog
      :visible.sync="abnormalVisible"
      title="异常工时"
      width="62%"
      center
    >
      <el-button icon="el-icon-add" plain type="primary" @click="addWorkTimeRecord" style="width: auto;" >新增异常工时</el-button>
      <el-table
        v-loading="loading"
        :data="abnormaltableData"
        :height="'50vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
        @row-click="handleRowClick2"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="50"
          fixed
        />
        <el-table-column
          align="center"
          prop="指派对象"
          label="人员"
          width="80"
          fixed
        />
        <el-table-column
          align="center"
          prop="订单号"
          label="生产订单"
          width="80"
          fixed
        />
        <el-table-column
          align="center"
          prop="操作类别"
          label="类型"
          width="80"
          fixed
        />
        <el-table-column
          align="center"
          prop="产品编码"
          label="物料编码"
          width="120"
        />
        <el-table-column
          align="center"
          prop="产品名称"
          label="物料名称"
          width="120"
        />
        <el-table-column
          align="center"
          prop="工序名称"
          label="工序名称"
          width="80"
        />
        <el-table-column align="center" label="开始时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.开始时间) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="结束时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.结束时间) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="加工工时" width="100">
          <template slot-scope="scope">
            {{ scope.row.总工时 || 0 }}秒
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="最后编辑人"
          label="最后编辑人"
          width="100"
        />
        <el-table-column align="center" label="最后编辑时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.最后编辑时间) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="editTask(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="abnormalVisible = false">取 消</el-button>
        <el-button type="primary" @click="abnormalForm()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog 
      :visible.sync="addRecordDialogVisible" 
      title="新增工时记录" 
      width="700px" 
      center
      :close-on-click-modal="false">
      <el-form ref="addRecordForm" :model="addRecordForm" label-width="120px" size="mini" :rules="addRecordRules">
        <el-form-item label="操作类别" prop="操作类别">
          <el-select v-model="addRecordForm.操作类别" placeholder="请选择操作类别" style="width: 100%">
            <el-option label="加班" value="8" />
            <el-option label="异常" value="9" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="生产订单" prop="订单编号">
          <el-select 
            v-model="addRecordForm.订单编号" 
            placeholder="请选择订单编号" 
            style="width: 100%"
            @change="handleOrderChange"
            filterable
            remote
            :remote-method = "loadOrderList"
            >
            <el-option 
              v-for="order in orderList" 
              :key="order.订单编号" 
              :label="order.订单编号" 
              :value="order.订单编号" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="物料编码">
          <el-input v-model="addRecordForm.产品编码" readonly />
        </el-form-item>
        
        <el-form-item label="物料名称">
          <el-input v-model="addRecordForm.产品名称" readonly />
        </el-form-item>
        
        <el-form-item label="工序名称" prop="工序名称">
          <el-select 
            v-model="addRecordForm.工序名称" 
            placeholder="请选择工序名称" 
            style="width: 100%"
            @change="handletaskChange">
            <el-option 
              v-for="process in processList" 
              :key="process.工艺顺序" 
              :label="process.工序名称" 
              :value="Number(process.TaskAID)" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="指派对象" prop="指派对象">
          <el-input v-model="addRecordForm.指派对象" disabled="disabled" />
        </el-form-item>
        
        <el-form-item label="开始时间" prop="开始时间">
          <el-date-picker
            v-model="addRecordForm.开始时间"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="结束时间">
          <el-date-picker
            v-model="addRecordForm.结束时间"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="工作内容">
          <el-input v-model="addRecordForm.操作内容" :rows="2" type="textarea" placeholder="请输入工作内容" />
        </el-form-item>
        
        <el-form-item label="备注说明">
          <el-input v-model="addRecordForm.操作描述" :rows="3" type="textarea" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRecordDialogVisible = false">取消</el-button>
        <el-button :loading="addRecordLoading" type="primary" @click="submitAddRecord">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑时间弹窗 -->
    <el-dialog
      :visible.sync="editDialogVisible"
      title="编辑任务信息"
      width="700px"
      center
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" :model="editForm" label-width="120px" size="mini">
        <el-form-item label="生产订单">
          <el-input v-model="editForm.订单编号" readonly />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="editForm.产品编码" readonly />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="editForm.产品名称" readonly />
        </el-form-item>
        <el-form-item label="工序名称">
          <el-input v-model="editForm.工序名称" readonly />
        </el-form-item>
        <el-form-item label="指派对象">
          <el-input v-model="editForm.指派对象" readonly />
        </el-form-item>

        <el-form-item label="开始时间" required>
          <el-date-picker
            v-model="editForm.开始时间"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
            @change="calculateWorkTime"
          />
        </el-form-item>

        <el-form-item label="结束时间" required>
          <el-date-picker
            v-model="editForm.结束时间"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
            @change="calculateWorkTime"
          />
        </el-form-item>

        <el-form-item label="加工工时">
          <el-input v-model="editForm.加工工时" readonly>
            <template slot="append">秒</template>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">关闭</el-button>
        <el-button
          v-if="!currentTask.已校验"
          type="primary"
          @click="submitEditForm"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="abnormalControlDialogVisible"
      title="异常管控"
      width="1200px"
      center
      append-to-body
      :close-on-click-modal="false">
      <abnormal-control-panel :initial-selected-row="selectedRow" />
    </el-dialog>
    <el-dialog :visible.sync="Abnormalcontrolpop"
      title="异常管控"
      width="1200px"
      center
      :close-on-click-modal="false">
      <div class="workflow-container">
      <!-- 选项卡切换 -->
      <el-tabs v-model="activeTab" type="border-card" class="workflow-tabs">
        <!-- 待我处理 -->
        <el-tab-pane label="待我处理" name="pending">
          <div class="filter-bar">
            <el-input placeholder="搜索流程名称" v-model="filters.pending.keyword" class="filter-item" style="width: 200px;" clearable>
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <el-select v-model="filters.pending.priority" placeholder="优先级" class="filter-item" clearable>
              <el-option label="紧急" value="urgent"></el-option>
              <el-option label="高" value="high"></el-option>
              <el-option label="普通" value="normal"></el-option>
            </el-select>
          </div>

          <div v-if="filteredPendingTasks.length > 0">
            <el-card v-for="task in filteredPendingTasks" :key="task.节点ID" class="process-card">
              <div slot="header" class="clearfix">
                <el-tag :type="getPriorityType(task.优先级)" class="priority-tag">
                  {{ getPriorityText(task.优先级) }}
                </el-tag>
                <span v-if="task.是否转办" class="node-status status-transferred">转办</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="handleTask(task)">处理</el-button>
                <el-button size="mini" icon="el-icon-s-fold" @click="showTransferDialog(task)">转办</el-button>
              </div>
              <div>
                <p><strong>流程名称:</strong> {{ task.流程标题 }}</p>
                <p><strong>申请人:</strong> {{ task.申请人 }}</p>
                <p><strong>申请时间:</strong> {{ task.申请时间 }}</p>
                <p><strong>当前节点:</strong> {{ task.当前节点 }}</p>
                <p><strong>描述:</strong> {{ task.流程描述 }}</p>
                <p><strong>已关联生产订单:</strong> {{ task.已关联计划号 }}</p>
                <p><strong>物料名称:</strong> {{ task.零件名称 }}</p>
                <p><strong>物料编号:</strong> {{ task.零件编号 }}</p>
                <p><strong>工序名称:</strong> {{ task.工序名称 }}</p>
              </div>
            </el-card>
          </div>
          <div v-else class="empty-state">
            <el-empty description="暂无待处理任务"></el-empty>
          </div>
        </el-tab-pane>

        <!-- 我发起的 -->
        <el-tab-pane label="我发起的" name="initiated">
          <div class="filter-bar">
            <el-input placeholder="搜索流程名称" v-model="filters.initiated.keyword" class="filter-item" style="width: 200px;" clearable>
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <el-select v-model="filters.initiated.status" placeholder="状态" class="filter-item" clearable>
              <el-option label="审批中" value="processing"></el-option>
              <el-option label="已完成" value="completed"></el-option>
              <el-option label="已拒绝" value="rejected"></el-option>
            </el-select>
            <el-button type="primary" icon="el-icon-plus" @click="showCreateDialog" style="width: auto;">发起新流程</el-button>
          </div>

          <el-table :data="filteredInitiatedProcesses" style="width: 100%">
            <el-table-column prop="流程标题" label="流程名称" width="150"></el-table-column>
            <el-table-column prop="发起时间" label="发起时间" width="200"></el-table-column>
            <el-table-column prop="当前节点" label="当前节点" width="120"></el-table-column>
            <el-table-column prop="状态" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.状态)">
                  {{ getStatusText(scope.row.状态) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="viewProcessDetail(scope.row)">查看进度</el-button>
                <el-button v-if="scope.row.状态 === 'processing'" type="text" @click="showCompleteDialog(scope.row)">完结</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 我已处理 -->
        <el-tab-pane label="我已处理" name="processed">
          <el-table :data="processedTasks" style="width: 100%">
            <el-table-column prop="流程名称" label="流程名称" width="150"></el-table-column>
            <el-table-column prop="申请人" label="申请人" width="100"></el-table-column>
            <el-table-column prop="处理时间" label="处理时间" width="200"></el-table-column>
            <el-table-column prop="处理结果" label="处理结果" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.处理结果 === 'transferred'">
                  转办
                </el-tag>
                <el-tag v-else :type="scope.row.处理结果 === 'approved' ? 'success' : 'danger'">
                  {{ scope.row.处理结果 === 'approved' ? '同意' : '拒绝' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="审批意见" label="审批意见"></el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" @click="viewProcessDetail(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      
    </div>
    </el-dialog>
    <!-- 发起流程对话框 -->
      <el-dialog title="发起新流程" :visible.sync="createDialogVisible" width="1000px" :close-on-click-modal="false">
        <el-form :model="newProcessForm" label-width="120px" :rules="formRules" ref="processForm">
          <!-- 基础信息 -->
          <div class="form-section">
            <div class="form-section-title">
              <i class="el-icon-info"></i>基础信息
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="优先级" prop="priority">
                  <el-select v-model="newProcessForm.priority" placeholder="请选择优先级" style="width: 100%">
                    <el-option label="普通" value="normal"></el-option>
                    <el-option label="高" value="high"></el-option>
                    <el-option label="紧急" value="urgent"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="流程标题" prop="title">
              <el-input v-model="newProcessForm.title" placeholder="请输入流程标题"></el-input>
            </el-form-item>
            
            <el-form-item label="流程描述" prop="description">
              <el-input type="textarea" v-model="newProcessForm.description" :rows="3" 
                    placeholder="请输入流程详细描述"></el-input>
            </el-form-item>
            <!-- 审批流程设置 -->
            <div class="form-section" v-if="newProcessForm.type">
              <div class="form-section-title">
                <i class="el-icon-s-check"></i>审批流程设置
              </div>
              
              <el-form-item label="审批人">
                <el-button type="text" icon="el-icon-plus" @click="addApprover">添加审批人</el-button>
                <div class="approver-list">
                  <div v-for="(approver, index) in newProcessForm.approvers" :key="index" class="approver-item">
    
                    <el-select v-model="approver.userId" placeholder="选择人员" 
                         filterable style="width: 200px; margin-right: 10px;">
                      <el-option v-for="user in getUserListByType(approver)" :key="user.id" 
                           :label="user.name" :value="user.id"></el-option>
                    </el-select>
                    <el-button type="text" icon="el-icon-delete" class="dynamic-remove-btn"
                         @click="removeApprover(index)"></el-button>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
          
          <div class="form-section">
            <div class="form-section-title">
              <i class="el-icon-info"></i>绑定任务信息
            </div>
            <el-form-item v-if="selectedRow != ''" label="已关联生产订单">
              <el-input v-model="tableOrderNum" placeholder="" readonly></el-input>
            </el-form-item>
            <el-form-item v-if="selectedRow != ''" label="物料名称">
              <el-input v-model="tableProductName" placeholder="" readonly></el-input>
            </el-form-item>
            <el-form-item v-if="selectedRow != ''" label="物料编号">
              <el-input v-model="tableProductCode" placeholder="" readonly></el-input>
            </el-form-item>
            <el-form-item v-if="selectedRow != ''" label="工序名称">
              <el-input v-model="tableProcessName" placeholder="" readonly></el-input>
            </el-form-item>
            <div class="search-container">
              <span class="show-text">生产订单:</span>
              <el-input v-model="orderNo" 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="productName" placeholder="请输入产品名称" clearable style="width: 150px;margin-right: 10px" />
              <el-button :disabled="loading" icon="el-icon-search" plain type="primary" @click="searchTable3()">查询</el-button>
            </div>
            <el-tabs v-model="activeTab" type="card" class="custom-tabs">
              <el-table v-loading="loading" :data="tableData5" :height="'40vh'" border
                element-loading-background="rgba(0, 0, 0, 0.2)" element-loading-spinner="el-icon-loading"
                highlight-current-row size="mini" style="width: 100%;" tooltip-effect="dark"
                @row-click="handleAbnormalControlTaskRowClick">
                <!-- <el-table-column align="center" label="序号" type="index" width="50" fixed /> -->
                
                <el-table-column align="center" prop="产品名称" label="物料名称" width="190" fixed/>
                <el-table-column align="center" prop="产品编码" label="物料编码" width="220" fixed/>
                <el-table-column align="center" prop="合同号" label="销售订单" width="60" fixed />
                <el-table-column align="center" prop="订单号" label="生产订单" width="80" fixed />

                <el-table-column align="center" prop="计划数量" label="计划数" width="80" />
                <el-table-column align="center" prop="工序名称" label="工序名称" width="120" />
                <el-table-column align="center" prop="指派对象编号" label="指派对象编号" width="120" />
                <el-table-column align="center" prop="指派对象" label="指派对象" width="120" />
                <el-table-column align="center" prop="指派数量" label="指派数量" width="120" />
                <el-table-column align="center" prop="计划开始时间" label="计划开始时间" width="120" />
                <el-table-column align="center" prop="计划完成时间" label="计划完成时间" width="120" />
                <el-table-column align="center" prop="最晚开始时间" label="最晚开始时间" width="120" />
                <el-table-column align="center" label="要求完工日期" width="120">
                  <template slot-scope="scope">
                    {{ formatDate(scope.row.要求完工日期) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tabs>
          </div>
        </el-form>
        
        <span slot="footer" class="dialog-footer">
          <el-button @click="createDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitNewProcess">提 交</el-button>
        </span>
      </el-dialog>

      <!-- 处理任务对话框 -->
      <el-dialog title="处理任务" :visible.sync="handleDialogVisible" width="700px">
        <div v-if="currentTask">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请人">{{ currentTask.申请人 }}</el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ currentTask.申请时间 }}</el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityType(currentTask.优先级)">
                {{ getPriorityText(currentTask.优先级) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">{{ currentTask.流程描述 }}</el-descriptions-item>
            <el-descriptions-item label="已关联生产订单">{{ currentTask.已关联计划号 }}</el-descriptions-item>
            <el-descriptions-item label="物料名称">{{ currentTask.零件名称 }}</el-descriptions-item>
            <el-descriptions-item label="物料编号">{{ currentTask.零件编号 }}</el-descriptions-item>
            <el-descriptions-item label="工序名称">{{ currentTask.工序名称 }}</el-descriptions-item>
          </el-descriptions>
          
          <el-divider></el-divider>

          <el-form :model="handleForm" label-width="100px" ref="approvalForm">
            <el-form-item label="处理意见" required>
              <el-radio-group v-model="handleForm.result">
                <el-radio label="approved">同意</el-radio>
                <el-radio label="rejected">拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审批意见">
              <el-input type="textarea" v-model="handleForm.comment" :rows="3" placeholder="请输入审批意见"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitHandle(currentTask)">提 交</el-button>
        </span>
      </el-dialog>

      <!-- 查看流程进度对话框 -->
      <el-dialog title="流程进度详情" :visible.sync="detailDialogVisible" width="800px">
        <div v-if="currentProcess">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="流程名称">{{ currentProcess.processInfo.流程标题 }}</el-descriptions-item>
            <el-descriptions-item label="发起人">{{ currentProcess.processInfo.发起人姓名 }}</el-descriptions-item>
            <el-descriptions-item label="发起时间">{{ currentProcess.processInfo.创建时间 }}</el-descriptions-item>
            <el-descriptions-item label="当前状态">
              <el-tag :type="getStatusType(currentProcess.processInfo.状态)">
                {{ getStatusText(currentProcess.processInfo.状态) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="已关联生产订单">{{ currentProcess.processInfo.已关联计划号 }}</el-descriptions-item>
            <el-descriptions-item label="物料名称">{{ currentProcess.processInfo.零件名称 }}</el-descriptions-item>
            <el-descriptions-item label="物料编号">{{ currentProcess.processInfo.零件编号 }}</el-descriptions-item>
            <el-descriptions-item label="工序名称">{{ currentProcess.processInfo.工序名称 }}</el-descriptions-item>
          </el-descriptions>

          <el-divider></el-divider>

          <h4>审批流程</h4>
          <el-steps :active="currentProcess.processInfo.当前步骤" align-center style="margin: 20px 0;">
            <el-step v-for="(step, index) in currentProcess.steps" :key="index" 
                 :title="step.标题" :description="step.描述"></el-step>
          </el-steps>

          <el-divider></el-divider>

          <h4>审批记录</h4>
          <el-timeline style="margin-top: 20px;">
            <el-timeline-item v-if="record.处理结果 != 'transferred'" v-for="(record, index) in currentProcess.approvalRecords" 
                     :key="index" :timestamp="record.时间" :type="record.处理结果 === 'approved' ? 'success' : 'danger'"
                     :icon="record.处理结果 === 'approved' ? 'el-icon-check' : 'el-icon-close'">
              <el-card>
                <h4>{{ record.审批人姓名 }} - {{ record.处理结果 === 'approved' ? '同意' : '拒绝' }}</h4>
                <p>{{ record.审批意见 || '无备注' }}</p>
              </el-card>
            </el-timeline-item>
            <el-timeline-item v-if="record.处理结果 == 'transferred'" v-for="(record, index) in currentProcess.approvalRecords" 
                     :key="index" :timestamp="record.时间" :type="'success'"
                     :icon="'el-icon-check'">
              <el-card>
                <h4>{{ record.审批人姓名 }}-转办</h4>
                <p>{{ record.审批意见 || '无备注' }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-dialog>

      <!-- 转办对话框 -->
      <el-dialog title="转办流程" :visible.sync="transferDialogVisible" width="700px">
        <el-form :model="transferForm" label-width="100px">
          <el-form-item label="目标人员" required>
            <el-select v-model="transferForm.newApproverId" placeholder="请选择人员" style="width: 100%">
              <el-option v-for="user in users" :key="user.id" 
                      :label="user.name" :value="user.id">
                <span>{{ user.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="转办原因" required>
            <el-input type="textarea" v-model="transferForm.reason" :rows="3" placeholder="请输入转办原因"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="transferDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmTransfer" :loading="transferLoading">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 完结对话框 -->
      <el-dialog title="完结流程" :visible.sync="completeDialogVisible" width="700px" class="complete-dialog">
        <el-form :model="completeForm" label-width="120px">
          <el-form-item label="流程名称">
            <div>{{ selectProcess ? selectProcess.流程标题 : '' }}</div>
          </el-form-item>
          <el-form-item label="完结原因" required>
            <el-input type="textarea" v-model="completeForm.reason" :rows="3" 
                      placeholder="请输入完结原因"></el-input>
          </el-form-item>
          <el-form-item label="完结结果" required>
            <el-radio-group v-model="completeForm.result">
              <el-radio label="completed">完成</el-radio>
              <el-radio label="cancelled">取消</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        
        <span slot="footer" class="dialog-footer">
          <el-button @click="completeDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmComplete" :loading="completeLoading" style="width: auto;">确 认 完 结</el-button>
        </span>
      </el-dialog>
      <!-- 退库弹窗 -->
      <el-dialog
        :visible.sync="ReturnWarehousepop"
        title="退库单"
        width="1500px"
        center
        :close-on-click-modal="false"
      >
        <el-form ref="ReturnWarehouseForm" :model="ReturnWarehouseForm" size="mini">
          <el-form-item  v-for="item in ReturnWarehouseForm" :key="item.编码" >
            <div class="info-container" >
              <div class="info-item">
                <span class="info-label" style="width: 80px">物料名称</span>
                <span class="info-value">
                  <el-input
                    v-model="item.名称"
                    size="mini"
                    readonly
                    style="width: 200px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">物料编码</span>
                <span class="info-value">
                  <el-input
                    v-model="item.编码"
                    size="mini"
                    readonly
                    style="width: 250px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">发料数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.数量"
                    size="mini"
                    style="width: 100px"
                    readonly
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">退库数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.退库数量"
                    size="mini"
                    style="width: 100px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">备注</span>
                <span class="info-value">
                  <el-input
                    v-model="item.LineText"
                    size="mini"
                    style="width: 200px"
                  />
                </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="ReturnWarehousepop = false">关闭</el-button>
          <el-button
            type="primary"
            @click="submitReturnWare"
          >
            确 定
          </el-button>
        </div>
      </el-dialog>
      <!-- 领料弹窗 -->
      <el-dialog
        :visible.sync="MaterialRequisitionpop"
        title="领料单"
        width="1200px"
        center
        :close-on-click-modal="false"
      >
        <el-form ref="MaterialRequisitionForm" :model="MaterialRequisitionForm" size="mini">
          <el-form-item  v-for="item in MaterialRequisitionForm.lines" :key="item.ItemNo" >
            <div class="info-container" >
              <div class="info-item">
                <span class="info-label" style="width: 80px">物料名称</span>
                <span class="info-value">
                  <el-input
                    v-model="item.ItemName"
                    size="mini"
                    readonly
                    style="width: 200px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">物料编码</span>
                <span class="info-value">
                  <el-input
                    v-model="item.ItemNo"
                    size="mini"
                    readonly
                    style="width: 250px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.Quantity"
                    size="mini"
                    style="width: 150px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">备注</span>
                <span class="info-value">
                  <el-input
                    v-model="item.LineText"
                    size="mini"
                    style="width: 150px"
                  />
                </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="MaterialRequisitionpop = false">关闭</el-button>
          <el-button
            type="primary"
            @click="submitMaterialRequisition(MaterialRequisitionForm.lines)"
          >
            确 定
          </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>
      <el-dialog
        :visible.sync="UrgentVisible"
        title="加急明细"
        width="1200px"
        center
        :close-on-click-modal="false"
      >
        <el-form ref="Urgentarr" :model="Urgentarr" size="mini">
          <el-form-item  v-for="item in Urgentarr" :key="item.订单编号" >
            <div class="info-container" >
              <div class="info-item">
                <span class="info-label" style="width: 80px">生产订单</span>
                <span class="info-value">
                  <el-input
                    v-model="item.订单编号"
                    size="mini"
                    readonly
                    style="width: 300px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">加急数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.加急数量"
                    size="mini"
                    style="width: 150px"
                    readonly
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">物料编号</span>
                <span class="info-value">
                  <el-input
                    v-model="item.物料编号"
                    size="mini"
                    style="width: 150px"
                    readonly
                  />
                </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="UrgentVisible = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 加班弹窗 -->
    <el-dialog
      title="报工确认"
      :visible.sync="overtimeDialogVisible"
      width="700px"
      :close-on-click-modal="false"
      :before-close="handleOvertimeClose"
    >
      <el-form label-width="150px">
        <el-form-item label="班次" required>
          <el-select v-model="selectedShiftName" placeholder="请选择班次" @change="onShiftChange" style="width: 100%">
            <el-option v-for="item in shiftoptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="selectedOption" size="default" @change="onStatusChange">
            <el-radio label="工作日" border>工作日</el-radio>
            <el-radio label="休息日" border>休息日</el-radio>
            <el-radio label="法定休息日" border>法定休息日</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="加班">
          <el-radio-group v-model="isOvertime" @change="onOvertimeChange">
            <el-radio :label="1">是</el-radio>    <!-- ⭐ 改为数字 1 -->
            <el-radio :label="0">否</el-radio>    <!-- ⭐ 改为数字 0 -->
          </el-radio-group>
        </el-form-item>

        <el-form-item label="加班人员" required>
          <el-select
            v-model="overtimePersons"
            placeholder="请选择加班人员"
            multiple
            filterable
            style="width: 100%"
            :disabled="isOvertime !== 1"   
          >
            <el-option v-for="item in overtimeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <!-- <div v-if="isOvertime === 1 && overtimePersons.length === 0" style="color: #f56c6c; font-size: 12px; margin-top: 5px">
            请至少选择一名加班人员
          </div> -->
        </el-form-item>
        
        <el-form-item label="特殊工时人员" >
          <el-select
            v-model="tsovertimePersons"
            placeholder="请选择加班工时人员"
            multiple
            filterable
            style="width: 100%"
            :disabled="isOvertime !== 1"   
          >
            <el-option v-for="item in overtimeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isOvertime === 1 && overtimePersons.length === 0 && tsovertimePersons.length === 0">
          <div style="color: #f56c6c; font-size: 12px;">
            请至少选择一名加班人员或特殊人员
          </div>
        </el-form-item>
        <el-form-item label="班次标准工时(H)" >
          <el-input-number 
            v-model="shiftStandardHours" 
            :min="0" 
            :max="24"
            :disabled="isOvertime !== 1"  
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
      <el-button @click="overtimeDialogVisible = false">取 消</el-button>
      <el-button 
        type="primary" 
        @click="confirmOvertime" 
        :disabled="isOvertime === 1 && overtimePersons.length === 0 && tsovertimePersons.length === 0"
      >
        确 定
      </el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>

import { mapGetters } from 'vuex'
import { MESDownFile } from '@/utils/request'
import { postB1 } from '@/api/b1s';
import { getB1 } from '@/api/b1s';
import { posttm } from '@/api/tm';
import { seepdf, initPDFKeyboardShortcuts, setZoom } from '@/utils/pdf';
import AbnormalControlPanel from '@/views/ProductionManagement/components/AbnormalControlPanel.vue';
export default {
  components: {
    AbnormalControlPanel
  },
  data() {
    return {
      TaskAID:'',
      radio: 1,
      orderNo2: "",
      contractNo: "",
      productCode2: "",
      plannum:"",
      salenum:'',
      process: "",
      processList2: [],
      nature: "",
      productionStatus2: null,
      taskstate: "",
      taskprogress: "0",
      startworktime: 0,
      shift: "白班",
      shiftoptions: [
        
      ],
      Doing: [],
      Doingoptions: [],
      // DoingData: {
      //   订单编号: "",
      //   合同号: "",
      //   物料编号: "",
      //   指派数量: "",
      //   完成数量: "",
      // },
      rptDate: [],
      completionTime: [],
      currentTime: "",
      loading: false,
      tableData: [],
      selectedRow: null,
      currentRow: {},
      colorstatus: "",
      assistendData: {},
      assistNumber: 0,
      assistendVisible: false,
      receiveData: {},
      receiveNum: 0,
      receiveVisible: false,
      workStartData: {},
      workStartNum: 0,
      workStartVisible: false,
      firstCheckData: {},
      firstCheckNumber: false,
      firstCheckVisible: false,
      prodReportData: [],
      prodReportDataTop: [],
      proReportNum: 0,
      prodReportVisible: false,
      tableDataBack: [],
      rptDesc: "",
      multipleSelection: "",
      editForm: {
        优先级: "",
        未完成说明: "",
        派工特殊说明: "",
      },
      splitTaskDialogVisible: false,
      splitTaskSubmitLoading: false,
      stationOptions: [],
      splitTaskForm: {
        分配数量: 0,
        指派对象: "",
        指派对象编号: "",
        派工特殊备注: "",
        计划开始时间: "",
        计划结束时间: "",
        最晚开始时间: "",
        任务概述: "",
      },
      tableData2: [], //检验标准数据
      type: "",
      checkForm: {
        检验标准编号: "",
        检验标准名称: "",
        检验项目: "",
        检验内容: "",
        检验比例: "",
        上限值: "",
        下限值: "",
        单位: "",
        检具: "",
        备注: "",
      },
      currentPage: 1, // 当前页码
      inspectionData: [], // 存储所有检测项的二维数组
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前时间之后的日期
          return time.getTime() > Date.now();
        },
      },
      processCheckVisible: false,
      receiveCheckVisible: false,
      checkRecordVisible: false,
      type: "",
      typeList: [],
      operationPerson: "",
      operationPersonList: [],
      operationDate: [],
      inspectionResult: "",
      inspectionResultList: [
        { value: "1", label: "合格" },
        { value: "0", label: "不合格" },
      ],
      checkDetailedVisible: false,
      DetailedVisible: false,
      // 序检自检相关数据
      processCheckData: {
        物料描述: "",
        合同号: "",
        物料编号: "",
        订单编号: "",
        工序名称: "",
        检测数量: 1,
        合格数: 1,
        计划数量: "",
        检验人: "",
        检验时间: "",
        顺序编号: "",
        TaskAID: "",
      },
      betweenProcessTableData: [], // 检验标准数据
      betweenProcessInspectionData: [], // 存储所有检测项的二维数组
      betweenProcessCurrentPage: 1,
      betweenProcessCurrentInspectionItem: 1, // 当前检测零件编号
      // 收检相关数据
      receiveCheckData: {
        物料描述: "",
        合同号: "",
        物料编号: "",
        订单编号: "",
        工序名称: "",
        检测数量: 0,
        合格数: 0,
        不合格数: 0,
        计划数量: "",
        检验人: "",
        检验时间: "",
        备注: "",
        顺序编号: "",
        TaskAID: "",
        已检测数量:0
      },

      // 检验记录相关数据
      checkRecordTableData: [],
      checkRecordLoading: false,
      checkRecordSelectedRow: null,
      currentInspectionItem: 1, // 当前检测零件编号
      QT_AID: -1,

      //异常工时
      abnormalVisible: false,
      abnormaltableData: [],
      editDialogVisible: false,
      currentTask: {},
      // 检验详情相关数据
      checkDetailedTableData: [], // 检验详情表格数据（检测零件）
      inspectionDetailTableData: [], // 检测详情表格数据（检测数据）
      currentQT_AID: null, // 当前选中的质检记录ID
      currentLJ_AID: null, // 当前选中的检测零件ID
      currentInspectionRecord: {}, // 当前选中的检验记录


      abnormalControlDialogVisible: false,
      //异常管控相关数据
      orderNo: '',
      contractNo: '',
      productCode: '',
      productName: '',
      processName: '',
      completionTime: [],
      productionStatus: '',
      
      tableData5: [],
      activeTab: 'pending',
      tableOrderNum: '',
      tableProductCode: '',
      tableProductName: '',
      tableProcessName: '',
      selectedRow: '',
      loading: false,
      // 转办相关数据
      transferDialogVisible: false,
      transferLoading: false,
      
      // 完结相关数据
      completeDialogVisible: false,
      completeLoading: false,
      
      //currentTask: null,
      currentProcess: null,
      selectProcess: null,
      
      transferForm: {
        newApproverId: '',
        newApproverName: '',
        reason: ''
      },
      
      completeForm: {
        reason: '',
        result: 'completed'
      },
      
      createDialogVisible: false,
      handleDialogVisible: false,
      detailDialogVisible: false,
      submitting: false,
      
      filters: {
        pending: { keyword: '', priority: '', type: '' },
        initiated: { keyword: '', status: '' }
      },
      
      newProcessForm: {
        type: '',
        priority: 'normal',
        title: '',
        description: '',
        approvers: []
      },
      
      formRules: {
        title: [{ required: true, message: '请输入流程标题', trigger: 'blur' }],
        description: [{ required: true, message: '请输入流程描述', trigger: 'blur' }]
      },
      
      handleForm: {
        result: 'approved',
        comment: ''
      },
      
      userList: [],
      
      stats: {
        pending: 0,
        initiated: 0,
        completed: 0,
      },
      
      // 数据
      pendingTasks: [],
      initiatedProcesses: [],
      processedTasks: [],
      users: [],
      Abnormalcontrolpop:false,
      ReturnWarehousepop:false,
      ReturnWarehouseForm:{},
      MaterialRequisitionpop:false,
      MaterialRequisitionForm:{},
      downPDF:MESDownFile,
      pausePreviousState:{},

      // 新增工时记录
      addRecordDialogVisible: false,
      addRecordLoading: false,
      addRecordForm: {
        操作类别: '',
        订单编号: '',
        产品编码: '',
        产品名称: '',
        工序名称: '',
        指派对象: '',
        开始时间: '',
        结束时间: '',
        操作内容: '',
        操作描述: ''
      },
      addRecordRules: {
        操作类别: [{ required: true, message: '请选择操作类别', trigger: 'change' }],
        订单编号: [{ required: true, message: '请选择订单编号', trigger: 'change' }],
        工序名称: [{ required: true, message: '请选择工序名称', trigger: 'change' }],
        指派对象: [{ required: true, message: '请输入操作人员', trigger: 'blur' }],
        开始时间: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        结束时间: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      },
      //异常工时
      abnormalVisible: false,
      abnormaltableData: [],
      editDialogVisible: false,
      currentTask: {},
      editForm: {
        优先级: "",
        未完成说明: "",
        派工特殊说明: "",
      },
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前时间之后的日期
          return time.getTime() > Date.now();
        },
      },
      
      // 人员时间记录相关
      userTimeRecords: {}, // 存储用户开始时间记录 { taskAID: { userId: startTime } }
      // 新增相关数据
      orderList: [], // 订单列表
      processList: [], // 工序列表
      seeVisible:false,
      UrgentVisible: false,
      Urgentarr: {},
      selectedOperators:'',
      processname2:'',
      TaskAID2:'',

      // 新增报工加班变量
      shiftConfig: [],           
      originalShift: null,       
      currentShift: null,        
      taskStartTime: null,       
      overtimeDialogVisible: false,
      overtimeOptions: [],       
      overtimePersons: [],       
      tsovertimePersons: [],     
      selectedOption: '工作日',   // 用户选择的状态名称
      selectedShiftName: '',     
      selectedOperatorsName: '', 
      overtimeResolve: null,     
      overtimeReject: null,
      isOvertime: false,      // 是否加班
      isRestDay: false,       // 是否休息日
      isLegalRestDay: false,  // 是否法定休息日
      shiftStandardHours:8
    };
    
  },
  created() {
    
    var now = new Date();
    var start = new Date(
      Date.UTC(now.getFullYear() , now.getMonth()-1, now.getDate(), 0, 0, 0)
    )
      .toISOString()
      .replace("T", " ")
      .replace(".000Z", "");
    var end = new Date(
      Date.UTC(now.getFullYear(), now.getMonth()+1, now.getDate(), 23, 59, 59)
    )
      .toISOString()
      .replace("T", " ")
      .replace(".000Z", "");
    this.completionTime = [start, end];
    this.rptDate = end;
    this.getCurrentTime();
    this.getDoing();
    this.getProcessList();
    this.getTypeList();
    this.getOperationPersonList();
    
    this.getUserList();
    this.initPauseState()
    this.loadOrderList('')
    this.getBind()
    this.getworkgroup()
    setInterval(this.getCurrentTime, 1000);
    this.operationDate = [start, end];
  },
  computed: {
    isOvertimeEnabled() {
      return this.isOvertime === 1
    },
    ...mapGetters([
      'id',
      'name',
      'token'
    ]),
    
    filteredPendingTasks() {
      let tasks = this.pendingTasks;
      if (this.filters.pending.keyword) {
        tasks = tasks.filter(task => 
          task.流程标题.includes(this.filters.pending.keyword)
        );
      }
      if (this.filters.pending.priority) {
        tasks = tasks.filter(task => task.优先级 == this.filters.pending.priority);
      }
      return tasks;
    },
    
    filteredInitiatedProcesses() {
      let processes = this.initiatedProcesses;
      if (this.filters.initiated.keyword) {
        processes = processes.filter(process => 
          process.流程标题.includes(this.filters.initiated.keyword)
        );
      }
      if (this.filters.initiated.status) {
        processes = processes.filter(process => process.状态 === this.filters.initiated.status);
      }
      return processes;
    },
    unqualifiedCount() {
      // 计算有多少页至少有一个不合格项
      let unqualifiedPages = 0;
      if (this.inspectionData && this.inspectionData.length > 0) {
        for (let page = 0; page < this.inspectionData.length; page++) {
          const pageData = this.inspectionData[page];
          if (pageData && pageData.some((item) => item.检测结果 === "0")) {
            unqualifiedPages++;
          }
        }
      }
      return unqualifiedPages;
      
    },
    
    betweenProcessUnqualifiedCount() {
      let unqualifiedPages = 0;
      if (
        this.betweenProcessInspectionData &&
        this.betweenProcessInspectionData.length > 0
      ) {
        for (
          let page = 0;
          page < this.betweenProcessInspectionData.length;
          page++
        ) {
          const pageData = this.betweenProcessInspectionData[page];
          if (pageData && pageData.some((item) => item.检测结果 === "0")) {
            unqualifiedPages++;
          }
        }
      }
      return unqualifiedPages;
    },
  },
  methods: {

    // 加载加班人员选项
    async loadOvertimePersonOptions(shiftName) {
      var params = []
      if (this.selectedRow) {
        params.push(['指派对象', this.selectedRow.指派对象])
      }
      params.push(['班次', shiftName])
      const Data = this.CreateData('11', '生产管理_加工中心_获取设备人员', params)

      try {
        const response = await this.ExecDatabase(Data)
        var person = []
        if (this.selectedOperatorsName) {
          person.push({ value: this.selectedOperatorsName, label: this.selectedOperatorsName })
        }
        response.data.forEach((element) => {
          person.push({ value: element.人员名称, label: element.人员名称 })
        })
        this.overtimeOptions = person
      } catch (error) {
        console.error('获取加班人员失败:', error)
        this.overtimeOptions = []
      }
    },

    // 显示加班人员选择对话框
async showOvertimeDialog() {
  return new Promise(async (resolve, reject) => {
    // 设置默认值 - 使用任务开始时间对应的班次
    this.selectedShiftName = this.shift || this.originalShift?.班次名称 || '白班'  // ⭐ 使用 this.shift
    this.selectedShiftObj = this.shiftConfig.find((s) => s.班次名称 === this.selectedShiftName)
    this.selectedOption = '工作日'
    this.isRestDay = 0
    this.isLegalRestDay = 0
    this.isOvertime = 0
    this.overtimePersons = []
    this.tsovertimePersons = []
    this.shiftStandardHours = 8

    // 加载加班人员选项
    await this.loadOvertimePersonOptions(this.selectedShiftName)
    
    // 默认全选所有加班人员
    if (this.overtimeOptions && this.overtimeOptions.length > 0) {
      this.overtimePersons = this.overtimeOptions.map(option => option.value)
      this.tsovertimePersons = []
    }

    this.overtimeResolve = resolve
    this.overtimeReject = reject
    this.overtimeDialogVisible = true
  })
},
// 日期类型变化时的处理
onStatusChange(value) {
  this.isRestDay = (value === '休息日' || value === '法定休息日')
  this.isLegalRestDay = (value === '法定休息日')
},
    // 确认加班
confirmOvertime() {
  // 根据 selectedOption 设置 isRestDay 和 isLegalRestDay
  this.isRestDay = (this.selectedOption === '休息日' || this.selectedOption === '法定休息日') ? 1 : 0
  this.isLegalRestDay = (this.selectedOption === '法定休息日') ? 1 : 0
  
  // ⭐ 修改：加班人员和特殊加班人员至少有一个有值
  const hasOvertimePersons = this.overtimePersons && this.overtimePersons.length > 0
  const hasSpecialPersons = this.tsovertimePersons && this.tsovertimePersons.length > 0
  // ⭐ 检查用户是否手动修改了班次
  // selectedShiftName 是用户在弹窗中选择的（如果修改了）
  // originalShift 是自动匹配的班次
  let finalShiftName = this.selectedShiftName
  
  // 如果用户没有手动修改（即弹窗关闭时 selectedShiftName 等于自动匹配的班次），使用自动匹配的
  // 如果用户手动修改了，就使用手动选择的
  if (!this.userManuallyChangedShift && finalShiftName === this.originalShift?.班次名称) {
    finalShiftName = this.originalShift?.班次名称 || this.shift
  }
  // 如果用户选择了加班（isOvertime === 1），必须至少选择一种加班人员
  if (this.isOvertime === 1 && !hasOvertimePersons && !hasSpecialPersons) {
    this.$message.error('请至少选择一名加班人员或特殊加班人员')
    return
  }

  if (this.overtimeResolve) {
    // ⭐ 传递加班人员时，合并普通加班人员和特殊加班人员
    let allPersons = [...this.overtimePersons]
    if (this.tsovertimePersons && this.tsovertimePersons.length > 0) {
      // 合并特殊加班人员，去重
      this.tsovertimePersons.forEach(person => {
        if (!allPersons.includes(person)) {
          allPersons.push(person)
        }
      })
    }
    
    this.overtimeResolve({
      persons: allPersons,                    // 所有加班人员（合并后的）
      ordinaryPersons: this.overtimePersons,  // 普通加班人员
      specialPersons: this.tsovertimePersons, // 特殊加班人员
      selectedShift: this.selectedShiftName,
      isRestDay: this.isRestDay,
      isLegalRestDay: this.isLegalRestDay,
      isOvertime: this.isOvertime,        // 已经是数字 0 或 1
      shiftStandardHours: this.shiftStandardHours || 8,  // ⭐ 返回班次标准工时
    })
  }

  this.overtimeDialogVisible = false
  this.overtimeResolve = null
  this.overtimeReject = null
},

    handleOvertimeClose(done) {
      if (this.overtimeReject) {
        this.overtimeReject('cancel')
      }
      this.overtimeResolve = null
      this.overtimeReject = null
      done()
    },

    onShiftChange(shiftName) {
      this.selectedShiftObj = this.shiftConfig.find((s) => s.班次名称 === shiftName)
      this.loadOvertimePersonOptions(shiftName)
      this.overtimePersons = []
      this.tsovertimePersons = []
      // this.recalculateOvertimeDuration()
    },

    // onRestDayChange() {
    //   this.recalculateOvertimeDuration()
    // },

    onOvertimeChange() {
      // 当用户选择"否"时，清空加班人员
      if (this.isOvertime === 0) {  // ⭐ 改为 === 0
        this.overtimePersons = []
        this.tsovertimePersons = []
      }
    },

    getworkgroup(){
      this.shiftoptions = []
      var Data = this.CreateData("11", "生产管理_加工中心_获取班次信息",'');
      this.ExecDatabase(Data).then((response) => {
        response.data.forEach(element => {
          this.shiftoptions.push({value:element.班次名称,label:element.班次名称})
        });
      });
    },
    handletaskChange(process){
      console.log(process)
      const res  = this.processList.find(item=>(item.TaskAID === process))
      console.log(res)
      this.processname2 = res.工序名称
      this.TaskAID2 = process
    },
    Urgent(row){
      var param = []
      param.push(["物料编号",row.零件编码])
      this.UrgentVisible = true
      var Data = this.CreateData("11", "加急订单_加急明细查询",param);
      this.ExecDatabase(Data).then((response) => {
        this.Urgentarr = response.data
      });
    },
    getBind(){
      var param = [['操作人ID', this.$store.state.user.id]]
      var Data = this.CreateData('11', '生产管理_获取人员绑定', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response.data)
        response.data.forEach(element => {
          this.Doing.push(element.工位名称)
          this.searchTable();
        });
      })
    },
    loadProcessList(orderId) {
      var param = [['订单编号', orderId]]
      var Data = this.CreateData('11', '工时校验_获取订单工序', param)
      this.ExecDatabase(Data).then(response => {
        this.processList = response.data || []
        // 如果只有一个工序，自动选择
        if (this.processList.length === 1) {
          this.addRecordForm.工序名称 = this.processList[0].工序名称
        }
      }).catch(error => {
        console.error('加载工序列表失败:', error)
        this.processList = []
      })
    },
    // 从操作记录表加载暂停状态
    loadOrderList(orderId) {
      var param = []
      param.push(['订单编号',orderId])
      var Data = this.CreateData('11', '工时校验_获取订单列表', param)
      this.ExecDatabase(Data).then(response => {
        this.orderList = response.data || []
      }).catch(error => {
        console.error('加载订单列表失败:', error)
        this.orderList = []
      })
    },
    submitAddRecord() {
      this.$refs.addRecordForm.validate((valid) => {
        if (valid) {
          this.addRecordLoading = true
          
          // 计算工时（秒）
          let workTime = 0
          if (this.addRecordForm.开始时间 && this.addRecordForm.结束时间) {
            const start = new Date(this.addRecordForm.开始时间)
            const end = new Date(this.addRecordForm.结束时间)
            const diff = end.getTime() - start.getTime()
            workTime = Math.round(diff / 1000)
          }
          
          const recordData = {
            ...this.addRecordForm,
            工时: workTime,
            操作人: this.getCurrentUser(),
            报工日期: new Date().toISOString().split('T')[0]
          }
          
          // 调用新增API
          var param = [
            ['操作类别', this.addRecordForm.操作类别],
            ['订单编号', this.addRecordForm.订单编号],
            ['物料编号', this.addRecordForm.产品编码],
            ['物料描述', this.addRecordForm.产品名称],
            ['工序名称', this.processname2],
            // ['工位名称', this.addRecordForm.指派对象], // 使用指派对象作为工位名称
            ['操作人', this.getCurrentUser()],
            ['开始时间', this.addRecordForm.开始时间],
            ['结束时间', this.addRecordForm.结束时间],
            ['操作内容', this.addRecordForm.操作内容],
            ['操作描述', this.addRecordForm.操作描述],
            ['TaskAID', this.TaskAID2],
          ]
          
          var Data = this.CreateData('11', '异常工时_新增操作记录', param)
          this.ExecDatabase(Data).then(response => {
            this.$message.success('新增成功')
            this.addRecordDialogVisible = false
            this.abnormalTable() // 刷新表格
          }).catch(error => {
            this.$message.error('新增失败：' + error.message)
          }).finally(() => {
            this.addRecordLoading = false
          })
        }
      })
    },
    handleOrderChange(orderId) {
      if (orderId) {
        this.loadOrderList(orderId)
        // 自动填充零件编码和零件名称
        const selectedOrder = this.orderList.find(order => order.订单编号 == orderId)
        if (selectedOrder) {
          this.addRecordForm.产品编码 = selectedOrder.零件编码
          this.addRecordForm.产品名称 = selectedOrder.零件名称
        }
        
        // 加载该订单的工序列表
        this.loadProcessList(orderId)
      } else {
        this.addRecordForm.产品编码 = ''
        this.addRecordForm.产品名称 = ''
        this.processList = []
      }
    },
    addWorkTimeRecord() {
      var row = this.selectedRow
      this.addRecordForm = {
        操作类别: '',
        订单编号: row.订单号,
        产品编码: row.零件编码,
        产品名称: row.零件名称,
        工序名称: row.工序名称,
        指派对象: this.$store.state.user.name,
        开始时间: '',
        结束时间: '',
        操作内容: '',
        操作描述: '',
        TaskAID: Number(row.TaskAID)
      }
      this.processname2 = row.工序名称
      this.TaskAID2 = row.TaskAID
      this.processList = []
      this.addRecordDialogVisible = true
    },
    async loadPauseStateFromRecords() {
      const params = [];
      params.push(["操作人", this.$store.state.user.name]);
      
      // 查询最近的暂停记录
      const Data = this.CreateData("11", "MES_操作记录_获取暂停状态", params);
      const response = await this.ExecDatabase(Data);
      
      if (response.data && response.data.length > 0) {
        // 创建 stateObj 对象
        const stateObj = {};
        console.log(response.data)
        response.data.forEach(item => {
          if (item.PreviousState) {
            // 将数据填充到 stateObj 中
            stateObj[item.TaskAID] = item.PreviousState;
          }
        });
        // 返回 stateObj
        return stateObj;
      }
      // 如果没有数据，返回空对象
      return {};
    },

    // 更新暂停状态管理方法
    async updatePauseState(taskAID, previousState) {
      // 暂停状态已经通过操作记录保存，这里只需要更新本地状态
      this.pausePreviousState[taskAID] = previousState;
    },

    async clearPauseState(taskAID) {
      if (this.pausePreviousState[taskAID]) {
        delete this.pausePreviousState[taskAID];
      }
    },

    // 初始化时从操作记录加载暂停状态
    // 初始化时加载暂停状态
    async initPauseState() {
      try {
        // 调用 loadPauseStateFromRecords 获取 stateObj
        const savedState = await this.loadPauseStateFromRecords();
        
        // 这里将 stateObj 赋值给 this.pausePreviousState
        this.pausePreviousState = savedState;
        console.log('加载暂停状态成功:', this.pausePreviousState);
      } catch (error) {
        console.error('加载暂停状态失败:', error);
        // 如果加载失败，初始化为空对象
        this.pausePreviousState = {};
      }
    },

    // 检查暂停状态是否允许操作
    checkPauseOperation(row, allowedPreviousState) {
      if (row.加工状态 === '暂停') {
        const previousState = this.pausePreviousState[row.TaskAID];
        if (!previousState) {
          // 如果没有本地状态，尝试从操作记录查询
          this.queryPauseStateFromServer(row.TaskAID);
          this.$message.error("无法确定暂停前的状态，请重新选择任务");
          return false;
        }
        return previousState === allowedPreviousState;
      }
      return true;
    },

    // 从服务器查询特定任务的暂停状态
    async queryPauseStateFromServer(taskAID) {
      try {
        const params = [];
        params.push(["TaskAID", taskAID]);
        
        const Data = this.CreateData("11", "MES_操作记录_获取任务暂停状态", params);
        const response = await this.ExecDatabase(Data);
        if (response.data && response.data.length > 0) {
          console.log(response.data[0].PreviousState)
          this.pausePreviousState[taskAID] = response.data[0].PreviousState;
        }
      } catch (error) {
        console.error('查询暂停状态失败:', error);
      }
    },


    tableRowClassName({ row, rowIndex }) {
      const isUrgent = row.优先 === '是' || row.加急 === '加急' ;
      if (isUrgent) {
        return 'priority-row';
      }
      return '';
    },
    filterstate(state) {
      var filterData = [];
      var table = this.tableDataBack;
      if (state === "1") {
        this.tableData = table;
      } else if (state === "2") {
        table.forEach((item) => {
          if (item.首检 === "OK") {
            filterData.push(item);
          }
        });
        this.tableData = filterData;
      } else if (state === "3") {
        table.forEach((item) => {
          if (item.序检 === "OK") {
            filterData.push(item);
          }
        });
        this.tableData = filterData;
      } else if (state === "4") {
        table.forEach((item) => {
          if (item.优先 === "是") {
            filterData.push(item);
          }
        });
        this.tableData = filterData;
      } else if (state === "5") {
        table.forEach((item) => {
          if (item.加急 === "加急") {
            filterData.push(item);
          }
        });
        this.tableData = filterData;
      }
    },
    getDoing() {
      var Data = this.CreateData("11", "MES_登录_工位与名称_查询");
      this.ExecDatabase(Data).then((response) => {
        this.loading = false;
        if (response.data.length !== 0) {
          this.Doingoptions = response.data;
        }
      });
    },
    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
      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}`;
    },
    getScoreStyle(bgcolor) {
      if (bgcolor == "可执行") {
        return {
          backgroundColor: "#f0f9eb",
          color: "#67c23a",
        };
      } else if (bgcolor == "已完成") {
        return {
          backgroundColor: "#ecf5ff",
          color: "#409eff",
        };
      } else if (bgcolor == "已开工") {
        return {
          backgroundColor: "#fdf6ec",
          color: "#e6a23c",
        };
      } else if (bgcolor == "开始加工"  ||  bgcolor == "辅助开始") {
        return {
          backgroundColor: "#f0f9eb",
          color: "#67c23a",
        };
      }  else if (bgcolor == "暂停") {
        return {
          backgroundColor: "#fdf6ec",
          color: "#e6a23c",
        };
      }else if (bgcolor == "报工" ||  bgcolor == "辅助结束") {
        return {
          backgroundColor: "#ecf5ff",
          color: "#409eff",
        };
      }
    },
    getProcessList() {
      this.processList2 = [];
      var Data = this.CreateData("11", "Prog_MES_LoadProcess");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.processList2.push({
            label: response.data[i].工序名称,
            value: response.data[i].工艺编号,
          });
        }
      });
    },
    getTypeList() {
      this.typeList = [];
      var Data = this.CreateData("11", "查询字典");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          // 假设 YL_基础表_数据字典 返回的字段是 DictName 和 DictID
          if (response.data[i].数据类别 === "检测类型") {
            this.typeList.push({
              label: response.data[i].词条名称,
              value: response.data[i].词条编号,
            });
          }
        }
      });
    },
    getOperationPersonList() {
      this.operationPersonList = [];
      var Data = this.CreateData("11", "人员管理_人员信息查询_质检部门_查询");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.operationPersonList.push({
            label: response.data[i].Personnel_Name,
            value: response.data[i].account,
          });
        }
      });
    },
    assiststart() {
      var row = this.selectedRow;
      if (!row) {
        this.$message.warning("请先选择一行数据");
        return;
      }
      
      // 如果当前是暂停状态，检查暂停前是否是辅助开始
      if (row.加工状态 === '暂停') {
        const previousState = this.pausePreviousState[row.TaskAID];
        if (previousState !== '辅助开始') {
          this.$message.error("当前暂停状态是基于开始加工，只能点击开始加工");
          return;
        }
      } else {
        // 正常状态的限制条件
        const validTaskStatus = ['可执行', '已开工'];
        const validProcessStatus = ['报工', '暂停', '', '辅助结束'];
        
        if (!validTaskStatus.includes(row.任务状态) || !validProcessStatus.includes(row.加工状态)) {
          this.$message.error("当前任务状态或加工状态不允许进行辅助开始操作");
          return;
        }
      }
      
      const params = [];
      params.push(["TaskAID", row.TaskAID]);
      params.push(["optor", this.$store.state.user.name]);
      const Data = this.CreateData("12", "MES_ProductTask_HelpStart", params);
      this.ExecDatabase(Data)
        .then(() => {
          this.$message.success("辅助开始操作成功");
          this.searchTable();
        })
        .catch(() => {
          this.$message.error("保存失败");
        });
    },
    assistend() {
      var row = this.selectedRow;
      if (!row) {
        this.$message.warning("请先选择一行数据");
        return;
      }
      
      // 限制条件：任务状态为可执行或已开工，加工状态为辅助开始
      const validTaskStatus = ['可执行', '已开工'];
      const validProcessStatus = ['辅助开始'];
      
      if (!validTaskStatus.includes(row.任务状态) || !validProcessStatus.includes(row.加工状态)) {
        this.$message.error("当前任务状态应为可执行或已开工，加工状态应为辅助开始");
        return;
      }
      
      this.assistendVisible = true;
      const param = [];
      param.push(["TaskAID", row.TaskAID]);
      var Data = this.CreateData("11", "Prog_MES_GetProductOrder_byAID", param);
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.assistendData = response.data[0];
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    receive() {
      var row = this.selectedRow;
      if(!row){
        this.$message.warning("请先选择一行数据");
        return;
      }
        this.receiveVisible = true;
        const param = [];
        param.push(["TaskAID", row.TaskAID]);
        var Data = this.CreateData("11", "Prog_MES_GetProductOrder_byAID", param);
        this.ExecDatabase(Data)
          .then((response) => {
            this.loading = false;
            if (response.data.length !== 0) {
              this.receiveData = response.data[0];
              this.receiveNummodel = response.data[0].指派数量;
            }
          })
          .catch(() => {
            this.loading = false;
          });
      
      
    },
    formatDate(date) {
      if (!date) return "";
      return date.split(" ").length > 1 ? date.split(" ")[0] : date;
    },
    logusername() {
      return this.name;
    },
    funassistNum(num) {
      console.log(num)
      this.assistNumber = num;
      
    },
    funreceiveNum(num) {
      this.receiveNum = num;
    },
    funreceiveperson(userId) {
      const selectedUser = this.userList.find((user) => user.id === userId)
      if (selectedUser) {
        this.selectedOperatorsName = selectedUser.name
      }
    },
    funworkStartNum(num) {
      this.workStartNum = num;
    },
    funproReportNum(num) {
      this.proReportNum = num;
    },
    funrptDesc(txt) {
      this.rptDesc = txt;
    },
    searchTable() {
      this.loading = true;
      this.tableData = [];
      var param = [];
      param.push(["TaskAID", this.TaskAID || 0]);
      param.push(["订单号", this.orderNo2 || 0]);
      param.push(["零件编号", this.productCode2]);
      param.push([
        "计划开工_Start" , "",
      ]);
      param.push([
        "计划开工_End", "",
      ]);
      param.push(["生产状态", this.productionStatus2]||-1);
      param.push(["工位名称", this.Doing]);
      param.push(["用户ID" , this.$store.state.user.id])
      param.push(["计划号" , this.plannum])
      param.push(["销售订单" , this.salenum])
      var Data = this.CreateData("11", "MES_ProductCenter_GetTask", param);
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          
          // 完整的优先级映射
          const priorityLevel = {
            '高': 3,
            '中': 2, 
            '低': 1,
            '是': 1,
            '否': 0,
            '加急': 4,
            '紧急': 4,
            '一般': 2
          };
          
          if (response.data && response.data.length !== 0) {
          
            this.tableData = response.data;
            
            this.tableData.sort((a, b) => {
              // 1. 首先按任务状态排序（2 > 1 > 0）
              const statusOrder = { '开始加工': 3,'辅助开始':3 }; // 2最高，1次之，0最低
              const aStatus = statusOrder[a.加工状态] || 0;
              const bStatus = statusOrder[b.加工状态] || 0;

              if (aStatus !== bStatus) {
                return bStatus - aStatus; // 数值大的在前
              }

              // // 2. 然后按加急状态排序
              // const aIsUrgent = a.加急 === '加急';
              // const bIsUrgent = b.加急 === '加急';

              // if (aIsUrgent && !bIsUrgent) return -1;
              // if (!aIsUrgent && bIsUrgent) return 1;

              // // 3. 按优先级排序（数值大的在前）
              // const aPriority = priorityLevel[a.优先] || 0;
              // const bPriority = priorityLevel[b.优先] || 0;

              // if (aPriority !== bPriority) {
              //   return bPriority - aPriority;
              // }

              // 4. 按计划开始时间排序（早的在前）
              const aStartTime = a.计划开始 ? new Date(a.计划开始).getTime() : Infinity;
              const bStartTime = b.计划开始 ? new Date(b.计划开始).getTime() : Infinity;

              if (aStartTime !== bStartTime) {
                return aStartTime - bStartTime; // 时间早的在前
              }

              // 5. 优先级相同，按订单号排序（安全比较）
              const aOrderNo = String(a.订单号 || '');
              const bOrderNo = String(b.订单号 || '');

              if (aOrderNo !== bOrderNo) {
                return aOrderNo.localeCompare(bOrderNo);
              }

              // 6. 订单号相同，按拆分内码排序（安全比较）
              const aSplitCode = Number(a.订单拆分内码) || 0;
              const bSplitCode = Number(b.订单拆分内码) || 0;
              return aSplitCode - bSplitCode;
              
            });
            
          
            this.tableDataBack = [...this.tableData];
          } else {
            console.log("没有获取到数据");
            this.tableData = [];
            this.tableDataBack = [];
          }
        })
        .catch((error) => {
          this.loading = false;
          console.error("请求失败:", error);
        });
    },

    //处理表格行点击事件
    handleRowClick(row) {
      console.log(this);
      this.selectedRow = row;
      this.taskstate = row.任务状态;
      this.taskprogress = (parseInt(row.完成数量) / parseInt(row.分配数)) * 100;
      this.WorkTimeSum(row.TaskAID);
      // this.startworktime = parseInt((new Date(this.currentTime) - new Date(row.开工时间)) / 60000)
    },
    WorkTimeSum(row) {
      var param = [];
      param.push([
        "计划开工_Start",
        this.completionTime ? this.completionTime[0] : "",
      ]);
      param.push([
        "计划开工_End",
        this.completionTime ? this.completionTime[1] : "",
      ]);
      var Data = this.CreateData("11", "MES_ProductTask_WorkTimeSum", param);
      this.ExecDatabase(Data)
        .then((response) => {
          console.log(response.data);
          response.data.forEach((item) => {
            if (item.TaskAID == row) {
              this.startworktime = item.总工时;
            }
          });
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async assistendForm() {
      var row = this.selectedRow;
      
      // 验证数量
      if (Number(this.assistNumber) < 0) {
        return this.$message.error("请输入正确数量");
      }
      if (this.assistNumber > row.上序合格数 && row.订单行号 > 1) {
        this.$message.error('数量输入错误')
        return
      }
      if (this.selectedOperators == '') {
        this.$message.error('请选择调机人员')
        return
      }
      
      // 加班相关变量初始化
      let overtimeResult = null
      let ordinaryPersons = ''
      let specialPersons = ''
      let isOvertime = 0
      let isRestDay = 0
      let isLegalRestDay = 0
      let selectedShiftName = ''
      let shiftStandardHours = 0
      
      try {
        // ⭐ 直接弹出加班确认弹窗
        overtimeResult = await this.showOvertimeDialog()
        
        if (overtimeResult) {
          isOvertime = overtimeResult.isOvertime || 0
          isRestDay = overtimeResult.isRestDay || 0
          isLegalRestDay = overtimeResult.isLegalRestDay || 0
          selectedShiftName = overtimeResult.selectedShift || this.shift
          shiftStandardHours = overtimeResult.shiftStandardHours || this.shiftStandardHours || 0

          if (overtimeResult.persons && overtimeResult.persons.length > 0) {
            // 添加调机人员到加班人员列表
            const allOvertimePersons = [...overtimeResult.persons]
            if (this.selectedOperatorsName && !allOvertimePersons.includes(this.selectedOperatorsName)) {
              allOvertimePersons.push(this.selectedOperatorsName)
            }

            ordinaryPersons = overtimeResult.ordinaryPersons ? overtimeResult.ordinaryPersons.join(',') : ''
            specialPersons = overtimeResult.specialPersons ? overtimeResult.specialPersons.join(',') : ''
          }
        } else if (overtimeResult === null || overtimeResult === undefined) {
          // 用户关闭了弹窗，询问是否继续
          const continueReport = await this.$confirm('未记录加班信息，是否继续辅助结束？', '提示', {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => false)
          
          if (!continueReport) {
            return
          }
        }
      } catch (error) {
        console.log('用户取消了加班弹框:', error)
        return
      }
      
      // 构建参数并调用存储过程
      const params = [];
      params.push(["TaskAID", row.TaskAID]);
      params.push(["optor", this.$store.state.user.name]);
      params.push(["partCount", this.assistNumber]);
      params.push(["指派数量", row.分配数]);
      params.push(["selectedOperators", this.selectedOperators]);
      
      // 添加加班参数
      params.push(['加班人员', ordinaryPersons]);
      params.push(['特殊加班人员', specialPersons]);
      params.push(['是否加班', isOvertime]);
      params.push(['是否休息日', isRestDay]);
      params.push(['是否法定休息日', isLegalRestDay]);
      params.push(['用户选择班次', selectedShiftName]);
      params.push(['班次标准工时', shiftStandardHours]);
      
      console.log('辅助结束参数:', params)
      
      const Data2 = this.CreateData("11", "MES_ProductTask_HelpEnd", params);
      this.ExecDatabase(Data2)
        .then((response) => {
          this.$message.success("辅助结束操作成功");
          this.assistendVisible = false;
          this.assistNumber = 0;
          this.searchTable();
          this.selectedOperators = ''
        })
        .catch(() => {
          this.$message.error("保存失败");
        })
        .finally(() => {});
    },
    receiveForm() {
      const params = [];
      var row = this.selectedRow;
      console.log(this.receiveData.上序合格数)
      if (!this.receiveNum) {
        this.$message.error('数量输入错误')
        return
      }
      if (this.receiveNum > this.receiveData.指派数量 - this.receiveData.收料数量) {
        this.$message.error('数量输入错误')
        return
      }
      if (this.receiveNum > this.receiveData.上序合格数 & this.receiveData.订单行号>1) {
        this.$message.error('数量输入错误')
        return
      }
      
      params.push(["TaskAID", row.TaskAID]);
      params.push(["optor", this.$store.state.user.name]);
      params.push(["recievCount", this.receiveNum]);
      const Data = this.CreateData(
        "12",
        "MES_ProductTask_MaterialRecieved",
        params
      );
      this.ExecDatabase(Data)
        .then(() => {
          this.$message.success("收料操作成功");
          this.receiveVisible = false;
          this.receiveNum = 0;
          this.searchTable();
        })
        .catch(() => {
          this.$message.error("保存失败");
        })
        .finally(() => {});
    },
    pause() {
      var row = this.selectedRow;
      if (!row) {
        this.$message.warning("请先选择一行数据");
        return;
      }
      
      // 限制条件：任务状态为可执行或已开工，加工状态为辅助开始或开始加工
      const validTaskStatus = ['可执行', '已开工'];
      const validProcessStatus = ['辅助开始', '开始加工'];
      
      if (!validTaskStatus.includes(row.任务状态) || !validProcessStatus.includes(row.加工状态)) {
        this.$message.error("当前任务状态应为可执行或已开工，加工状态应为辅助开始或开始加工");
        return;
      }
      
      // 记录暂停前的状态
      this.pausePreviousState[row.TaskAID] = row.加工状态;
      this.$message.error('任务不允许暂停，请点击结束')
      // const params = [];
      // params.push(["TaskAID", row.TaskAID]);
      // params.push(["optor", this.$store.state.user.name]);
      // const Data = this.CreateData("12", "MES_ProductTask_Rest", params);
      // this.ExecDatabase(Data)
      //   .then(() => {
      //     this.$message.success("暂停操作成功");
      //     this.searchTable();
      //   })
      //   .catch(() => {
      //     this.$message.error("保存失败");
      //   });
    },
    async workStart() {
      var row = this.selectedRow;
      if (!row) {
        this.$message.warning("请先选择一行数据");
        return;
      }
      
      try {
        // 1. 先检查设备是否正在加工
        const params = [];
        params.push(["指派对象", row.指派对象]);
        var Data = await this.CreateData("11", "生产管理_加工中心_设备是否正在加工", params);
        const response = await this.ExecDatabase(Data);
        
        if (response.data && response.data.length > 0) {
          this.$message.error(`${response.data[0].订单编号},${response.data[0].工序名称}正在加工`);
          return;
        }
        
        // 2. 设备空闲，继续检查状态
        // 如果当前是暂停状态，检查暂停前是否是开始加工
        if (row.加工状态 === '暂停') {
          console.log(this.pausePreviousState)
          const previousState = this.pausePreviousState[row.TaskAID];
          if (previousState !== '开始加工') {
            this.$message.error("当前暂停状态是基于辅助开始，只能点击辅助开始");
            return;
          }
        } else {
          // 正常状态的限制条件
          const validTaskStatus = ['可执行', '已开工'];
          const validProcessStatus = ['报工', '暂停', '', '辅助结束'];
          
          if (!validTaskStatus.includes(row.任务状态) || !validProcessStatus.includes(row.加工状态)) {
            this.$message.error("当前任务状态应为可执行或已开工，加工状态应为报工、暂停、空或辅助结束");
            return;
          }
        }
        
        // 3. 所有验证通过，打开弹窗并获取任务详情
        this.workStartVisible = true;
        const param = [];
        param.push(["TaskAID", row.TaskAID]);
        var Data2 = this.CreateData("11", "Prog_MES_GetProductOrder_byAID", param);
        const response2 = await this.ExecDatabase(Data2);
        
        this.loading = false;
        if (response2.data && response2.data.length !== 0) {
          this.workStartData = response2.data[0];
        }
        
      } catch (error) {
        console.error("workStart error:", error);
        this.loading = false;
        this.$message.error("操作失败，请重试");
      }
    },
    workStartForm() {
      const params = [];
      var row = this.selectedRow;
      // if (!this.workStartNum) {
      //   this.workStartNum = this.workStartData.指派数量;
      // }
      params.push(["TaskAID", row.TaskAID]);
      params.push(["optor", this.$store.state.user.name]);
      params.push(['收料', row.收料])
      params.push(['分配数', row.分配数])
      // params.push(['辅助数', this.workStartNum])
      const Data = this.CreateData(
        "12",
        "MES_ProductTask_WorkingStart",
        params
      );
      this.ExecDatabase(Data)
        .then(() => {
          this.$message.success("开始加工操作成功");
          this.workStartVisible = false;
          this.workStartNum = 0;
          this.searchTable();
        })
        
    },

    prodReport() {
      var row = this.selectedRow
      if (!row) {
        this.$message.warning('请先选择一行数据')
        return
      }

      const validTaskStatus = ['可执行','已开工']
      const validProcessStatus = ['开始加工']

      if (!validTaskStatus.includes(row.任务状态) || !validProcessStatus.includes(row.加工状态)) {
        this.$message.error('当前任务状态应为已开工，加工状态应为开始加工')
        return
      }

      const params = []
      params.push(['TaskAID', row.TaskAID])
      this.prodReportData = []

      var Data = this.CreateData('11', 'MES_ProductCenter_GetOrderTasks', params)
      this.ExecDatabase(Data)
        .then(async (response) => {
          this.loading = false
          if (response.data.length !== 0) {
            this.prodReportData = response.data
            this.prodReportDataTop = response.data[0]
            this.prodReportVisible = true
            this.proReportNum = 0
            response.data.forEach((element, index) => {
              if (element.TaskAID == row.TaskAID) {
                setTimeout(() => {
                  this.$refs.multipleTable.toggleRowSelection(this.prodReportData[index])
                }, 100)
              }
            })
            // 获取班次配置
            let shiftConfig = []
            try {
              const shiftParams = this.CreateData('11', '生产管理_加工中心_班次信息', [])
              const shiftResponse = await this.ExecDatabase(shiftParams)
              shiftConfig = shiftResponse.data || []
              this.shiftConfig = shiftConfig
            } catch (error) {
              console.error('获取班次配置失败:', error)
            }

            // 获取任务的开始时间
            var param4 = []
            param4.push(['TaskAID', row.TaskAID])
            const data4 = this.CreateData('11', '生产管理_加工中心_开始时间', param4)
            const result4 = await this.ExecDatabase(data4)

            const Strtime = this.formatDateTime(result4.data[0].开始时间)
            console.log('任务开始时间:', Strtime)

            // 保存任务开始时间
            this.taskStartTime = Strtime
            console.log('班次配置:', shiftConfig)

            // 根据开始时间判断原始所属班次
            let originalShift = this.determineShift(Strtime, shiftConfig)
            this.originalShift = originalShift
            this.currentShift = originalShift
            this.shift = originalShift.班次名称
            this.selectedShiftName = originalShift.班次名称
            console.log('任务开始时间:', Strtime)
            console.log('任务开始时间对应的班次:', this.shift)
            // 原有的选中行逻辑
            // response.data.forEach((element, index) => {
            //   if (element.TaskAID == row.TaskAID) {
            //     setTimeout(() => {
            //       this.$refs.multipleTable.toggleRowSelection(this.prodReportData[index])
            //     }, 100)
            //   }
            // })
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 将时间字符串转换为分钟数
    timeToMinutes(dateTimeStr) {
      if (!dateTimeStr) return 0;
      
      let timeStr = dateTimeStr;
      if (dateTimeStr.includes(' ')) {
        timeStr = dateTimeStr.split(' ')[1];
      }
      
      const parts = timeStr.split(':');
      const hours = parseInt(parts[0]);
      const minutes = parseInt(parts[1]) || 0;
      
      return hours * 60 + minutes;
    },
    // 根据时间判断所属班次
    // 根据时间判断所属班次
determineShift(dateTime, shiftConfig) {
  console.log('determineShift 被调用, dateTime:', dateTime)
  
  if (!shiftConfig || shiftConfig.length === 0) {
    console.log('班次配置为空')
    return { 班次名称: '白班' }
  }
  
  // 获取时间的分钟数
  const minutes = this.timeToMinutes(dateTime)
  console.log('时间分钟数:', minutes)
  
  for (const shift of shiftConfig) {
    // ⭐ 直接使用 TimeSpan 对象的 Hours 和 Minutes
    let startMinutes = (shift.开始时间?.Hours || 0) * 60 + (shift.开始时间?.Minutes || 0)
    let endMinutes = (shift.结束时间?.Hours || 0) * 60 + (shift.结束时间?.Minutes || 0)
    
    console.log(`班次: ${shift.班次名称}, 开始: ${startMinutes}, 结束: ${endMinutes}`)
    
    // 跨天班次处理
    if (endMinutes < startMinutes) {
      if (minutes >= startMinutes || minutes <= endMinutes) {
        console.log(`匹配到跨天班次: ${shift.班次名称}`)
        return { 班次名称: shift.班次名称 }
      }
    } else {
      if (minutes >= startMinutes && minutes <= endMinutes) {
        console.log(`匹配到正常班次: ${shift.班次名称}`)
        return { 班次名称: shift.班次名称 }
      }
    }
  }
  
  console.log('未匹配到班次，返回默认白班')
  return { 班次名称: '白班' }
},
    // 辅助方法：获取班次结束时间对应的日期时间
    getShiftEndDateTime(currentDateTime, currentShift) {
      const currentDate = new Date(currentDateTime.replace(' ', 'T'));
      const endTimeObj = currentShift.结束时间;
      const shiftEndDate = new Date(currentDate);
      shiftEndDate.setHours(endTimeObj.Hours, endTimeObj.Minutes || 0, 0, 0);
      
      // 判断是否为跨天班次
      const startTimeObj = currentShift.开始时间;
      const isCrossDay = endTimeObj.Hours < startTimeObj.Hours || 
                        (endTimeObj.Hours === startTimeObj.Hours && endTimeObj.Minutes < startTimeObj.Minutes);
      
      if (isCrossDay && currentDate.getHours() >= 12) {
        // 晚上时段，结束时间是第二天
        shiftEndDate.setDate(shiftEndDate.getDate() + 1);
      }
      
      return shiftEndDate;
    },
async proReportForm() {
  const params = []
  var row = this.selectedRow
  var multipleSelectionrow = this.multipleSelection
  var BindRpt_ALLtaskids = ''
  var 前序不合格总数 = ''

  if (multipleSelectionrow.length < 1) {
    return this.$message.error('请选择报工工序')
  }

  // 验证报工数量
  for (const item of multipleSelectionrow) {
    var 总数 = item.完成数量 + Number(this.proReportNum)
    if (item.上序合格数 < 总数 && item.订单行号 > 1) {
      this.$message.error('报工数量输入错误')
      return
    }
  }

  // 加班相关变量初始化（只收集用户选择）
  let overtimeResult = null
  let overtimePersons = ''
  let ordinaryPersons = ''      // ⭐ 定义普通加班人员字符串
  let specialPersons = ''       // ⭐ 定义特殊加班人员字符串
  let isOvertime = 0
  let isRestDay = 0
  let isLegalRestDay = 0
  let selectedShiftName = ''
  let shiftStandardHours = 8    // ⭐ 班次标准工时

  try {
    // 每次都弹出加班确认弹框
    overtimeResult = await this.showOvertimeDialog()
    
    if (overtimeResult) {
      isOvertime = overtimeResult.isOvertime
      isRestDay = overtimeResult.isRestDay
      isLegalRestDay = overtimeResult.isLegalRestDay
      selectedShiftName = overtimeResult.selectedShift || this.shift
      shiftStandardHours = overtimeResult.shiftStandardHours || this.shiftStandardHours || 8

      if (overtimeResult.persons && overtimeResult.persons.length > 0) {
        overtimePersons = overtimeResult.persons.join(',')           // 所有人员
        ordinaryPersons = overtimeResult.ordinaryPersons ? overtimeResult.ordinaryPersons.join(',') : ''   // 普通人员
        specialPersons = overtimeResult.specialPersons ? overtimeResult.specialPersons.join(',') : ''     // 特殊人员
      }
    } else if (overtimeResult === null || overtimeResult === undefined) {
      // 用户关闭了弹窗，询问是否继续
      const continueReport = await this.$confirm('未记录加班信息，是否继续报工？', '提示', {
        confirmButtonText: '继续报工',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => false)
      
      if (!continueReport) {
        return
      }
    }
  } catch (error) {
    console.log('用户取消了加班弹框:', error)
    return
  }

  // 构建报工参数
  multipleSelectionrow.forEach((item) => {
    BindRpt_ALLtaskids = BindRpt_ALLtaskids + item.TaskAID + ','
    if (!item.前序不合格数) {
      item.前序不合格数 = 0
    }
    前序不合格总数 = 前序不合格总数 + item.前序不合格数 + ','
  })

  params.push(['TaskAID', row.TaskAID])
  params.push(['前序不合格总数', 前序不合格总数])
  params.push(['BindRpt_ALLtaskids', BindRpt_ALLtaskids])
  params.push(['rptDate', this.currentTime])
  params.push(['rptShift', this.shift])
  params.push(['partCount', this.proReportNum])
  params.push(['rptDesc', this.rptDesc])
  params.push(['optor', this.$store.state.user.name])
  
  // ⭐ 只传递用户选择的参数，不传递时长
  params.push(['加班人员', ordinaryPersons])           // 普通加班人员
  params.push(['特殊加班人员', specialPersons])        // 特殊加班人员
  params.push(['是否加班', isOvertime])                 // 0或1
  params.push(['是否休息日', isRestDay])                // 0或1
  params.push(['是否法定休息日', isLegalRestDay])       // 0或1
  params.push(['用户选择班次', selectedShiftName])      // 班次名称
  params.push(['班次标准工时', shiftStandardHours])     // 班次标准工时（分钟），前端手动输入的值
  const Data3 = this.CreateData('11', 'MES_ProductTask_ProdReport', params)

  this.ExecDatabase(Data3)
    .then(() => {
      this.$message.success('报工操作成功')
      this.prodReportVisible = false
      this.proReportNum = 0
      this.multipleSelection = ''
      this.searchTable()
    })
    .catch((error) => {
      this.$message.error('报工失败：' + error.message)
    })
},
    formatTimeSpanToHHmm(timeSpan) {
      const hours = timeSpan.Hours.toString().padStart(2, '0');
      const minutes = timeSpan.Minutes.toString().padStart(2, '0');
      
      return `${hours}:${minutes}`;
    },
    formatOvertimeHours(timeSpan) {
      if (timeSpan.TotalHours <= 0) {
        return '0分钟';
      }
      
      if (timeSpan.Hours >= 1) {
        if (timeSpan.Minutes === 0) {
          return `${timeSpan.Hours}小时`;
        } else {
          return `${timeSpan.Hours}小时${timeSpan.Minutes}分钟`;
        }
      } else {
        return `${Math.round(timeSpan.TotalMinutes)}分钟`;
      }
    },
    // 获取加班人员选项
    // getOvertimePersonOptions() {
    //   // 这里可以从接口获取可加班人员列表
    //   // 暂时返回示例数据
    //   var params = []
    //   params.push(["指派对象", this.selectedRow.指派对象]);
    //   params.push(["班次", this.currentShift.班次名称]);
    //   const Data = this.CreateData("11", "生产管理_加工中心_获取设备人员", params);
      
    //   this.ExecDatabase(Data)
    //     .then((response) => {
    //       var person = []
    //       if (this.selectedOperators !=''){
    //         person.push({ value: this.selectedOperatorsName, label: this.selectedOperatorsName  })
    //       }
    //       response.data.forEach(element => {
    //         person.push({ value: element.人员名称, label: element.人员名称 })
    //         this.overtimeOptions = person
    //         console.log(this.overtimeOptions)
    //       });
    //     })
    //   // return [
    //   //   { value: '张三', label: '张三' },
    //   //   { value: '李四', label: '李四' },
    //   //   { value: '王五', label: '王五' }
    //   // ];
    // },

    // 计算加班时长
    // 计算加班时长
    // 计算加班时长
    // 计算加班时长
    calculateOvertimeHours(startDateTime, currentDateTime, shiftEndTime, isCrossShift) {
      // 将参数统一转换为 Date 对象
      let startDate, currentDate;
      
      // 处理开始时间
      if (startDateTime instanceof Date) {
        startDate = startDateTime;
      } else if (typeof startDateTime === 'string') {
        startDate = new Date(startDateTime.replace(' ', 'T'));
        // 如果转换失败，尝试直接解析
        if (isNaN(startDate.getTime())) {
          startDate = new Date(startDateTime);
        }
      } else {
        startDate = new Date(startDateTime);
      }
      
      // 处理当前时间
      if (currentDateTime instanceof Date) {
        currentDate = currentDateTime;
      } else if (typeof currentDateTime === 'string') {
        currentDate = new Date(currentDateTime.replace(' ', 'T'));
        if (isNaN(currentDate.getTime())) {
          currentDate = new Date(currentDateTime);
        }
      } else {
        currentDate = new Date(currentDateTime);
      }
      
      // 检查日期是否有效
      if (isNaN(startDate.getTime()) || isNaN(currentDate.getTime())) {
        console.error('无效的日期时间参数:', { startDateTime, currentDateTime });
        return {
          Days: 0,
          Hours: 0,
          Minutes: 0,
          Seconds: 0,
          TotalHours: 0,
          TotalMinutes: 0
        };
      }
      
      console.log('任务开始时间:', startDate);
      console.log('当前时间:', currentDate);
      
      let diffMs;
      
      if (isCrossShift) {
        // 场景二：跨班次加班，加班时长 = 当前时间 - 任务开始时间
        diffMs = currentDate - startDate;
        console.log('跨班次加班，从任务开始计算');
      } else {
        // 场景一：班次内加班，需要计算班次结束时间
        const endTime = new Date(currentDate);
        endTime.setHours(shiftEndTime.Hours, shiftEndTime.Minutes || 0, 0, 0);
        
        // 处理跨天班次
        if (currentDate.getHours() < 12 && shiftEndTime.Hours < 12) {
          // 凌晨时段，结束时间是当天
        } else if (currentDate.getHours() >= 12 && shiftEndTime.Hours < 12) {
          // 晚上时段，结束时间是第二天
          endTime.setDate(endTime.getDate() + 1);
        }
        
        console.log('班次结束时间:', endTime);
        diffMs = currentDate - endTime;
        console.log('班次内加班，从班次结束计算');
      }
      
      if (diffMs <= 0) {
        console.log('未到加班时间');
        return {
          Days: 0,
          Hours: 0,
          Minutes: 0,
          Seconds: 0,
          TotalHours: 0,
          TotalMinutes: 0
        };
      }
      
      const diffMinutes = Math.floor(diffMs / (1000 * 60));
      const hours = Math.floor(diffMinutes / 60);
      const minutes = diffMinutes % 60;
      
      console.log('加班时长:', hours, '小时', minutes, '分钟');
      
      return {
        Days: Math.floor(hours / 24),
        Hours: hours % 24,
        Minutes: minutes,
        Seconds: 0,
        TotalHours: diffMinutes / 60,
        TotalMinutes: diffMinutes
      };
    },
    // proReportForm() {
    //   const params = [];
    //   var row = this.selectedRow;
    //   var multipleSelectionrow = this.multipleSelection;
    //   var BindRpt_ALLtaskids = "";
    //   var 前序不合格总数 = "";
    //   if (multipleSelectionrow.length < 1) {
    //     return this.$message.error("请选择报工工序");
    //   }
    //   // if (!this.proReportNum) {
    //   //   this.proReportNum = this.prodReportDataTop.指派数量;
    //   // }
    //   for (const item of multipleSelectionrow) {
    //     console.log(item.上序合格数)
        
    //     console.log(Number(this.proReportNum))
    //     var 总数 = item.完成数量 + Number(this.proReportNum)
    //     console.log(总数)
    //     if (item.上序合格数 < 总数  & item.订单行号>1) {
    //       this.$message.error("报工数量输入错误");
    //       return; 
    //     }
    //   }
    //   multipleSelectionrow.forEach((item) => {
    //     var ba = "";
    //     ba = item.TaskAID;
    //     BindRpt_ALLtaskids = BindRpt_ALLtaskids + ba + ",";
    //     if(!item.前序不合格数){
    //       item.前序不合格数 = 0
    //     }
    //     前序不合格总数 = 前序不合格总数 + item.前序不合格数 + ",";
    //   });
    //   console.log(前序不合格总数)
    //   // return
    //   params.push(["TaskAID", row.TaskAID]);
    //   params.push(["前序不合格总数", 前序不合格总数]);
    //   params.push(["BindRpt_ALLtaskids", BindRpt_ALLtaskids]);
    //   params.push(["rptDate", this.currentTime]);
    //   params.push(["rptShift", this.shift]);
    //   params.push(["partCount", this.proReportNum]);
    //   params.push(["rptDesc", this.rptDesc]);
    //   params.push(["optor", this.$store.state.user.name]);
    //   const Data = this.CreateData("11", "MES_ProductTask_ProdReport", params);
    //   this.ExecDatabase(Data)
    //     .then((response) => {

    //         this.$message.success("报工操作成功");
    //         this.prodReportVisible = false;
    //         this.proReportNum = 0;
    //         this.multipleSelection = "";
    //         this.searchTable();

    //     })

    // },
    Doingform(value){
      console.log(value)
      this.station = ''
    },
    // Doingform(Dingid) {
    //   var params = [];
    //   params.push(["指派对象编号", Dingid]);
    //   var Data = this.CreateData("11", "MES_ProductCenter_DoingTask", params);
    //   this.ExecDatabase(Data)
    //     .then((response) => {
    //       this.loading = false;
    //       if (response.data.length !== 0) {
    //         this.DoingData = response.data[0];
    //       } else {
    //         this.DoingData = {
    //           订单编号: "",
    //           合同号: "",
    //           物料编号: "",
    //           指派数量: "",
    //           完成数量: "",
    //         };
    //       }
    //     })
    //     .catch(() => {
    //       this.loading = false;
    //     });
    // },
    handleInspectionCountChange(count) {
      if (count > 0) {
        // 初始化检测数据数组
        this.inspectionData = [];
        for (let i = 0; i < count; i++) {
          // 为每个检测项创建副本
          this.inspectionData.push(
            JSON.parse(JSON.stringify(this.tableData2)).map((item) => {
              return {
                ...item,
                检测结果: "1", // 默认选中"合格"
                实测值: "",
              };
            })
          );
        }
        this.currentPage = 1; // 重置到第一页
      } else {
        this.inspectionData = [];
      }
    },
    // 获取当前页的数据
    getCurrentPageData() {
      const pageIndex = this.currentPage - 1;

      if (
        this.inspectionData.length > 0 &&
        pageIndex >= 0 &&
        this.inspectionData[pageIndex]
      ) {
        console.log(
          `获取第${this.currentPage}页数据:`,
          this.inspectionData[pageIndex].map((item) => ({
            检测项目: item.检测项目,
            实测值: item.实测值,
            检测结果: item.检测结果,
          }))
        );

        return this.inspectionData[pageIndex];
      }

      console.warn(`第${this.currentPage}页数据不存在`);
      return [];
    },
    // 更新检测数据
    updateInspectionData(item, pageIndex) {
      console.log("开始更新检测数据:", {
        页面索引: pageIndex,
        当前项目: item,
        检测项目: item.检测项目,
        实测值: item.实测值,
      });

      if (!this.inspectionData[pageIndex]) {
        console.error(`页面索引 ${pageIndex} 不存在`);
        return;
      }

      // 直接使用数组索引更新，避免查找问题
      const itemIndex = this.inspectionData[pageIndex].findIndex((i) => {
        const found = i.检测项目 === item.检测项目;
        console.log("查找项目:", {
          当前检测项目: i.检测项目,
          目标检测项目: item.检测项目,
          是否匹配: found,
        });
        return found;
      });

      console.log("查找到的项目索引:", itemIndex);

      if (itemIndex !== -1) {
        // 创建新对象确保响应式更新
        const updatedItem = {
          ...this.inspectionData[pageIndex][itemIndex],
          实测值: item.实测值,
          检测结果: item.检测结果,
        };

        // 使用 Vue.set 确保响应式
        this.$set(this.inspectionData[pageIndex], itemIndex, updatedItem);

        console.log("更新后的数据:", {
          页面: pageIndex,
          索引: itemIndex,
          新实测值: updatedItem.实测值,
          新检测结果: updatedItem.检测结果,
        });

        // 更新合格数
        this.updateQualifiedCount();
      } else {
        console.error("未找到对应的检测项目:", item.检测项目);
      }
    },

    // 首检自检弹框信息加载
    firstCheck() {
      var row = this.selectedRow;
      if (!row) {
        this.$message.warning("请先选择一行数据");
        return;
      }

      // 初始化firstCheckData和当前检测零件编号
      this.firstCheckData = {
        ...this.firstCheckData,
        TaskAID: row.TaskAID,
        检验人: this.$store.state.user.name,
        检验时间: this.currentTime,
        检测数量: 1,
        合格数: 1,
      };

      this.currentPage = 1;
      this.currentInspectionItem = 1; // 初始化当前检测零件编号为1
      this.inspectionData = [];
      this.firstCheckVisible = true;

      // 先获取产品订单信息
      const param = [];
      param.push(["TaskAID", row.TaskAID]);
      var Data = this.CreateData("11", "Prog_MES_GetProductOrder_byAID", param);

      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.firstCheckData = {
              ...response.data[0],
              TaskAID: row.TaskAID,
              检验人: this.firstCheckData.检验人,
              检验时间: this.firstCheckData.检验时间,
              检测数量: this.firstCheckData.检测数量,
              合格数: this.firstCheckData.合格数,
            };
          }
        })
        .then(() => {
          // 继续执行其他操作
          return this.searchTable2();
        })
        .then(() => {
          // 初始化检测数据
          this.handlePageChange();
          this.$message.info(`开始检测第 ${this.currentInspectionItem} 件`);
        })
        .catch((error) => {
          this.loading = false;
          console.error("首检自检初始化失败:", error);
          this.$message.error("初始化失败: " + error.message);
        });
    },

    // 首检自检弹框保存，用于最终确认提交
    submitQualityData() {
      // 现在这个方法可以用于最终确认提交所有数据
      this.saveCurrentPageData().then((success) => {
        if (success) {
          this.$message({
            message: `所有质检数据提交完成，共检测 ${this.firstCheckData.检测数量} 件`,
            type: "success",
          });
          this.firstCheckVisible = false;
          this.searchTable();
        } else {
          this.$message.error("最终提交失败，请检查数据");
        }
      });
    },
    // 首检自检更新合格数的方法
    updateQualifiedCount() {
      // 合格数 = 检测数量 - 不合格页数
      this.firstCheckData.合格数 =
        this.firstCheckData.检测数量 - this.unqualifiedCount;
    },
    // 修改删除当前页的方法，在删除前保存数据
    confirmDeleteCurrentPage() {
      if (this.firstCheckData.检测数量 <= 1) {
        this.$message.warning("至少需要保留一个检测页");
        return;
      }

      this.$confirm("确定要删除当前检测页吗？删除后将无法恢复。", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 先保存当前页数据
          this.saveCurrentPageData().then((success) => {
            if (success) {
              this.deleteCurrentPage();
            }
          });
        })
        .catch(() => {
          // 用户取消删除
        });
    },
    // 首检自检删除当前页
    deleteCurrentPage() {
      // 从inspectionData中移除当前页
      this.inspectionData.splice(this.currentPage - 1, 1);

      // 更新检测数量
      this.firstCheckData.检测数量--;

      // 调整当前页码
      if (this.currentPage > this.firstCheckData.检测数量) {
        this.currentPage = this.firstCheckData.检测数量;
      }

      // 更新当前检测零件编号
      this.currentInspectionItem = this.currentPage;

      // 更新合格数
      this.updateQualifiedCount();

      this.$message.success(`第 ${this.currentPage + 1} 件检测页已删除`);
    },
    // 首检自检上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.currentInspectionItem = this.currentPage;
        this.$message.info(`已切换到第${this.currentPage}页`);
      }
    },
    // 首检自检下一页
    nextPage() {
      // 先保存当前页数据
      this.saveCurrentPageData()
        .then((success) => {
          if (success) {
            // 保存成功后，再处理页面跳转
            if (this.currentPage >= this.firstCheckData.检测数量) {
              // 如果是最后一页，创建新页面
              this.firstCheckData.检测数量++;

              const newPageData = JSON.parse(
                JSON.stringify(this.tableData2)
              ).map((item) => {
                return {
                  ...item,
                  检测结果: item.检测结果 || "1",
                  实测值: item.实测值 || "",
                };
              });

              this.inspectionData.push(newPageData);
              this.firstCheckData.合格数++;
            }

            this.currentPage++;
            // 更新当前检测零件编号为下一页的页码
            this.currentInspectionItem = this.currentPage;
            this.$message.success(
              `第 ${this.currentPage - 1} 件检测数据已保存，已跳转到第 ${
                this.currentPage
              } 件检测`
            );
          } else {
            this.$message.error("保存失败，请检查数据后重试");
          }
        })
        .catch((error) => {
          console.error("保存错误:", error);
          this.$message.error("保存过程中发生错误");
        });
    },
    // 保存当前页数据的方法
    saveCurrentPageData() {
      return new Promise((resolve, reject) => {
        const currentPageData = this.getCurrentPageData();
        console.log("准备保存的数据:", currentPageData);

        // 验证数据完整性
        let isValid = true;
        let errorMessages = [];

        currentPageData.forEach((item, index) => {
          console.log(`检查项目${index}:`, item);
          if (!item.实测值 && item.实测值 !== 0) {
            isValid = false;
            const errorMsg = `"${item.检测项目}"的实测值不能为空`;
            errorMessages.push(errorMsg);
            console.error("验证失败:", errorMsg, item);
          }

          if (!item.检测结果) {
            isValid = false;
            const errorMsg = `"${item.检测项目}"的判定结果不能为空`;
            errorMessages.push(errorMsg);
            console.error("验证失败:", errorMsg, item);
          }
        });

        if (!isValid) {
          this.$message({
            message: errorMessages.join("；"),
            type: "warning",
          });
          resolve(false);
          return;
        }

        // 提交数据
        const submitPromises = [];

        currentPageData.forEach((item) => {
          const param = [];
          // 确保所有必要参数都有值
          param.push(["TaskAID", this.firstCheckData.TaskAID || -1]);
          param.push(["物料编号", this.firstCheckData.物料编号 || ""]);
          param.push(["阶段标识", this.firstCheckData.顺序编号 || -1]);
          param.push(["工序名称", this.firstCheckData.工序名称 || ""]);
          param.push(["计划号", this.firstCheckData.订单编号 || ""]);
          param.push(["检测项目", item.检测项目 || ""]);
          param.push(["理论值", item.理论值 || ""]);
          param.push(["上限值", item.上限值 || ""]);
          param.push(["下限值", item.下限值 || ""]);
          param.push(["实测值", item.实测值 || ""]);
          param.push(["测量单位", item.测量单位 || ""]);
          param.push(["检验比例", item.检验比例 || ""]);
          param.push(["检具", item.检具 || ""]);
          param.push(["检测结果", item.检测结果 === "1" ? 1 : 0]);
          param.push(["合格数", this.firstCheckData.合格数 || 0]);
          param.push([
            "不合格数",
            this.firstCheckData.检测数量 - this.firstCheckData.合格数 || 0,
          ]);
          param.push(["备注", item.备注 || ""]);
          param.push(["检测人", this.firstCheckData.检验人 || ""]);
          param.push([
            "检测时间",
            this.firstCheckData.检验时间 || new Date().toISOString(),
          ]);
          param.push(["质检类型", "首检自检"]);
          param.push(["检测类型编号", "1"]);
          param.push(["零件名称", this.firstCheckData.物料描述 || ""]);
          param.push(["内部合同号", this.firstCheckData.合同号 || ""]);
          param.push(["零件编码", this.firstCheckData.物料编号 || ""]);
          param.push(["检验数量", this.firstCheckData.检测数量 || 1]);
          param.push(["计划生产数", this.firstCheckData.计划数量 || 0]);
          param.push(["检测说明", item.备注 || ""]);
          param.push(["当前检测零件编号", this.currentPage]);
          param.push(["QT_AID", -1]);
          param.push(["LJ_AID", -1]);

          console.log("提交参数:", param);

          const data = this.CreateData(
            "12",
            "MES_QulityInspection_CheckItemData_Save",
            param
          );
          submitPromises.push(this.ExecDatabase(data));
        });

        Promise.all(submitPromises)
          .then((responses) => {
            console.log("保存响应详情:", responses);

            responses.forEach((response, index) => {
              console.log(`第${index + 1}个请求响应:`, response);
              if (!response || !response.data || !response.data[0]) {
                console.error(`第${index + 1}个请求响应格式不正确:`, response);
              } else {
                console.log(
                  `第${index + 1}个请求执行结果:`,
                  response.data[0].执行结果
                );
              }
            });

            const allSuccess = responses.every((response, index) => {
              const success =
                response &&
                response.data &&
                response.data[0] &&
                response.data[0].result === "1"; // 注意这里是字符串'1'，不是数字1
              if (!success) {
                console.error(`第${index + 1}个请求失败:`, response);
              }
              return success;
            });

            if (allSuccess) {
              this.$message.success("数据保存成功");
              resolve(true);
            } else {
              this.$message.error("部分数据保存失败");
              resolve(false);
            }
          })
          .catch((error) => {
            console.error("保存失败:", error);
            this.$message.error("保存失败: " + error.message);
            reject(error);
          });
      });
    },
    // 首检自检处理页码变化
    handlePageChange() {
      if (this.inspectionData.length === 0) {
        console.log("初始化检测数据，数量:", this.firstCheckData.检测数量);

        for (let i = 0; i < this.firstCheckData.检测数量; i++) {
          const pageData = this.tableData2.map((item, index) => {
            // 深拷贝每个项目，确保独立性
            const newItem = JSON.parse(JSON.stringify(item));
            newItem.唯一标识 = `page${i}_item${index}_${Date.now()}_${Math.random()}`;
            newItem.检测结果 = newItem.检测结果 || "1";
            newItem.实测值 = newItem.实测值 || "";

            console.log(`创建页面${i}项目${index}:`, {
              检测项目: newItem.检测项目,
              唯一标识: newItem.唯一标识,
            });

            return newItem;
          });

          this.inspectionData.push(pageData);
        }

        console.log("初始化完成，总页面数:", this.inspectionData.length);
      }
    },
    searchTable2() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        this.tableData2 = [];
        var param = [];
        console.log(this.firstCheckData)
        param.push(["物料编号", this.firstCheckData.物料编号]);
        param.push(["工序名称编号", this.firstCheckData.顺序编号]);
        param.push(["检测类别编号", 1]);

        var Data = this.CreateData(
          "11",
          "MES_QulityInspection_GetItemStandard",
          param
        );

        this.ExecDatabase(Data)
          .then((response) => {
            this.loading = false;
            if (response.data.length !== 0) {
              this.tableData2 = response.data.map((item) => {
                return {
                  ...item,
                  检测结果: item.检测结果 || "1", // 如果数据库中有检测结果则使用，否则默认为"1"
                  实测值: item.实测值 || "", // 如果数据库中有实测值则使用，否则默认为空
                };
              });
            }
            resolve();
          })
          .catch((error) => {
            this.loading = false;
            reject(error);
          });
      });
    },
    // 序检自检方法
    processCheck() {
      var row = this.selectedRow;
      if (!row) {
        this.$message.warning("请先选择一行数据");
        return;
      }

      // 初始化processCheckData和当前检测零件编号
      this.processCheckData = {
        ...this.processCheckData,
        TaskAID: row.TaskAID,
        检验人: this.$store.state.user.name,
        检验时间: this.currentTime,
        检测数量: 1,
        合格数: 1,
      };

      this.betweenProcessCurrentPage = 1;
      this.betweenProcessCurrentInspectionItem = 1;
      this.betweenProcessInspectionData = [];
      this.processCheckVisible = true;

      // 先获取产品订单信息
      const param = [];
      param.push(["TaskAID", row.TaskAID]);
      var Data = this.CreateData("11", "Prog_MES_GetProductOrder_byAID", param);

      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.processCheckData = {
              ...response.data[0],
              TaskAID: row.TaskAID,
              检验人: this.processCheckData.检验人,
              检验时间: this.processCheckData.检验时间,
              检测数量: this.processCheckData.检测数量,
              合格数: this.processCheckData.合格数,
            };
          }
        })
        .then(() => {
          // 继续执行其他操作
          return this.searchBetweenProcessTable();
        })
        .then(() => {
          // 初始化检测数据
          this.handleBetweenProcessPageChange();
          this.$message.info(
            `开始检测第 ${this.betweenProcessCurrentInspectionItem} 件`
          );
        })
        .catch((error) => {
          this.loading = false;
          console.error("序检自检初始化失败:", error);
          this.$message.error("初始化失败: " + error.message);
        });
    },
    // 搜索序检自检检验标准
    searchBetweenProcessTable() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        this.betweenProcessTableData = [];
        var param = [];
        param.push(["物料编号", this.processCheckData.物料编号]);
        param.push(["工序名称编号", this.processCheckData.顺序编号]);
        param.push(["检测类别编号", 3]); // 序检自检的检测类别编号为3

        var Data = this.CreateData(
          "11",
          "MES_QulityInspection_GetItemStandard",
          param
        );

        this.ExecDatabase(Data)
          .then((response) => {
            this.loading = false;
            if (response.data.length !== 0) {
              this.betweenProcessTableData = response.data.map((item) => {
                return {
                  ...item,
                  检测结果: item.检测结果 || "1",
                  实测值: item.实测值 || "",
                };
              });
            }
            resolve();
          })
          .catch((error) => {
            this.loading = false;
            reject(error);
          });
      });
    },
    // 获取当前页的数据
    getBetweenProcessCurrentPageData() {
      const pageIndex = this.betweenProcessCurrentPage - 1;

      if (
        this.betweenProcessInspectionData.length > 0 &&
        pageIndex >= 0 &&
        this.betweenProcessInspectionData[pageIndex]
      ) {
        return this.betweenProcessInspectionData[pageIndex];
      }

      return [];
    },
    // 更新序检自检检测数据
    updateBetweenProcessInspectionData(item, pageIndex) {
      if (!this.betweenProcessInspectionData[pageIndex]) {
        console.error(`页面索引 ${pageIndex} 不存在`);
        return;
      }

      const itemIndex = this.betweenProcessInspectionData[pageIndex].findIndex(
        (i) => i.检测项目 === item.检测项目
      );

      if (itemIndex !== -1) {
        const updatedItem = {
          ...this.betweenProcessInspectionData[pageIndex][itemIndex],
          实测值: item.实测值,
          检测结果: item.检测结果,
        };

        this.$set(
          this.betweenProcessInspectionData[pageIndex],
          itemIndex,
          updatedItem
        );
        this.updateBetweenProcessQualifiedCount();
      }
    },
    // 序检自检更新合格数
    updateBetweenProcessQualifiedCount() {
      this.processCheckData.合格数 =
        this.processCheckData.检测数量 - this.betweenProcessUnqualifiedCount;
    },
    // 序检自检上一页
    betweenProcessPrevPage() {
      if (this.betweenProcessCurrentPage > 1) {
        // 先保存当前页数据
        this.saveBetweenProcessCurrentPageData().then((success) => {
          if (success) {
            this.betweenProcessCurrentPage--;
            this.betweenProcessCurrentInspectionItem =
              this.betweenProcessCurrentPage;
            this.$message.info(`已切换到第${this.betweenProcessCurrentPage}页`);
          }
        });
      }
    },
    // 序检自检下一页
    betweenProcessNextPage() {
      // 先保存当前页数据
      this.saveBetweenProcessCurrentPageData()
        .then((success) => {
          if (success) {
            if (
              this.betweenProcessCurrentPage >= this.processCheckData.检测数量
            ) {
              // 如果是最后一页，创建新页面
              this.processCheckData.检测数量++;

              const newPageData = JSON.parse(
                JSON.stringify(this.betweenProcessTableData)
              ).map((item) => {
                return {
                  ...item,
                  检测结果: item.检测结果 || "1",
                  实测值: item.实测值 || "",
                };
              });

              this.betweenProcessInspectionData.push(newPageData);
              this.processCheckData.合格数++;
            }

            this.betweenProcessCurrentPage++;
            this.betweenProcessCurrentInspectionItem =
              this.betweenProcessCurrentPage;
            this.$message.success(
              `第 ${
                this.betweenProcessCurrentPage - 1
              } 件检测数据已保存，已跳转到第 ${
                this.betweenProcessCurrentPage
              } 件检测`
            );
          } else {
            this.$message.error("保存失败，请检查数据后重试");
          }
        })
        .catch((error) => {
          console.error("保存错误:", error);
          this.$message.error("保存过程中发生错误");
        });
    },
    // 保存序检自检当前页数据
    saveBetweenProcessCurrentPageData() {
      return new Promise((resolve, reject) => {
        const currentPageData = this.getBetweenProcessCurrentPageData();

        // 验证数据完整性
        let isValid = true;
        let errorMessages = [];

        currentPageData.forEach((item, index) => {
          if (!item.实测值 && item.实测值 !== 0) {
            isValid = false;
            errorMessages.push(`"${item.检测项目}"的实测值不能为空`);
          }

          if (!item.检测结果) {
            isValid = false;
            errorMessages.push(`"${item.检测项目}"的判定结果不能为空`);
          }
        });

        if (!isValid) {
          this.$message({
            message: errorMessages.join("；"),
            type: "warning",
          });
          resolve(false);
          return;
        }

        // 提交数据
        const submitPromises = [];

        currentPageData.forEach((item) => {
          const param = [];
          param.push(["TaskAID", this.processCheckData.TaskAID || -1]);
          param.push(["物料编号", this.processCheckData.物料编号 || ""]);
          param.push(["阶段标识", this.processCheckData.顺序编号 || -1]);
          param.push(["工序名称", this.processCheckData.工序名称 || ""]);
          param.push(["计划号", this.processCheckData.订单编号 || ""]);
          param.push(["检测项目", item.检测项目 || ""]);
          param.push(["理论值", item.理论值 || ""]);
          param.push(["上限值", item.上限值 || ""]);
          param.push(["下限值", item.下限值 || ""]);
          param.push(["实测值", item.实测值 || ""]);
          param.push(["测量单位", item.测量单位 || ""]);
          param.push(["检验比例", item.检验比例 || ""]);
          param.push(["检具", item.检具 || ""]);
          param.push(["检测结果", item.检测结果 === "1" ? 1 : 0]);
          param.push(["合格数", this.processCheckData.合格数 || 0]);
          param.push([
            "不合格数",
            this.processCheckData.检测数量 - this.processCheckData.合格数 || 0,
          ]);
          param.push(["备注", item.备注 || ""]);
          param.push(["检测人", this.processCheckData.检验人 || ""]);
          param.push([
            "检测时间",
            this.processCheckData.检验时间 || new Date().toISOString(),
          ]);
          param.push(["质检类型", "序检自检"]);
          param.push(["检测类型编号", "3"]); // 序检自检类型编号为3
          param.push(["零件名称", this.processCheckData.物料描述 || ""]);
          param.push(["内部合同号", this.processCheckData.合同号 || ""]);
          param.push(["零件编码", this.processCheckData.物料编号 || ""]);
          param.push(["检验数量", this.processCheckData.检测数量 || 1]);
          param.push(["计划生产数", this.processCheckData.计划数量 || 0]);
          param.push(["检测说明", item.备注 || ""]);
          param.push(["当前检测零件编号", this.betweenProcessCurrentPage]);
          param.push(["QT_AID", -1]);
          param.push(["LJ_AID", -1]);

          const data = this.CreateData(
            "12",
            "MES_QulityInspection_CheckItemData_Save",
            param
          );
          submitPromises.push(this.ExecDatabase(data));
        });

        Promise.all(submitPromises)
          .then((responses) => {
            const allSuccess = responses.every(
              (response) =>
                response &&
                response.data &&
                response.data[0] &&
                response.data[0].result === "1"
            );

            if (allSuccess) {
              this.$message.success("数据保存成功");
              resolve(true);
            } else {
              this.$message.error("部分数据保存失败");
              resolve(false);
            }
          })
          .catch((error) => {
            console.error("保存失败:", error);
            this.$message.error("保存失败: " + error.message);
            reject(error);
          });
      });
    },
    // 序检自检删除当前页
    confirmDeleteBetweenProcessCurrentPage() {
      if (this.processCheckData.检测数量 <= 1) {
        this.$message.warning("至少需要保留一个检测页");
        return;
      }

      this.$confirm("确定要删除当前检测页吗？删除后将无法恢复。", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 先保存当前页数据
          this.saveBetweenProcessCurrentPageData().then((success) => {
            if (success) {
              this.deleteBetweenProcessCurrentPage();
            }
          });
        })
        .catch(() => {
          // 用户取消删除
        });
    },
    // 序检自检删除当前页逻辑
    deleteBetweenProcessCurrentPage() {
      this.betweenProcessInspectionData.splice(
        this.betweenProcessCurrentPage - 1,
        1
      );
      this.processCheckData.检测数量--;

      if (this.betweenProcessCurrentPage > this.processCheckData.检测数量) {
        this.betweenProcessCurrentPage = this.processCheckData.检测数量;
      }

      this.betweenProcessCurrentInspectionItem = this.betweenProcessCurrentPage;
      this.updateBetweenProcessQualifiedCount();

      this.$message.success(
        `第 ${this.betweenProcessCurrentPage} 件检测页已删除`
      );
    },

    // 序检自检处理页码变化
    handleBetweenProcessPageChange() {
      if (this.betweenProcessInspectionData.length === 0) {
        for (let i = 0; i < this.processCheckData.检测数量; i++) {
          const pageData = this.betweenProcessTableData.map((item, index) => {
            const newItem = JSON.parse(JSON.stringify(item));
            newItem.唯一标识 = `between_page${i}_item${index}_${Date.now()}_${Math.random()}`;
            newItem.检测结果 = newItem.检测结果 || "1";
            newItem.实测值 = newItem.实测值 || "";
            return newItem;
          });

          this.betweenProcessInspectionData.push(pageData);
        }
      }
    },

    // 序检自检最终提交
    submitBetweenProcessQualityData() {
      this.saveBetweenProcessCurrentPageData().then((success) => {
        if (success) {
          this.$message({
            message: `所有序检自检数据提交完成，共检测 ${this.processCheckData.检测数量} 件`,
            type: "success",
          });
          this.processCheckVisible = false;
          this.searchTable();
        } else {
          this.$message.error("最终提交失败，请检查数据");
        }
      });
    },

    // 添加实测值变更处理方法（与首检自检相同）
    handleBetweenProcessRealTimeInput(item, itemIndex, pageIndex) {
      this.updateBetweenProcessInspectionData(item, pageIndex);
    },

    // 收检加载数据方法
    receiveCheck() {
      var row = this.selectedRow;
      console.log(row)
      if(row != ''){
        this.receiveCheckVisible = true;
        const param = [];
        param.push(["TaskAID", row.TaskAID]);
        var Data = this.CreateData("11", "加工中心_收检_读取收检记录", param);
        this.ExecDatabase(Data)
          .then((response) => {
            this.loading = false;
            if (response.data.length !== 0) {
                this.receiveCheckData.零件名称 = row.零件名称
                this.receiveCheckData.内部合同号 = row.订单号
                this.receiveCheckData.计划号 = row.订单号
                this.receiveCheckData.零件编码 = row.零件编码
                this.receiveCheckData.工序名称 = row.工序名称
                this.receiveCheckData.计划生产数 = row.分配数;
                console.log(!response.data[0].Column1)
                if(!response.data[0].Column1){
                  response.data[0].Column1 = 0
                }
                  this.receiveCheckData.已检验数量 = response.data[0].Column1
                if(!response.data[0].Column2){
                  response.data[0].Column2 = 0
                }
                if(!response.data[0].Column3){
                  response.data[0].Column3 = 0
                }
                if(!response.data[0].Column4){
                  response.data[0].Column4 = 0
                }
                this.receiveCheckData.上序合格数 = response.data[0].Column3
                this.receiveCheckData.订单行号 = response.data[0].Column4
                this.receiveCheckData.检测数量 = response.data[0].Column2 - response.data[0].Column1;
                this.receiveCheckData.检验人 = this.$store.state.user.name;
                this.receiveCheckData.检验时间 = this.currentTime;

                this.receiveCheckData.合格数 = 0; 
                this.receiveCheckData.不合格数 = 0;
                this.receiveCheckData.TaskAID = row.TaskAID;
              }
          })
          .catch(() => {
            this.loading = false;
          });
      }else{
        this.$message.error('请先选择数据')
      }
      
    },
    // 收检数据提交逻辑
    submitReceiveCheckData() {
      // 验证数据完整性
      let isValid = true;
      let errorMessage = "";

      if (!this.receiveCheckData.检验时间) {
        errorMessage = "请填写检验时间";
        isValid = false;
      }
      if (!isValid) {
        this.$message({
          message: errorMessage,
          type: "warning",
        });
        return;
      }
      if (this.receiveCheckData.检测数量 == 0){
        return this.$message.error('检测数量不能为0')
      }
      if (this.receiveCheckData.上序合格数 - this.receiveCheckData.已检验数量 < this.receiveCheckData.检测数量 & this.receiveCheckData.订单行号 > 1  ){
        return this.$message.error('检测数量不能大于未检测数量')
      }
      if (this.receiveCheckData.计划生产数 - this.receiveCheckData.已检验数量 < this.receiveCheckData.检测数量){
        return this.$message.error('检测数量不能大于未检测数量')
      }
      if (this.receiveCheckData.检测数量 - this.receiveCheckData.合格数 != this.receiveCheckData.不合格数){
        return this.$message.error('检测数量必须是合格数和不合格数之和')
      }
      // 提交收检数据
      const param = [];
      param.push(["TaskAID", this.receiveCheckData.TaskAID]);
      param.push(["检测类型编号", 6]);
      param.push(["质检类型", "收检"]);
      param.push(["零件名称", this.receiveCheckData.零件名称]);
      param.push(["内部合同号", this.receiveCheckData.内部合同号]);
      param.push(["零件编码", this.receiveCheckData.零件编码]);
      param.push(["计划号", this.receiveCheckData.计划号 || ""]);
      param.push(["工序名称", this.receiveCheckData.工序名称 || ""]);
      param.push(["检测数量", this.receiveCheckData.检测数量]);
      param.push(["合格数", this.receiveCheckData.合格数]);
      param.push(["不合格数", this.receiveCheckData.不合格数]);
      param.push(["检测人", this.receiveCheckData.检验人 || ""]);
      param.push(["检测时间", this.receiveCheckData.检验时间 || ""]);
      param.push(["计划生产数", this.receiveCheckData.计划生产数 || ""]);
      param.push(["检测说明", this.receiveCheckData.备注 || ""]);
     
      this.receiveCheckVisible = false;
      const data = this.CreateData(
        "12",
        "MES_QulityInspection_ReceiveCheck",
        param
      );

      this.ExecDatabase(data)
        .then((response) => {
          if (response.data[0].result === "1") {
            this.$message({
              message: "收检数据提交成功",
              type: "success",
            });
            
            if( this.receiveCheckData.不合格数>0){
               this.saveReceiveCheck()
            }
           
            this.searchTable(); // 刷新主表数据
          } else {
            this.$message({
              message: "收检数据提交失败：" + response.data[0].message,
              type: "error",
            });
          }
        })
        .catch((error) => {
          this.$message({
            message: "收检数据提交失败: " + error,
            type: "error",
          });
        });
    },
    transformData(rawArray) {
    // 先转成对象便于取值
      const map = {};
      for (const [key, value] of rawArray) {
        map[key] = value;
      }

      const taskItemsArray = map.task_items;
      const taskMap = {};
      for (const [k, v] of taskItemsArray) {
        taskMap[k] = v;
      }
      return {
        doc_date: map.doc_date, // 或 new Date().toISOString().split('T')[0]
        doc_type: map.doc_type,
        external_num: taskMap.external_num,
        
        task_items: [
          {
            base_entry:taskMap.base_entry,
            base_type: taskMap.base_type,
            external_num: taskMap.external_num,
            item_code: taskMap.item_code,
            item_name: taskMap.item_name,
            whs_code: '', // 原值被清空
            manage_type: taskMap.manage_type,
            price: taskMap.price,
            quantity: taskMap.quantity,
          }
        ]
      };
    },
// 如果需要转成 JSON 字符串
    async saveReceiveCheck() {
      var param = [];
      var param2 = [];
      // var param3 = [];
      param.push(["doc_date", this.completionTime[0]]);
      param.push(["doc_type", "202-59"]);
      param.push(["external_num", this.receiveCheckData.计划号]);
      param.push(["task_items", param2]);
      param2.push(["base_entry", this.receiveCheckData.计划号]);
      param2.push(["base_type", "202"]);
      param2.push(["external_num", this.receiveCheckData.计划号])
      param2.push(["item_code", this.receiveCheckData.零件编码]);
      param2.push(["item_name", this.receiveCheckData.零件名称]);
      param2.push(["whs_code", ""]);
      param2.push(["manage_type", 'B']);
      param2.push(["price", 0]);
      param2.push(["quantity", this.receiveCheckData.不合格数]);
      // param3.push(["item_code",  this.receiveCheckData.零件编码]);
      // param3.push(["batch_number", ""]);
      // param3.push(["quantity", this.receiveCheckData.不合格数]);
      
      const result = this.transformData(param);
      console.log(result);

      // 如果需要转成 JSON 字符串
      // const jsonString = JSON.stringify(result, null, 2);
      // console.log(jsonString);
      const result2 = await posttm('/stocktask/task/receiptordertask',result)
      console.log(result2)
    },
    // 检验记录方法
    checkRecord() {
      var row = this.selectedRow
      if(row){
        this.loadCheckRecordData(row);
      }else{
        this.$message.error("请先选择数据");
      }
      
    },
    //加载检查记录数据
    loadCheckRecordData(row) {
      this.checkRecordLoading = true;
      this.checkRecordVisible = true;
      // 构造查询参数
      const param = [];
      console.log("检测类型编号", this.type);
      param.push(["计划号", this.orderNo2 || row.订单号]);
      param.push(["零件编码", this.productCode2 || ""]);
      param.push(["工艺编号", this.process || ""]);
      param.push(["检测类型编号", this.type || ""]);
      param.push(["检验结果", this.inspectionResult || ""]);
      let inspectorName = "";
      if (this.operationPerson) {
        const selectedPerson = this.operationPersonList.find(
          (item) => item.value === this.operationPerson
        );
        inspectorName = selectedPerson
          ? selectedPerson.label
          : this.operationPerson;
      }
      param.push(["检测人", inspectorName || ""]);
      param.push([
        "检测时间开始",
        this.operationDate && this.operationDate[0]
          ? this.operationDate[0]
          : "",
      ]);
      param.push([
        "检测时间结束",
        this.operationDate && this.operationDate[1]
          ? this.operationDate[1]
          : "",
      ]);

      // 调用后台接口获取检验记录数据
      const data = this.CreateData(
        "11",
        "MES_QualityInspection_CheckRecord_Query",
        param
      );

      this.ExecDatabase(data)
        .then((response) => {
          this.checkRecordLoading = false;
          if (response.data.length !== 0) {
            this.checkRecordTableData = response.data;
          } else {
            this.checkRecordTableData = [];
            this.$message.info("未查询到相关检验记录");
          }
        })
        .catch((error) => {
          this.checkRecordLoading = false;
          this.$message.error("检验记录加载失败: " + error);
          this.checkRecordTableData = [];
        });
    },
    //检验记录里的检验详情弹窗触发
    viewInspectionDetail(row) {
      console.log("查看检验详情", row);
      this.currentQT_AID = row.QT_AID;
      this.currentInspectionRecord = row;
      this.checkDetailedVisible = true;
      // 加载检测零件数据
      this.loadInspectionParts(row.QT_AID);
    },
    // 加载检测零件数据
    loadInspectionParts(qtAid) {
      this.loading = true;
      const param = [["QT_AID", qtAid]];
      const Data = this.CreateData(
        "11",
        "MES_QualityInspection_GetInspectionParts",
        param
      );

      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.checkDetailedTableData = response.data;
          } else {
            this.checkDetailedTableData = [];
            this.$message.info("未找到检测零件记录");
          }
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error("加载检测零件记录失败: " + error);
          this.checkDetailedTableData = [];
        });
    },
    // 修改检验详情里的详情弹窗触发方法
    Detailed(row) {
      console.log("查看检测详情", row);
      this.currentLJ_AID = row.LJ_AID;
      this.DetailedVisible = true;

      // 加载检测数据
      this.loadInspectionDetails(row.LJ_AID);
    },
    // 加载检测数据
    loadInspectionDetails(ljAid) {
      this.loading = true;
      const param = [["LJ_AID", ljAid]];
      const Data = this.CreateData(
        "11",
        "MES_QualityInspection_GetInspectionDetails",
        param
      );

      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.length !== 0) {
            this.inspectionDetailTableData = response.data;
          } else {
            this.inspectionDetailTableData = [];
            this.$message.info("未找到检测数据记录");
          }
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error("加载检测数据失败: " + error);
          this.inspectionDetailTableData = [];
        });
    },

    // 处理记录行点击事件
    handleCheckRecordRowClick(row) {
      this.checkRecordSelectedRow = row;
    },

    //异常相关逻辑
    abnormal() {
      this.abnormalVisible = true;
      this.abnormalTable();
    },
    abnormalTable() {
      var param = [];
      param.push(["操作人", this.$store.state.user.name]);
      var Data = this.CreateData(
        "11",
        "加工中心_异常工时_获取操作记录列表",
        param
      );
      this.ExecDatabase(Data)
        .then((response) => {
          this.abnormaltableData = response.data || [];
          this.loading = false;
        })
        .catch((error) => {
          this.$message.error("查询失败：" + error.message);
          this.loading = false;
        });
    },
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      if (isNaN(date.getTime())) return ''
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    editTask(row) {
      this.currentTask = row;
      this.editForm = {
        订单编号: row.订单号,
        产品编码: row.产品编码,
        产品名称: row.产品名称,
        工序名称: row.工序名称,
        指派对象: row.指派对象,
        开始时间: row.开始时间,
        结束时间: row.结束时间,
        加工工时: row.加工工时 || 0,
      };
      this.editDialogVisible = true;
    },
    submitEditForm() {
      var param = [
        ["TaskAID", this.currentTask.AID],
        ["开始时间", this.editForm.开始时间],
        ["结束时间", this.editForm.结束时间],
        ["工时", this.editForm.加工工时],
        ["操作人", this.getCurrentUser()],
        ["最后编辑人", this.getCurrentUser()],
      ];

      var Data = this.CreateData("11", "加工中心_修改工时_保存修改记录", param);
      this.ExecDatabase(Data).then((response) => {
        this.$message.success("校验成功");
        this.editDialogVisible = false;
        this.abnormalTable();
      });
    },
    calculateWorkTime() {
      if (this.editForm.开始时间 && this.editForm.结束时间) {
        const start = new Date(this.editForm.开始时间);
        const end = new Date(this.editForm.结束时间);
        const diff = end.getTime() - start.getTime();
        this.editForm.加工工时 = Math.round(diff / 1000); // 转换为秒
      } else {
        this.editForm.加工工时 = 0;
      }
    },
    handleRowClick2(row) {
      this.currentTask = row;
    },
    getCurrentUser() {
      console.log(this);
      return this.$store.state.user.name;
    },
    // 添加专门的实测值变更处理方法
    handleMeasuredValueChange(item, itemIndex, pageIndex) {
      console.log("实测值变更:", {
        页面: pageIndex + 1,
        项目索引: itemIndex,
        检测项目: item.检测项目,
        实测值: item.实测值,
        完整数据: this.inspectionData[pageIndex][itemIndex],
      });

      this.updateInspectionData(item, pageIndex);
    },

    handleRealTimeInput(item, itemIndex, pageIndex) {
      // 实时更新，不等待blur
      this.updateInspectionData(item, pageIndex);
    },
    handleInputBlur(item, itemIndex, pageIndex) {
      console.log("输入框失去焦点，最终值:", item.实测值);
    },
    // 处理检测零件行点击事件
    handleInspectionPartRowClick(row) {
      this.currentLJ_AID = row.LJ_AID;
    },


    //异常管控相关函数
    getProcessedTasks() {
      var params = []
      params.push(['审批人ID', this.$store.state.user.id])
      const data = this.CreateData('11', 'sp_获取最近处理任务', params)
      this.ExecDatabase(data).then((response) => {
        this.processedTasks = response.data
        this.stats.completed = response.data.length
      })
    },
    
    getUserList() {
      const data = this.CreateData('11', '人员管理_人员信息查询')
      this.ExecDatabase(data).then((response) => {
        response.data.forEach(item => {
          this.users.push({ id: item.Personnel_Number, name: item.Personnel_Name })
          this.userList.push({ id: item.Personnel_Number, name: item.Personnel_Name })
        });
        console.log( this.userList)
      }).catch(() => {
        this.$message.error('处理失败')
      }) 
    },
    
    searchTable4() {
      var params = []
      params.push(['发起人ID', this.$store.state.user.id])
      params.push(['状态', null])
      var data = this.CreateData('11', 'sp_获取我的流程', params)
      this.ExecDatabase(data).then(response => {
        this.loading = false
        if (response.data.length !== 0) {
          this.initiatedProcesses = response.data;
          this.stats.initiated = response.data.length
        }
      }).catch(() => {
        this.loading = false
      })
    },
    
    searchTable1() {
      var params = []
      params.push(['审批人ID', this.$store.state.user.id])
      var data = this.CreateData('11', 'sp_获取待处理任务', params)
      this.ExecDatabase(data).then(response => {
        this.loading = false
        if (response.data.length !== 0) {
          this.pendingTasks = response.data;
          this.stats.pending = response.data.length
        }
      }).catch(() => {
        this.loading = false
      })
    },
    
    searchTable3() {
      this.loading = true
      var params = []
      params.push(['订单号', this.orderNo || 0])
      params.push(['物料类型', '自制件'])
      params.push(['合同号', this.contractNo])
      params.push(['产品编码', this.productCode])
      params.push(['产品名称', this.productName])
      params.push(['工序名称', this.processName])
      params.push(['性质', this.nature])
      params.push(['要求完工日期1', this.completionTime ? this.completionTime[0] : ''])
      params.push(['要求完工日期2', this.completionTime ? this.completionTime[1] : ''])
      params.push(['排产状态', this.productionStatus])
      params.push(['工位',''])
      var data = this.CreateData('11', 'MES_ProductAdmin_Query', params)
      this.ExecDatabase(data).then(response => {
        this.loading = false
        if (response.data.length !== 0) {
          this.tableData5 = response.data
        }
      }).catch(() => {
        this.loading = false
      })
    },

    // 对话框控制方法
    showCreateDialog() {
      this.createDialogVisible = true;
      this.resetNewProcessForm();
    },
    
    showTransferDialog(task) {
      this.currentTask = task;
      this.transferForm = {
        newApproverId: '',
        newApproverName: '',
        reason: ''
      };
      this.transferDialogVisible = true;
    },
    
    showCompleteDialog(process) {
      this.selectProcess = process;
      this.completeForm = {
        reason: '',
        result: 'completed'
      };
      this.completeDialogVisible = true;
    },
    
    handleTask(task) {
      this.currentTask = task;
      this.handleForm = {
        result: 'approved',
        comment: ''
      };
      this.handleDialogVisible = true;
    },

    // 表单操作方法
    resetNewProcessForm() {
      this.newProcessForm = {
        type: true,
        priority: 'normal',
        title: '',
        description: '',
        approvers: []
      };
    },
    
    addApprover() {
      this.newProcessForm.approvers.push({
        userId: ''
      });
    },
    
    removeApprover(index) {
      this.newProcessForm.approvers.splice(index, 1);
    },
    
    getUserListByType(type) {
      console.log(this.userList)
      return this.userList || [];
    },

    // 数据处理方法
    handleAbnormalControlTaskRowClick(row) {
      this.selectedRow = row
      this.tableOrderNum = row.订单号
      this.tableProductCode = row.物料编码
      this.tableProductName = row.产品名称
      this.tableProcessName = row.工序名称
    },
    
    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },

    // 提交处理方法
    // 调用简化版存储过程的方法
submitNewProcess() {
  if(this.selectedRow == ""){
    return this.$message.warning('请选择绑定信息');
  }

  this.$refs.processForm.validate((valid) => {
    if (valid) {
      this.submitting = true;
      
      // 获取第一个审批人
      let approverId = this.$store.state.user.id; // 默认使用当前用户
      let approverName = this.$store.state.user.name;
      
      if(this.newProcessForm.approvers.length > 0 && this.newProcessForm.approvers[0].userId){
        let foundUser = this.userList.find(user => user.id == this.newProcessForm.approvers[0].userId);
        if(foundUser){
          approverId = foundUser.id;
          approverName = foundUser.name;
        }
      }
      
      const params = []
      params.push(['流程标题', this.newProcessForm.title])
      params.push(['流程描述', this.newProcessForm.description])
      params.push(['优先级', this.newProcessForm.priority || 'normal'])
      params.push(['发起人ID', this.$store.state.user.id])
      params.push(['发起人姓名', this.$store.state.user.name])
      params.push(['审批人ID', approverId])
      params.push(['审批人姓名', approverName])
      params.push(['新流程ID', '0'])
      params.push(['已关联计划号', this.tableOrderNum || ''])
      params.push(['零件名称', this.tableProductName || ''])
      params.push(['零件编号', this.tableProductCode || ''])
      params.push(['工序名称', this.tableProcessName || ''])
      
      console.log('简化版参数:', params);

      // 调用简化版存储过程
      const data = this.CreateData('11', 'sp_创建流程_简化版', params)
      
      this.ExecDatabase(data).then((response) => {
        console.log('简化版返回:', response);
        if(response.data && response.data.length > 0){
          const result = response.data[0];
          if(result.结果 == 1){
            this.$message.success('流程创建成功！流程ID: ' + result.新流程ID);
            this.createDialogVisible = false;
            this.resetNewProcessForm();
            this.searchTable();
          } else {
            this.$message.error('创建失败: ' + (result.消息 || '未知错误'));
          }
        }
        this.submitting = false;
      }).catch((error) => {
        console.error('API调用错误:', error);
        this.$message.error('保存失败');
        this.submitting = false;
      }) 
    }
  });
},
    submitHandle(task) {
      const params = []
      params.push(['流程ID', task.流程ID])
      params.push(['节点ID', task.节点ID])
      params.push(['审批人ID', this.$store.state.user.id])
      params.push(['审批人姓名', this.$store.state.user.name])
      params.push(['处理结果', this.$refs.approvalForm.model.result])
      params.push(['审批意见', this.$refs.approvalForm.model.comment])
      params.push(['成功',''])
      
      const data = this.CreateData('12', 'sp_处理审批', params)
      this.ExecDatabase(data).then((response) => {
       
          this.$message.success('处理完成');
          this.handleDialogVisible = false;
          this.searchTable1();
          this.getProcessedTasks();
        
      }).catch(() => {
        this.$message.error('处理失败')
      }) 
    },
    
    confirmTransfer() {
      if (!this.transferForm.newApproverId) {
        this.$message.warning('请选择目标人员');
        return;
      }
      
      this.users.forEach(user => {
        if(user.id == this.transferForm.newApproverId){
          this.transferForm.newApproverName = user.name
        }
      });
      
      if (!this.transferForm.reason) {
        this.$message.warning('请输入转办原因');
        return;
      }
      
      this.transferLoading = true;
      const params = []
      params.push(['流程ID', this.currentTask.流程ID])
      params.push(['节点ID', this.currentTask.节点ID])
      params.push(['原审批人ID', this.$store.state.user.id])
      params.push(['原审批人姓名', this.$store.state.user.name])
      params.push(['新审批人ID', this.transferForm.newApproverId])
      params.push(['新审批人姓名', this.transferForm.newApproverName])
      params.push(['转办原因', this.transferForm.reason])
      params.push(['成功', ''])
      
      const data = this.CreateData('12', 'sp_转办流程', params)
      this.ExecDatabase(data).then((response) => {
        
          this.$message.success('转办成功！');
          this.transferDialogVisible = false;
          this.searchTable1();
        
      }).catch(() => {
        this.$message.error('保存失败')
      }).finally(() => {
        this.transferLoading = false;
      })
    },
    
    confirmComplete() {
      if (!this.completeForm.reason) {
        this.$message.warning('请输入完结原因');
        return;
      }
      
      const params = []
      params.push(['流程ID', this.selectProcess.流程ID])
      params.push(['发起人ID', this.$store.state.user.id])
      params.push(['发起人姓名', this.$store.state.user.name])
      params.push(['完成类型', this.completeForm.result])
      params.push(['完成原因', this.completeForm.reason])
      params.push(['成功', ''])
      
      const data = this.CreateData('11', 'sp_完成流程', params)
      this.ExecDatabase(data).then((response) => {
       
          this.$message.success('操作成功！');
          this.completeDialogVisible = false;
          this.searchTable4();
        
      }).catch(() => {
        this.$message.error('保存失败')
      }).finally(() => {
        this.completeLoading = false;
      })
    },
    // 查看详情方法
    viewProcessDetail(process) {
      var params = []
      params.push(['流程ID', process.流程ID])
      var data = this.CreateData('11', 'sp_获取流程详情', params)
      this.ExecDatabase(data).then(response => {
        this.加载中 = false
        const result = JSON.parse(response.data[0]["JSON_F52E2B61-18A1-11d1-B105-00805F49916B"])
        const processInfo = JSON.parse(result.流程信息);
        const steps = JSON.parse(result.步骤信息);
        var  approvalRecords = ''
        if(result.审批记录){
          approvalRecords = JSON.parse(result.审批记录);
        }
        this.currentProcess = {
          'processInfo': processInfo,
          'steps': steps,
          'approvalRecords': approvalRecords,
        }
        console.log(this.currentProcess)
        
        this.detailDialogVisible = true;
      }).catch(() => {
        this.加载中 = false
      })
    },

    // 工具方法
    getPriorityType(priority) {
      const map = { urgent: 'danger', high: 'warning', normal: 'success' };
      return map[priority] || 'info';
    },
    
    getPriorityText(priority) {
      const map = { urgent: '紧急', high: '高', normal: '普通' };
      return map[priority] || '普通';
    },
    
    getStatusType(status) {
      const map = { processing: 'warning', completed: 'success', rejected: 'danger', cancelled: 'info' };
      return map[status] || 'info';
    },
    
    getStatusText(status) {
      const map = { processing: '审批中', completed: '已完成', rejected: '已拒绝', cancelled: '已取消' };
      return map[status] || status;
    },
    
    isUrgent(deadline) {
      return new Date(deadline) - new Date() < 24 * 60 * 60 * 1000;
    },
    Abnormalcontrol(){
      this.abnormalControlDialogVisible = true
    },
    ReturnWarehouse(){
      this.ReturnWarehousepop = true
      var row = this.selectedRow;
      if(row == ''){
        return this.$message.error('请先选择任务')
      }
      var param = []
      param[0] = ['生产订单号',row.订单号]
      var Data = this.CreateData('11', '生产管理_加工中心_生产发料查询', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response)
        this.ReturnWarehouseForm = response.data.map(element => ({
          ...element,
          退库数量: 0
        }))
      })
    },
    async MaterialRequisition(){
      var row = this.selectedRow;
      console.log(row)
      if(row == ''){
         return this.$message.error('请先选择任务')
      }
      
      // var param = []
      // param[0] = ['编码',row.零件编码]
      var result = await getB1("/ProductionOrders",{"$filter":"AbsoluteEntry eq "+this.selectedRow.订单号})
      if (result.success) {
        console.log('请求成功');
        console.log('数据:', result.data); // ✅ 这就是你要的数据

        // 例如：访问第一个生产订单的字段
        this.MaterialRequisitionpop = true
        const productionOrder = result.data.value[0];
        productionOrder.ProductionOrderLines.forEach (item=>{
          item.Quantity = 0
        })
        const formModel = {
          lines: productionOrder.ProductionOrderLines
        };
        this.MaterialRequisitionForm = formModel
      } else {
        console.error('请求失败:', result.message);
      }
      // var Data = this.CreateData('11', '生产管理_加工中心_领料物料查询', param)
      // this.ExecDatabase(Data).then(response => {
      //   console.log(response)
      //   this.MaterialRequisitionForm = response.data
      // })
    },
    //查看图纸
    getitemdraw() {
      var row = this.selectedRow;
      if (!row) {
        this.$message.error('请先选择任务');
        return;
      }
      
      var param = [];
      param[0] = ['物料编号', row.零件编码];
      var Data = this.CreateData('11', '工艺管理_图纸维护_查看图纸', param);
      
      this.ExecDatabase(Data).then(async (response) => {
        console.log(response);
        if (response.data.length > 0) {
          var pdfSrc = "" + this.downPDF + "" + response.data[0].uid + ".pdf";
          
          // 1. 先打开对话框
          this.seeVisible = true;
          
          // 2. 等待对话框完全渲染（使用 $nextTick 确保 DOM 已更新）
          await this.$nextTick();
          
          // 3. 等待一小段时间确保对话框内的容器完全渲染
          setTimeout(async () => {
            try {
              await seepdf(pdfSrc, 'see');
            } catch (error) {
              console.error('PDF 渲染失败:', error);
              this.$message.error('PDF 渲染失败: ' + error.message);
            }
          }, 300); // 增加延迟确保 DOM 完全渲染
          
        } else {
          this.$message.error('未上传图纸');
        }
      });
    },
    getprocessdraw(row) {
      var row = this.selectedRow;
      if(row == ''){
        return this.$message.error('请先选择任务')
      }
      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"
          this.seeVisible = true
            seepdf(pdfSrc,'see')
        }else{
          this.$message.error('未上传图纸')
        }
      })
    },
    async submitReturnWare() {
      const validData = this.ReturnWarehouseForm
        .filter(element => element.退库数量 != 0)
        .map(element => {
          const param = [
            ['生产订单号', element.生产订单号],
            ['编码', element.编码],
            ['名称', element.名称],
            ['数量', element.退库数量],
            ['单位', element.单位],
            ['批次信息', element.批次信息],
            ['最后编辑人', this.$store.state.user.name],
            ['备注', element.LineText]
          ];
          return this.CreateData('12', '生产管理_加工中心_退库', param);
        });
      
      // 顺序执行，避免并发压力
      let successCount = 0;
      let errorCount = 0;
      for (const data of validData) {
        try {
          const response = await this.ExecDatabase(data);
          // 更安全的响应检查
          if (response.data[0].result == 1) {
            successCount++;
          } else {
            errorCount++;
            console.warn('服务器返回异常:', response);
          }
          
        } catch (error) {
          errorCount++;
          console.error('请求失败:', error);
        }
      }
      if (errorCount === 0) {
        this.$message.success(`所有${successCount}条退库记录提交成功，等待质检`);
        this.ReturnWarehousepop = false
      } else {
        this.$message.warning(`提交完成：成功${successCount}条，失败${errorCount}条`);
      }
    },
    async submitMaterialRequisition(datarow) {
      console.log(datarow)
      var params = []
      datarow.forEach( async item => {
        if(item.Quantity != 0){
          var param = []
          var param2 = [];
          param.push(["doc_date", this.formatDate(this.currentTime)]);
          param.push(["doc_type", "202-60"]);
          param.push(["external_num", item.DocumentAbsoluteEntry]);
          param.push(["task_items", param2]);
          param2.push(["base_type", "202"]);
          param2.push(["external_num", item.DocumentAbsoluteEntry])
          param2.push(["item_code", item.ItemNo]);
          param2.push(["item_name", item.ItemName]);
          param2.push(["line_memo", item.LineText]);
          param2.push(["whs_code", ""]);
          param2.push(["manage_type", 'B']);
          param2.push(["price", 0]);
          param2.push(["quantity", item.Quantity]);
          param2.push(["base_line_num",item.LineNumber]);
          param2.push(["base_entry", item.DocumentAbsoluteEntry]);
          params.push(param)
        }
      });
        const result = this.transformData(params);
        // const jsonString = JSON.stringify(result, null, 2);
        // console.log(jsonString);
        this.MaterialRequisitionpop = false
        const result2 = await posttm('/stocktask/task/issueordertask',result)
        this.$message.success('请求成功')
        console.log(result2)
    },
    transformData(rawArray) {
      console.log("原始数据:", rawArray);
      
      // 初始化结果对象
      const result = {
        doc_date: "",
        doc_type: "",
        external_num: 0,
        task_items: []
      };
      
      // 遍历所有文档，合并 task_items
      for (const docArray of rawArray) {
        // 将单个文档的二维数组转换为对象
        const map = {};
        for (const [key, value] of docArray) {
          map[key] = value;
        }

        // 设置文档级别信息（使用第一个文档的信息）
        if (result.task_items.length === 0) {
          result.doc_date = map.doc_date;
          result.doc_type = map.doc_type;
          result.external_num = map.external_num;
        }

        // 处理 task_items
        const taskItemsArray = map.task_items;
        
        console.log("当前文档的 task_items:", taskItemsArray);
        
        if (Array.isArray(taskItemsArray)) {
          // 将 task_items 的二维数组转换为对象
          const taskMap = {};
          for (const [k, v] of taskItemsArray) {
            taskMap[k] = v;
          }
          
          // 将每个文档的 task_item 添加到结果中
          result.task_items.push({
            base_line_num: taskMap.base_line_num,
            base_entry: taskMap.base_entry,
            base_type: taskMap.base_type,
            external_num: taskMap.external_num,
            item_code: taskMap.item_code,
            item_name: taskMap.item_name,
            whs_code: '', // 原值被清空
            manage_type: taskMap.manage_type,
            price: taskMap.price,
            quantity: taskMap.quantity,
          });
        }
      }

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

<style scoped>
::v-deep .priority-row {
  background-color: #f56c6c !important; /* 浅红色背景 */
  color: #000000 !important;            /* 深红色文字 */
}
::v-deep .priority-row td {
  background-color: #f56c6c !important;
  color: #000000 !important;
  border: #f56c6c;
}
.footbox {
  display: flex;
  margin-top: 10px;
  background: #fff;
  padding: 5px 0;
  border-radius: 10px;
  width: 92%;
}

.el-radio__input.is-checked .el-radio__inner {
  border-color: #67c23a;
  background: #67c23a;
}

.el-radio__inner {
  width: 20px;
  height: 20px;
}

.logo {
  width: 15%;
  height: 70px;
  margin: 10px;
  background: url(~@/assets/img/logo.png);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: 0 5px;
}

.logname {
  width: 20%;
  line-height: 50px;
  text-align: center;
}

.headerbox {
  display: flex;
  justify-content: space-between;
  background: #fff;
  margin: 5px 0px 10px 5px;
  border-radius: 5px;
  box-shadow: 2px 2px 5px #c0c4cc;
}

.grid-btn {
  height: 60px;
  width: 13%;
  text-align: center;
  line-height: 60px;
  background: linear-gradient(to bottom, #5a89d2, #012cac);
  border-radius: 5px;
  color: white;
  font-size: 20px;
  font-weight: bolder;
  box-shadow: 2px 5px 10px #1474d7;
}

.workstatus {
  display: block;
  font-size: 18px;
  font-weight: bold;
  line-height: 50px;
  padding-left: 25px;
  color: #3a8ee6;
}

.workstatus ::v-deep .el-radio__label {
  font-size: 18px;
}

.upbox {
  background: #fff;
  padding: 10px 0;
  border-radius: 20px;
  margin-left: 5px;
}

.downbox {
  width: 100%;
  background: #67c23a;
  color: white;
  line-height: 30px;
  font-size: 16px;
  margin: 20px 5px;
  border-radius: 5px;
  padding: 10px 0px 10px 5px;
  font-weight: bold;
  display: none;
}

.bottombox {
  width: 100%;
  margin: 0px 5px;
}

.search-container {
  margin-bottom: 20px;
}

.show-text {
  margin-right: 5px;
  line-height: 32px;
}

.status-light {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-light-green {
  background-color: #67c23a;
}

.status-light-gray {
  background-color: #909399;
}

.dialog-footer {
  text-align: right;
}

.info-container {
  border: 1px solid #ccc;
  display: flex;
}

.info-item {
  display: flex;
  flex: 1;
  border-right: 1px solid #ccc;
}

.info-item:last-child {
  border-right: none;
}

.info-label {
  width: 30%;
  padding: 8px;
  background-color: #f5f7fa;
  border-right: 1px solid #ccc;
}

.info-value {
  flex: 1;
  padding: 5px;
}

.info-label,
.info-value {
  display: flex;
  align-items: center;
}
.inspection-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}

.inspection-info .el-row {
  margin-bottom: 5px;
}

.inspection-info strong {
  color: #606266;
  margin-right: 5px;
}

.workflow-container {
			padding: 20px;
			min-height: 100vh;
	}
	.page-header {
			background: #fff;
			padding: 20px;
			margin-bottom: 20px;
			border-radius: 4px;
			box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
			display: flex;
			justify-content: space-between;
			align-items: center;
	}
	.workflow-tabs {
			background: #fff;
			border-radius: 4px;
			overflow: hidden;
	}
	.filter-bar {
			padding: 15px;
			background: #fff;
			margin-bottom: 15px;
			border-radius: 4px;
			display: flex;
			flex-wrap: wrap;
			align-items: center;
	}
	.filter-item {
			margin-right: 15px;
			margin-bottom: 10px;
	}
	.process-card {
			margin-bottom: 15px;
			cursor: pointer;
			transition: all 0.3s;
	}
	.process-card:hover {
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	}
	.priority-tag {
			margin-left: 10px;
	}
	.footer-buttons {
			margin-top: 20px;
			text-align: right;
	}
	.empty-state {
			text-align: center;
			padding: 40px 0;
			color: #909399;
	}
	.stats-card {
			text-align: center;
			padding: 20px;
			cursor: pointer;
			transition: all 0.3s;
	}
	.stats-card:hover {
			transform: translateY(-5px);
			box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
	}
	.stats-number {
			font-size: 24px;
			font-weight: bold;
			color: #409EFF;
			margin: 10px 0;
	}
	.stats-label {
			color: #909399;
	}
	.transfer-actions {
			margin: 10px 0;
			padding: 10px;
			background: #f5f7fa;
			border-radius: 4px;
	}
	.complete-dialog .el-dialog__body {
			max-height: 60vh;
			overflow-y: auto;
	}
	.node-status {
			display: inline-block;
			padding: 2px 8px;
			border-radius: 4px;
			font-size: 12px;
			margin-left: 10px;
	}
	.status-transferred {
			background: #fdf6ec;
			color: #e6a23c;
	}
  ::v-deep .el-checkbox__label {
    display: inline-block;
    padding-left: 10px;
    line-height: 16px;
    font-size: 14px;
    font-weight: bold;
    margin-top: 10px;
}
</style>
