<template>
  <!-- 模板部分保持不变 -->
  <div>
    <el-card>
      <div class="search-container">
        <span class="show-text">任务ID:</span>
        <el-input v-model="taskid" placeholder="请输入任务ID" clearable style="width: 130px; margin-right: 10px" />
        <span class="show-text">生产订单:</span>
        <el-input v-model="taskorder" placeholder="请输入生产订单" clearable style="width: 150px; margin-right: 10px"/>
        <span class="show-text">操作人:</span>
        <el-select
          v-model="checker"
          placeholder="请选择操作人"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in checkerList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span class="show-text">开始时间范围:</span>
        <el-date-picker 
          v-model="timeRange" 
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 360px; margin-right: 10px" />
        
        <span class="show-text">校验状态:</span>
        <el-select v-model="checkStatus" style="width: 120px; margin-right: 10px">
          <el-option label="全部" value="2" />
          <el-option label="已校验" value="1" />
          <el-option label="未校验" value="0" />
        </el-select>
        <!-- <span class="show-text">异常:</span>
        <el-select v-model="abnormalstatus" style="width: 120px; margin-right: 10px">
          <el-option label="全部" value="0" />
          <el-option label="异常" value="1" />
          <el-option label="正常" value="2" />
        </el-select> -->
        <span class="show-text">性质:</span>
        <el-select v-model="natureStatus"  style="width: 120px; margin-right: 10px">
          <el-option label="装配" value="2" />
          <el-option label="机加" value="1" />
          <el-option label="全部" value="0" />
        </el-select>
        <span class="show-text">加班:</span>
        <el-select v-model="addwork" style="width: 120px; margin-right: 10px">
          <el-option label="全部" value="0" />
          <el-option label="加班" value="1" />
          <el-option label="正常" value="2" />
        </el-select>
        <el-button :disabled="!!loading" icon="el-icon-search" plain type="primary" @click="searchTable()">查询</el-button>
        <el-button :disabled="!!multipleSelection.length === 0 || loading" icon="el-icon-check" plain type="success" style="width: 100px;" @click="batchValidate">一键校验</el-button>
        <el-button :disabled=" uesrname != '付延辉'" icon="el-icon-check" plain type="danger" style="position: absolute;
    width: 100px;
    right: 36px;
    top: 70px;width: 100px;" @click="saveValidationRecord2(multipleSelection)">直接校验</el-button>
        <!-- <el-button :disabled="!!loading" icon="el-icon-plus" plain type="warning" style="width: 130px;" @click="addWorkTimeRecord">新增工时记录</el-button> -->
      </div>
      
      <el-tabs v-model="activeTab" type="card" class="custom-tabs">
        <el-table 
          v-loading="loading" 
          :data="tableData" 
          :height="'67vh'" 
          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-class-name="tableRowClassName"  
          @row-click="handleRowClick"
          @selection-change="handleSelectionChange">
          
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column align="center" label="序号" type="index" width="50" fixed />
          <el-table-column align="center" label="工时ID" prop="AID" width="100" fixed />
          <el-table-column align="center" prop="操作人" label="人员" width="120" fixed />
          <el-table-column align="center" prop="订单编号" label="生产订单" width="100" fixed />
          <el-table-column align="center" prop="产品编码" label="物料编码" width="220" />
          <el-table-column align="center" prop="产品名称" label="物料名称" width="190" />
          <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="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) / 60).toFixed(2).replace(/\.?0+$/, '') }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="人员工时" width="100">
            <template slot-scope="scope">
               {{ (scope.row.加工工时 != NULL ? 0 : scope.row.总时长 / 60).toFixed(2).replace(/\.?0+$/, '') }}
            </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" label="工序说明" width="100">
            <template slot-scope="scope">
              {{ scope.row.工序说明 || '' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="异常说明" width="100">
            <template slot-scope="scope">
              {{ scope.row.异常说明 || '' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="校验状态" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.已校验 ? 'success' : 'info'" size="mini">
                {{ scope.row.已校验 ? '已校验' : '未校验' }}
              </el-tag>
            </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="100" fixed="right">
            <template slot-scope="scope">
              <el-button 
                type="text" 
                size="mini" 
                :disabled="!!scope.row.已校验"
                @click="editTask(scope.row)">
                {{ scope.row.已校验 ? '已校验' : '修改' }}
              </el-button>
              <!-- <el-button 
                type="text" 
                size="mini" 
                @click="seetime(scope.row)">
                设备工时
              </el-button> -->
              <!-- <el-button 
                type="text" 
                size="mini" 
                @click="seetime(scope.row)">
                设备工时
              </el-button> -->
            </template>
          </el-table-column>

        </el-table>
        
        <div class="block" style="margin-top: 10px;">
          <el-pagination
            :current-page="pageCurrent"
            :page-sizes="[20, 50, 100]"
            :page-size="pageSize"
            :total="total1"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChanges"
            @current-change="handleCurrentChanges" />
        </div>
      </el-tabs>
    </el-card>

    <!-- 编辑时间弹窗 -->
    <el-dialog 
      :visible.sync="editDialogVisible" 
      :title="currentTask.已校验 ? '查看任务信息' : '编辑任务信息'" 
      width="700px" 
      center
      :close-on-click-modal="false">
      <el-form ref="editForm" :model="editForm" label-width="120px" size="mini" :disabled="!!currentTask.已校验">
        <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="操作人">
          <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-item label="人员工时">
          <el-input v-model="editForm.总时长" readonly>
            <template slot="append">秒</template>
          </el-input>
        </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.当日班次最小标准工时" ></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.已校验"
          :loading="editSubmitLoading" 
          type="primary" 
          @click="submitEditForm"
          :disabled="!editForm.开始时间 || !editForm.结束时间">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 查看工时弹窗 -->
    <el-dialog 
      :visible.sync="seeDialogVisible" 
      title="设备工时" 
      width="1200px" 
      center
      :close-on-click-modal="false">

        <el-table 
          :data="seeForm" 
          :height="'67vh'" 
          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" prop="工位名称" label="工位名称" width="120" />
          <el-table-column align="center" prop="累计分钟" label="累计分钟" width="120" />
          <el-table-column align="center" prop="设备状态" label="设备状态" width="150" />
          <el-table-column align="center" prop="累计秒数" label="累计秒数" width="120" />
          
        </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="seeDialogVisible = false">关闭</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="辅助结束" />
            <el-option label="报工" value="报工" />
          </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="handleProcessChange">
            <el-option 
              v-for="process in processList" 
              :key="process.TaskAID" 
              :label="process.工序名称" 
              :value="process.TaskAID" />
          </el-select>
        </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%">
            <el-option 
              v-for="personne in personnelList" 
              :key="personne.key" 
              :label="personne.label" 
              :value="personne.label" />
          </el-select>
        </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.操作数值" placeholder="请输入数量" />
        </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> -->
  </div>
</template>

<script>
import { postB1 } from '@/api/b1s';
import { getB1 } from '@/api/b1s';
import { patchB1 } from '@/api/b1s';

export default {
  name: 'WorkTimeValidation',
  data() {
    return {
      // 分页
      pageCurrent: 1,
      pageSize: 20,
      total1: 0,
      
      // 搜索条件
      timeRange: [],
      checkStatus: '0',
      natureStatus: '1',
      addwork:'0',
      abnormalstatus: '2',
      
      // 表格数据
      loading: false,
      activeTab: 'first',
      tableData: [],
      multipleSelection: [],
      // 查看工时弹窗
      seeDialogVisible: false,
      // 编辑弹窗
      editDialogVisible: false,
      editSubmitLoading: false,
      currentTask: {},
      editForm: {
        订单编号: '',
        产品编码: '',
        产品名称: '',
        工位名称: '',
        工序名称: '',
        操作人: '',
        操作类别: '',
        操作数值: 0,
        开始时间: '',
        结束时间: '',
        加工工时: 0,
        总时长: 0,
        工艺顺序: 0,
        当日班次最小标准工时:8,
      },
      seeForm: [],
      // 新增相关数据
      orderList: [],
      processList: [],
      personnelList: [],
      
      // 新增工时记录
      // addRecordDialogVisible: false,
      // addRecordLoading: false,
      // addRecordForm: {
      //   操作类别: '',
      //   订单编号: '',
      //   产品编码: '',
      //   产品名称: '',
      //   工序名称: '',
      //   工位名称: '',
      //   操作人: '',
      //   操作数值: '',
      //   开始时间: '',
      //   结束时间: '',
      //   操作内容: '',
      //   操作描述: '',
      //   工位ID: '',
      //   工序ID: ''
      // },
      // addRecordRules: {
      //   操作类别: [{ required: true, message: '请选择操作类别', trigger: 'change' }],
      //   订单编号: [{ required: true, message: '请选择订单编号', trigger: 'change' }],
      //   工序名称: [{ required: true, message: '请选择工序名称', trigger: 'change' }],
      //   操作人: [{ required: true, message: '请选择操作人员', trigger: 'change' }],
      //   开始时间: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
      //   结束时间: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      // },
      
      currentTime: '',
      currentdate: '',
      yescurrentdate: '',
      checkerList: [],
      checker: "",
      checkerLabel: "",

      taskorder: '',
      taskid: '',
      uesrname:''
    }
  },
  
  mounted() {
    this.searchTable()
    this.loadOrderList('') 
    this.loadPersonnelList()
    this.getCheckerList();
    this.getUserName()
  },
  
  methods: {
    // ============ 调用存储过程进行工时校验 ============

    // 在 callBatchValidateSP 方法中添加详细日志
// 修正后的 callBatchValidateSP 方法
// ============ 上传SAP的核心方法 ============

/**
 * 单条记录上传到SAP（整合工序、资源、工时）
 * @param {Object} record - 原始记录数据
 * @param {Object} spDetail - 存储过程计算的结果详情
 */
// ============ 上传SAP的核心方法（完整安全版） ============

/**
 * 单条记录上传到SAP（整合工序、资源、工时）
 * @param {Object} record - 原始记录数据
 * @param {Object} detail - 存储过程计算的结果详情
 * @returns {Object} { success: boolean, error: string }
 */
getUserName() {
  this.uesrname = this.$store.state.user.name;
  console.log(this.uesrname)
},
async uploadToSAP(record, detail) {
  try {
    this.getCurrentTime()
    const uploadMinutes = detail.UploadMinutes || 0
    const workType = detail.WorkType || ''
    console.log(`=== AID ${record.AID} 开始上传SAP ===`)
    console.log(`上传工时: ${uploadMinutes}分钟`)
    // ========== 如果是跳过SAP类型，直接返回成功 ==========
    if (workType === '跳过SAP') {
      console.log(`AID ${record.AID} 总时长为0，跳过SAP上传`)
      return { success: true, warning: '总时长为0，跳过SAP上传' }
    }
    
    // ========== 上传工时小于等于0，返回失败 ==========
    if (uploadMinutes <= 0) {
      const errorMsg = `上传工时小于等于0（${uploadMinutes}分钟）`
      this.$message.error(`AID ${record.AID}: ${errorMsg}`)
      return { success: false, error: errorMsg }
    }
    
    // ========== 1. 基础数据校验 ==========
    if (!record.订单编号) {
      this.$message.error(`AID ${record.AID}: 订单编号为空`)
      return { success: false, error: '订单编号为空' }
    }
    
    if (!record.工序名称) {
      this.$message.error(`AID ${record.AID}: 工序名称为空`)
      return { success: false, error: '工序名称为空' }
    }
    
    if (uploadMinutes <= 0) {
      this.$message.error(`AID ${record.AID}: 上传工时小于等于0`)
      return { success: false, error: '上传工时小于等于0' }
    }
    
    // ========== 2. 获取工序数据和订单数据 ==========
    let processData = []
    let order = null
    
    try {
      const [processResult, orderResult] = await Promise.all([
        this.getProcessDataAsync(record.订单编号).catch(err => {
          console.error(`获取工序数据失败:`, err)
          return []
        }),
        getB1("/ProductionOrders", {
          "$filter": `AbsoluteEntry eq ${record.订单编号}`
        }).catch(err => {
          console.error(`获取订单数据失败:`, err)
          return null
        })
      ])
      
      processData = processResult || []
      console.log(processResult)
      console.log(`获取到工序数据: ${processData.length}条`)
      
      // 安全地获取 order
      if (!orderResult) {
        this.$message.error(`AID ${record.AID}: 获取订单API返回为空`)
        return { success: false, error: '获取订单API返回为空' }
      }
      
      if (!orderResult.data) {
        console.error('orderResult 结构异常:', orderResult)
        this.$message.error(`AID ${record.AID}: 未获取到生产订单`)
        return { success: false, error: '订单数据格式异常' }
      }
      
      if (!orderResult.data.value || orderResult.data.value.length === 0) {
        this.$message.error(`AID ${record.AID}: 未找到订单 ${record.订单编号}`)
        return { success: false, error: `未找到订单 ${record.订单编号}` }
      }
      
      order = orderResult.data.value[0]
      console.log(`获取到订单: AbsoluteEntry=${order.AbsoluteEntry}`)
      
    } catch (apiError) {
      this.$message.error(`AID ${record.AID}: 获取数据失败 - ${apiError.message}`)
      console.error(`AID ${record.AID} 获取数据异常:`, apiError)
      return { success: false, error: `获取数据失败: ${apiError.message}` }
    }
    
    // ========== 3. 计算StageID偏移量 ==========
    let jia = 0
    try {
      jia = this.calculateStageOffset(order.ProductionOrderLines || [])
      console.log(`StageID偏移量: ${jia}`)
    } catch (offsetError) {
      console.error(`计算StageID偏移量失败:`, offsetError)
      jia = 0
    }
    
    // ========== 4. 找到当前工序 ==========
    console.log(record)
    const currentProcess = processData.find(item => item.工序名称 === record.工序名称 && item.工艺顺序 === record.订单行号)
    if (!currentProcess) {
      this.$message.error(`AID ${record.AID}: 未找到工序 "${record.工序名称}"`)
      console.error(`可用工序列表:`, processData.map(p => p.工序名称))
      return { success: false, error: `未找到工序: ${record.工序名称}` }
    }
    
    const currentStageId = (currentProcess.工艺顺序 || 0) + jia
    console.log(currentProcess)
    console.log(`当前工序StageID: ${currentStageId}`)
    
    // ========== 5. 准备要添加的资源 ==========
    let resourcesToAdd = []
    try {
      resourcesToAdd = await this.prepareResourcesToAdd(record, currentProcess, currentStageId)
      console.log(`准备资源: ${resourcesToAdd.length}个`)
    } catch (resourceError) {
      console.error(`准备资源失败:`, resourceError)
      this.$message.error(`AID ${record.AID}: 准备资源失败 - ${resourceError.message}`)
      return { success: false, error: `准备资源失败: ${resourceError.message}` }
    }
    
    // ========== 6. 更新SAP：添加工序和资源 ==========
    let hasUpdated = false
    try {
      hasUpdated = await this.updateSapWithAllStagesAndResources(
        record.订单编号,
        order,
        processData,
        jia,
        resourcesToAdd,
        record
      )
      console.log(`SAP工序资源更新: ${hasUpdated ? '已更新' : '无需更新'}`)
    } catch (updateError) {
      console.error(`更新SAP工序资源失败:`, updateError)
      this.$message.error(`AID ${record.AID}: 更新SAP工序资源失败 - ${updateError.message}`)
      return { success: false, error: `更新SAP工序资源失败: ${updateError.message}` }
    }
    
    // ========== 7. 重新获取订单数据（如果更新了SAP） ==========
    let updatedOrder = order
    if (hasUpdated) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const reorderResult = await getB1("/ProductionOrders", {
          "$filter": `AbsoluteEntry eq ${record.订单编号}`
        })
        if (reorderResult && reorderResult.data && reorderResult.data.value && reorderResult.data.value.length > 0) {
          updatedOrder = reorderResult.data.value[0]
          console.log(`重新获取订单数据成功`)
        }
      } catch (reorderError) {
        console.warn(`重新获取订单数据失败，使用原订单:`, reorderError)
      }
    }
    
    // ========== 8. 创建工时单据 ==========
    const params = []
    
    try {
      if (record.操作类别 === '报工') {
        if ((record.加工工时 || 0) > 0) {
          const equipmentHours = (record.加工工时 / 60) || 0
          await this.addEquipmentTimeSheet(record, updatedOrder, currentStageId, equipmentHours, params, false)
        }
        console.log(record.总时长,(record.加工工时 || 0))
        if (record.总时长 > 0 && (record.加工工时 || 0) === 0) {
          
          await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, false)
        }
      } else if (record.操作类别 === '辅助结束') {
        if ((record.加工工时 || 0) > 0) {
          const equipmentHours = (record.加工工时 / 60) || 0
          await this.addEquipmentTimeSheet(record, updatedOrder, currentStageId, equipmentHours, params, true)
        }
        
        if (record.总时长 > 0 && (record.加工工时 || 0) === 0) {
          await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
        }
      } else if (record.操作类别 && record.操作类别.includes('加班')) {
        if (record.总时长 > 0) {
          await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
        }
      } else if (record.操作类别 === '开始加工') {
        if (record.总时长 > 0) {
          await this.addPersonnelTimeSheet3(record, updatedOrder, currentStageId, uploadMinutes, params, true)
        }
      } else {
        console.warn(`未知的操作类别: ${record.操作类别}`)
      }
      
      console.log(`创建工时单据参数: ${params.length}个`)
      
    } catch (paramsError) {
      console.error(`创建工时单据参数失败:`, paramsError)
      
      this.$message.error(`AID ${record.AID}: 创建工时单据参数失败 - ${paramsError.message}`)
      throw new Error(`AID ${record.AID}: 创建工时单据参数失败 - ${paramsError.message}`) 
      return { success: false, error: `创建工时单据参数失败: ${paramsError.message}` }
    }
    
    // ========== 9. 提交工时单据到SAP ==========
    if (params.length > 0) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))

        const reorderResult = await getB1("/ProductionOrders", {
          "$filter": `AbsoluteEntry eq ${record.订单编号}`
        })

        if (!reorderResult.success || !reorderResult.data?.value?.length) {
          return { success: false, error: '重新获取生产订单失败' }
        }

        const updatedOrder = reorderResult.data.value[0]
        const lines = updatedOrder.ProductionOrderLines || []

        lines.forEach(line => {
          const matched = params.find(param => Number(line.LineNumber) === Number(param.BaseLine))
          if (matched) {
            line.PlannedQuantity = Number(line.IssuedQuantity) + Number(matched.Quantity)
          }
        })

        const patchResult = await patchB1(`ProductionOrders(${updatedOrder.AbsoluteEntry})`, {
          ProductionOrderLines: lines,
          ProductionOrdersStages: updatedOrder.ProductionOrdersStages || []
        })

        if (!patchResult.success) {
          this.$message.error(patchResult.message)
          return { success: false, error: patchResult.message || '更新生产订单PlannedQuantity失败' }
        }
      } catch (reorderError) {
        console.warn(`重新获取订单数据失败:`, reorderError)
        return { success: false, error: reorderError.message || '更新生产订单PlannedQuantity异常' }
      }
      try {
        const startDate = record.开始时间 ? record.开始时间.split(' ')[0] : this.currentdate
        const result = await postB1("/InventoryGenExits", {
          "DocDate": startDate,
          "DocDueDate": startDate,
          "Comments": `MES报工 AID:${record.AID}`,
          "DocumentLines": params
        })
        
        if (result && result.success) {
          console.log(`AID ${record.AID} 成功创建${params.length}个工时记录`)
          this.$message.success(`AID ${record.AID} 上传SAP成功`)
          return { success: true }
        } else {
          const errorMsg = (result && result.message) || '工时单据创建失败'
          this.$message.error(`AID ${record.AID}: ${errorMsg}`)
          return { success: false, error: errorMsg }
        }
      } catch (postError) {
        this.$message.error(`AID ${record.AID}: 提交工时单据失败 - ${postError.message}`)
        console.error(`提交工时单据失败:`, postError)
        return { success: false, error: `提交工时单据失败: ${postError.message}` }
      }
    } 
    // else {
    //   console.warn(`AID ${record.AID} 没有需要上传的工时单据`)
    //   // 某些类型的记录可能不需要上传工时，也算成功
    //   this.$message.info(`AID ${record.AID} 无工时单据，跳过SAP上传`)
    //   return { success: true, warning: '无工时单据' }
    // }
    
  } catch (error) {
    const errorMsg = error.message || '未知错误'
    this.$message.error(`AID ${record.AID} 上传SAP异常: ${errorMsg}`)
    console.error(`AID ${record.AID} 上传SAP异常:`, error)
    return { success: false, error: errorMsg }
  }
},
// 修正后的 callBatchValidateSP 方法
async callBatchValidateSP(recordAIDs) {
  const aidList = recordAIDs.join(',')
  const currentUser = this.getCurrentUser()
  
  console.log('=== 调用存储过程 ===')
  console.log('RecordAIDs:', aidList)
  
  var param = [
    ['RecordAIDs', aidList],
    ['Operator', currentUser],
    ['Editor', currentUser],
    ['SuccessCount', '0', 'int', '2'],
    ['FailCount', '0', 'int', '2'],
    ['ResultDetails', '', 'string', '2']
  ]
  
  var Data = this.CreateData('11', 'usp_BatchValidateWorkTime', param)
  
  try {
    const response = await this.ExecDatabase(Data)
    
    // ========== 详细打印响应结构 ==========
    console.log('=== 完整响应 ===')
    console.log('response:', JSON.stringify(response, null, 2))
    console.log('response.data:', response.data)
    console.log('response.data 类型:', typeof response.data)
    console.log('response.data 是否为数组:', Array.isArray(response.data))
    
    // 尝试多种方式获取结果
    let result = null
    
    // 方式1：response.data[0]
    if (response.data && Array.isArray(response.data) && response.data.length > 0) {
      result = response.data[0]
      console.log('从 response.data[0] 获取:', result)
    }
    // 方式2：response.data 本身就是结果对象
    else if (response.data && typeof response.data === 'object' && !Array.isArray(response.data)) {
      result = response.data
      console.log('从 response.data 直接获取:', result)
    }
    // 方式3：response.data.output
    else if (response.data && response.data.output) {
      result = response.data.output
      console.log('从 response.data.output 获取:', result)
    }
    // 方式4：response.output
    else if (response.output) {
      result = response.output
      console.log('从 response.output 获取:', result)
    }
    // 方式5：response 本身
    else if (response.SuccessCount !== undefined) {
      result = response
      console.log('从 response 本身获取:', result)
    }
    
    if (!result) {
      console.error('无法解析响应数据')
      return {
        success: false,
        successCount: 0,
        failCount: recordAIDs.length,
        error: '无法解析响应数据',
        resultDetails: { Details: [], RatioGroups: [] }
      }
    }
    
    console.log('最终使用的 result:', result)
    
    const successCount = result.SuccessCount || 0
    const failCount = result.FailCount || 0
    const resultDetailsStr = result.ResultDetails || '{}'
    
    console.log('ResultDetails 字符串:', resultDetailsStr)
    
    // 解析 ResultDetails JSON
    let parsedDetails = { Details: [], RatioGroups: [] }
    try {
      parsedDetails = JSON.parse(resultDetailsStr)
      console.log('解析后的 ResultDetails:', parsedDetails)
    } catch (e) {
      console.error('JSON解析失败:', e)
    }
    
    return {
      success: true,
      successCount,
      failCount,
      resultDetails: parsedDetails
    }
  } catch (error) {
    console.error('调用存储过程失败:', error)
    return {
      success: false,
      successCount: 0,
      failCount: recordAIDs.length,
      error: error.message,
      resultDetails: { Details: [], RatioGroups: [] }
    }
  }
},


    async callSingleValidateSP(recordAID) {
      const currentUser = this.getCurrentUser()
      
      var param = [
        ['RecordAID', recordAID],
        ['Operator', currentUser],
        ['Editor', currentUser],
        ['StartTime', null],
        ['EndTime', null],
        ['Success', '0', 'bit', '2'],
        ['Message', '', 'string', '2'],
        ['SAPDocumentLine', '', 'string', '2']
      ]
      
      var Data = this.CreateData('11', 'usp_ValidateWorkTime', param)
      
      try {
        const response = await this.ExecDatabase(Data)
        const output = response.data.output || []
        
        return {
          success: output.find(p => p.Name === 'Success')?.Value === '1',
          message: output.find(p => p.Name === 'Message')?.Value || '',
          sapLine: output.find(p => p.Name === 'SAPDocumentLine')?.Value
        }
      } catch (error) {
        console.error('单条校验失败:', error)
        return {
          success: false,
          message: error.message
        }
      }
    },
    getCheckerList() {
      this.checkerList = [];
      var Data = this.CreateData("11", "人员管理_人员信息查询_质检部门_查询");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.checkerList.push({
            label: response.data[i].Personnel_Name,
            value: response.data[i].Personnel_Number,
          });
        }
      });
    },
    // ============ 表格相关方法 ============
    tableRowClassName({ row, rowIndex }) {
      // 原有：结束时间为空的记录显示红色
      if (!row.结束时间 || row.结束时间 === '') {
        return 'row-without-endtime'
      }
      
      // 新增：工时大于33000秒时，整行变成红色
      const workTime = row.加工工时 || 0
      const personTime = row.总时长 || 0
      if (workTime > 33000 || personTime > 33000) {
        return 'row-time-exceed'
      }
      
      // 新增：结束时间小于昨天的记录，整行变成橙色
      const endTime = row.结束时间
      if (endTime) {
        const endDate = new Date(endTime)
        const yesterday = new Date()
        yesterday.setDate(yesterday.getDate() - 1)
        yesterday.setHours(0, 0, 0, 0)
        
        if (endDate < yesterday) {
          return 'row-time-old'
        }
      }
      
      return ''
    },
    
    handleRowClick(row) {
      this.currentTask = row
    },
    
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    
    // ============ 数据加载方法 ============
    loadPersonnelList() {
      var param = []
      var Data = this.CreateData('11', '系统管理_人员管理_所有有效人员查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.personnelList = response.data.map(person => ({
            key: person.人员编号,
            label: person.人员姓名,
            disabled: false
          }))
        }
      })
    },
    
    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 = []
      })
    },
    
    handleOrderChange(orderId) {
      if (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 = []
      }
    },
    
    loadProcessList(orderId) {
      var param = [['订单编号', orderId]]
      var Data = this.CreateData('11', '工时校验_获取订单工序', param)
      this.ExecDatabase(Data).then(response => {
        this.processList = response.data || []
      }).catch(error => {
        console.error('加载工序列表失败:', error)
        this.processList = []
      })
    },
    
    handleProcessChange(taskAID) {
      const selectedProcess = this.processList.find(process => process.TaskAID == taskAID)
      if (selectedProcess) {
        this.addRecordForm.工序名称 = selectedProcess.工序名称
        this.addRecordForm.工位名称 = selectedProcess.工位名称
        this.addRecordForm.工位ID = selectedProcess.工位ID
        this.addRecordForm.工序ID = taskAID
      }
    },
    
    // ============ 分页方法 ============
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    },
    
    searchTable() {
      this.loading = true
      
      var param = []
      if (this.timeRange && this.timeRange.length === 2) {
        param[0] = ['开始时间', this.timeRange[0]]
        param[1] = ['结束时间', this.timeRange[1]]
      }
      param[param.length] = ['校验状态', this.checkStatus || 0]
      param[param.length] = ['过滤性质', this.natureStatus || 0]
      param[param.length] = ['异常', this.abnormalstatus || 0]
      param[param.length] = ['PageCurrent', this.pageCurrent]
      param[param.length] = ['PageSize', this.pageSize]
      param[param.length] = ['PageCount', '1111', 'int', '1']
      param[param.length] = ['ItemCount', '1111', 'int', '1']
      param[param.length] = ['任务ID', this.taskid || 0]
      param[param.length] = ['生产订单', this.taskorder || 0]
      param[param.length] = ['加班', this.addwork || 0]
      const selectedChecker = this.checkerList.find(
        (item) => item.value === this.checker
      );
      param.push(['人员', selectedChecker ? selectedChecker.label : 0])
      var Data = this.CreateData('11', '工时校验_获取昨日之前操作记录列表', param)
      this.ExecDatabase(Data).then(response => {
        // this.tableData = response.data.result || []
        let dataList = response.data.result || []
        this.total1 = parseInt(response.data.output[0].ItemCount)
        dataList = dataList.map(item => {
        let colorPriority = 0 // 0: 无颜色, 1: 橙色, 2: 红色
        
        // 检查是否有颜色标记
        if (!item.结束时间 || item.结束时间 === '') {
          colorPriority = 2 // 红色优先
        } else {
          const workTime = item.加工工时 || 0
          const personTime = item.总时长 || 0
          if (workTime > 33000 || personTime > 33000) {
            colorPriority = 2 // 红色优先
          } else {
            const endTime = item.结束时间
            if (endTime) {
              const endDate = new Date(endTime)
              const yesterday = new Date()
              yesterday.setDate(yesterday.getDate() - 1)
              yesterday.setHours(0, 0, 0, 0)
              
              if (endDate < yesterday) {
                colorPriority = 1 // 橙色
              }
            }
          }
        }
        
        return {
          ...item,
          colorPriority: colorPriority
        }
      })
      
      // 按颜色优先级排序：红色(2) > 橙色(1) > 无颜色(0)
      dataList.sort((a, b) => {
        // 优先按颜色优先级排序
        if (a.colorPriority !== b.colorPriority) {
          return b.colorPriority - a.colorPriority
        }
        // 颜色优先级相同时，按原来的顺序（可以按AID或其他字段）
        return b.AID - a.AID
      })
      
      this.tableData = dataList
      this.loading = false
      }).catch(error => {
        this.$message.error('查询失败：' + error.message)
        this.loading = false
      })
    },
    
    // ============ 工具方法 ============
    getCurrentTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, "0")
      const day = String(now.getDate()).padStart(2, "0")
      const hours = String(now.getHours()).padStart(2, "0")
      const minutes = String(now.getMinutes()).padStart(2, "0")
      const seconds = String(now.getSeconds()).padStart(2, "0")
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      this.currentdate = `${year}-${month}-${day}`
      this.yescurrentdate = `${year}-${month}-${day}`
    },
    
    getCurrentUser() {
      return this.$store.state.user.name
    },
    
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    },
    
    // ============ 工时校验核心方法 ============
    // 获取资源VisCode
    async getResourceVisCode(resourceName) {
      try {
        var params = [['资源名称', resourceName]]
        var data = this.CreateData('11', '工时校验_获取资源', params)
        const response = await this.ExecDatabase(data)
        
        if (response.data && response.data.length > 0 ) {
          return {
            visCode: response.data[0].VisCode,
            resourceName: response.data[0].资源名称
          }
        }
        this.$message.error(`资源${resourceName}获取失败`)
        throw new Error(`资源${resourceName}获取失败`)
        return null
        
      } catch (error) {
        this.$message.error(`资源${resourceName}获取失败`)
        throw new Error(`资源${resourceName}获取失败`)
        // console.error(`获取资源VisCode失败: ${resourceName}`, error)
        throw new Error('资源获取失败')
      }
    },
    
    // 获取工序数据（异步）
    async getProcessDataAsync(orderId) {
      try {
        var params = [['订单编号', orderId]]
        var processlist = this.CreateData('11', '工时校验_获取订单工序', params)
        const response = await this.ExecDatabase(processlist)
        return response.data || []
      } catch (error) {
        console.error('获取工序数据失败:', error)
        return []
      }
    },
    
    // 计算StageID偏移量
    calculateStageOffset(productionOrderLines) {
      let jia = 0
      productionOrderLines.forEach(item => {
        if (item.ItemType == 'pit_Item') {
          item.StageID = 1
        }
        if (item.ItemName == '期初物料') {
          // jia = item.StageID || 1
          item.StageID = 1
        }
        if (item.ItemNo == 'Z108-001' ||  item.ItemNo == '26') {
          // jia = item.StageID || 1
          item.StageID = 1
        }
      })
      return jia
    },
    
    // 检查资源是否已存在
    isResourceExists(productionOrderLines, itemNo, stageId) {
      return productionOrderLines.some(item => 
        item.ItemType === 'pit_Resource' &&
        item.ItemNo === itemNo && 
        item.StageID === stageId
      )
    },
    
    // 添加所有缺失的工序到生产订单（新增方法）
    async addAllMissingStages(absoluteEntry, productionOrdersStages, processData, jia) {
      // 复制现有的工序
      let updatedStages = [...productionOrdersStages]
      let hasNewStage = false
      
      // 遍历所有工序，添加缺失的工序
      processData.forEach(element => {
        const stageId = element.工艺顺序 + jia
        const existingIndex = updatedStages.findIndex(item => item.StageID === stageId)
        
        if (existingIndex !== -1) {
          // 找到了相同 StageID 的工序
          if (updatedStages[existingIndex].Name !== element.工序名称) {
            // Name 不同，执行更新
            updatedStages[existingIndex] = {
              ...updatedStages[existingIndex],
              "Name": element.工序名称,
              "StageEntry": element.顺序编号
            }
            hasNewStage = true
            console.log(`更新工序: ${element.工序名称}, StageID: ${stageId}, 原名称: ${updatedStages[existingIndex].Name}`)
          }
        } else {
          // 没有找到相同 StageID，新增工序
          updatedStages.push({
            "DocEntry": absoluteEntry,
            "Name": element.工序名称,
            "StageEntry": element.顺序编号,
            "StageID": stageId
          })
          hasNewStage = true
          console.log(`添加工序: ${element.工序名称}, StageID: ${stageId}`)
        }
      })
      
      return {
        stages: updatedStages,
        hasNewStage: hasNewStage
      }
    },
    
    // 添加所有缺失的资源到生产订单（新增方法）
    async addAllMissingResources(absoluteEntry, productionOrderLines, processData, stageId, resourcesToAdd) {
      // 复制现有的资源行
      let updatedLines = [...productionOrderLines]
      let hasNewResource = false
      
      // 添加当前报工工序需要的资源
      console.log(111,resourcesToAdd)
      console.log(222,updatedLines)
      if (resourcesToAdd && resourcesToAdd.length > 0) {
        for (const resource of resourcesToAdd) {
          const exists = this.isResourceExists(updatedLines, resource.itemNo, resource.stageId)
          console.log(exists)
          if (!exists) {
            updatedLines.push({
              "ProductionOrderIssueType": "im_Manual",
              "Warehouse": "W03",
              "ItemType": "pit_Resource",
              "ItemName": resource.itemName,
              "ItemNo": resource.itemNo,
              "StageID": resource.stageId
            })
            hasNewResource = true
            console.log(`添加资源: ${resource.itemName}, StageID: ${resource.stageId}`)
          }
        }
      }
      
      return {
        lines: updatedLines,
        hasNewResource: hasNewResource
      }
    },
    // ============ 查看工时相关 ============
    async seetime(row){
      this.currentTask = row
      this.seeDialogVisible = true
      var queryParam = [
        ['工位名称', row.工位名称],
      ]
      var queryData = this.CreateData('11', '工时校验_获取设备数据', queryParam)
      const response = await this.ExecDatabase(queryData)
      this.seeForm = response.data
      
    },
    
    // ============ 编辑任务相关 ============
    editTask(row) {
      this.currentTask = row
      this.editForm = {
        订单编号: row.订单编号,
        产品编码: row.产品编码,
        产品名称: row.产品名称,
        工序名称: row.工序名称,
        工位名称: row.工位名称,
        操作人: row.操作人,
        操作类别: row.操作类别,
        操作数值: row.操作数值 || 0,
        开始时间: row.开始时间,
        结束时间: row.结束时间,
        加工工时: row.加工工时 || 0,
        总时长: row.总时长 || 0,
        工艺顺序: row.订单行号 || 0,
        当日班次最小标准工时 : row.当日班次最小标准工时 || 0
      }
      this.editDialogVisible = true
    },
    
    calculateWorkTime() {
      if (this.editForm.开始时间 && this.editForm.结束时间) {
        const start = new Date(this.editForm.开始时间)
        const end = new Date(this.editForm.结束时间)
        const diff = end.getTime() - start.getTime()
        const seconds = Math.round(diff / 1000)
        this.editForm.加工工时 = seconds
        this.editForm.总时长 = seconds
      } else {
        this.editForm.加工工时 = 0
        this.editForm.总时长 = 0
      }
    },
    
    // 提交编辑表单
    // 提交编辑表单（单条校验）
async submitEditForm() {
  this.editSubmitLoading = true
  try {
    // // 1. 先调用存储过程计算
    // const spResult = await this.callSingleValidateSP(this.currentTask.AID)
    
    // if (!spResult.success) {
    //   this.$message.error('工时计算失败：' + spResult.message)
    //   return
    // }
    
    // 2. 更新本地数据库
    await this.updateValidationStatus(this.editForm)
    
    // 3. 上传到SAP（如果不是订单3886）
    // if (this.currentTask.订单编号 != 3886) {
    //   const uploadResult = await this.uploadToSAP(this.currentTask, {
    //     UploadMinutes: spResult.uploadMinutes || 0
    //   })
      
    //   if (uploadResult.success) {
    //     this.$message.success('校验成功，已上传SAP')
    //   } else {
    //     this.$message.warning('校验成功，但SAP上传失败：' + uploadResult.error)
    //   }
    // } else {
    //   this.$message.success('校验成功（订单3886，未上传SAP）')
    // }
    
    this.editDialogVisible = false
    this.searchTable()
  } catch (error) {
    this.$message.error('修改失败：' + error.message)
  } finally {
    this.editSubmitLoading = false
  }
},
    
    // 准备要添加的资源（仅当前工序）
    // 简化后的 prepareResourcesToAdd（只保留资源准备逻辑）
async prepareResourcesToAdd(data, currentProcess, stageId) {
  const resources = []
  
  // 获取正常设备资源
  // const equipmentResource = await this.getResourceVisCode(currentProcess.工位名称)
  const equipmentResource = await this.getResourceVisCode(data.工位名称)
  if (equipmentResource) {
    resources.push({
      type: 'equipment',
      itemName: data.工位名称,
      itemNo: equipmentResource.visCode,
      stageId: stageId,
      isAssistant: false
    })
  }
  
  // 根据操作类型判断是否需要添加其他资源
  if (data.操作类别 === '报工') {
    const personnelResource = await this.getResourceVisCode(data.操作人)
    if (personnelResource) {
      resources.push({
        type: 'personnel',
        itemName: data.操作人,
        itemNo: personnelResource.visCode,
        stageId: stageId,
        isAssistant: false
      })
    }
  } else if (data.操作类别 === '辅助结束') {
    const assistantEquipmentName = `辅助-${data.工位名称}`
    const assistantEquipment = await this.getResourceVisCode(assistantEquipmentName)
    if (assistantEquipment) {
      resources.push({
        type: 'equipment',
        itemName: assistantEquipmentName,
        itemNo: assistantEquipment.visCode,
        stageId: stageId,
        isAssistant: true
      })
    }
    
    const assistantPersonnelName = `辅助-${data.操作人}`
    const assistantPersonnel = await this.getResourceVisCode(assistantPersonnelName)
    if (assistantPersonnel) {
      resources.push({
        type: 'personnel',
        itemName: assistantPersonnelName,
        itemNo: assistantPersonnel.visCode,
        stageId: stageId,
        isAssistant: true
      })
    }
  } else if (data.操作类别 && data.操作类别.includes('加班')) {
    const addworkName = `加班-${data.操作人}`
    const addwork = await this.getResourceVisCode(addworkName)
    if (addwork) {
      resources.push({
        type: 'personnel',
        itemName: addworkName,
        itemNo: addwork.visCode,
        stageId: stageId,
        isAssistant: true
      })
    }
  } else if (data.操作类别  === '开始加工') {
    const startName = `${data.操作人}`
    const startwork = await this.getResourceVisCode(startName)
    if (startwork) {
      resources.push({
        type: 'personnel',
        itemName: startName,
        itemNo: startwork.visCode,
        stageId: stageId,
        isAssistant: true
      })
    }
  }
  
  return resources
},
    
    // 更新SAP：添加工序和资源（新增方法）
    async updateSapWithAllStagesAndResources(orderId, order, processData, jia, resourcesToAdd, record) {
  try {
    // 1. 添加所有缺失的工序
    const stagesResult = await this.addAllMissingStages(
      order.AbsoluteEntry,
      order.ProductionOrdersStages,
      processData,
      jia
    )
    
    // 2. 添加所有缺失的资源（仅当前工序）
    const resourcesResult = await this.addAllMissingResources(
      order.AbsoluteEntry,
      order.ProductionOrderLines,
      processData,
      resourcesToAdd[0]?.stageId,
      resourcesToAdd
    )
    
    // 3. 如果有新的工序或资源，更新到SAP
    if (stagesResult.hasNewStage || resourcesResult.hasNewResource) {
      console.log('更新SAP生产订单，添加工序和资源')
      
      const aaa = await patchB1(`ProductionOrders(${order.AbsoluteEntry})`, {
        "ProductionOrderLines": resourcesResult.lines,
        "ProductionOrdersStages": stagesResult.stages
      })
      console.log(aaa)
      if (!aaa.success) {
        this.$message.error(`AID ${record.AID}: 更新SAP工序资源失败 - ${aaa.message}`)
        return false
      } else {
        let message = ''
        if (stagesResult.hasNewStage) {
          message += '添加工序成功'
        }
        if (resourcesResult.hasNewResource) {
          message += (message ? '，' : '') + '添加资源成功'
        }
        console.log(`AID ${record.AID}: ${message}`)
        return true
      }
    } else {
      console.log('没有新的工序或资源需要添加')
      return false
    }
    
  } catch (error) {
    
    console.error('更新SAP失败:', error)
    this.$message.error(`AID ${record.AID}: 更新SAP工序资源异常 - ${error.message}`)
    throw error
  }
},
    
    
      // 添加设备工时单据
    async addEquipmentTimeSheet(data, order, stageId, workHours, params, isAssistant) {
  const equipmentName = isAssistant ? 
    `辅助-${data.工位名称}` : 
    data.工位名称
  
  console.log(`查找设备资源: ${equipmentName}, StageID: ${stageId}`)
  
  const equipmentResource = await this.getResourceVisCode(equipmentName)
  if (!equipmentResource) {
    const errorMsg = `未找到设备资源: ${equipmentName}`
    this.$message.error(errorMsg)
    return { success: false, error: errorMsg }
  }
  console.log(order.ProductionOrderLines)
  const equipmentLine = order.ProductionOrderLines.find(item =>
    item.ItemType === 'pit_Resource' &&
    item.ItemNo == equipmentResource.visCode &&
    item.StageID == stageId
  )

  
  console.log("123",equipmentLine)
  
  if (!equipmentLine || !equipmentLine.LineNumber) {
    const errorMsg = `未找到设备资源行: ${equipmentName}, StageID: ${stageId}`
    this.$message.error(errorMsg)
    return { success: false, error: errorMsg }
  }
  
  // ========== 直接使用传入的工时，不再调整 ==========
  params.push({
    "Quantity": workHours,
    "BaseType": 202,
    "BaseEntry": Number(data.订单编号),
    "BaseLine": equipmentLine.LineNumber,
    "LineType": "dlt_Resource",
    "WarehouseCode": '',
    "U_ResName": data.工位名称
  })
  
  console.log(`添加设备工时单据: ${equipmentName}, LineNumber: ${equipmentLine.LineNumber}, 工时: ${workHours}分钟`)
  return { success: true }
},
    // 添加人员工时单据
    async addPersonnelTimeSheet(data, order, stageId, workHours, params, isAssistant) {
      const personnelName = isAssistant ? 
        (data.操作类别 && data.操作类别.includes('加班') ? `加班-${data.操作人}` : `辅助-${data.操作人}`) : 
        data.操作人
      
      console.log(`查找人员资源: ${personnelName}, StageID: ${stageId}`)
      
      const personnelResource = await this.getResourceVisCode(personnelName)
      if (!personnelResource) {
        const errorMsg = `未找到人员资源: ${personnelName}`
        this.$message.error(errorMsg)
        return { success: false, error: errorMsg }
      }
      
      const personnelLine = order.ProductionOrderLines.find(item =>
        item.ItemType === 'pit_Resource' &&
        item.ItemNo === personnelResource.visCode &&
        item.StageID === stageId
      )
      
      if (!personnelLine || !personnelLine.LineNumber) {
        const errorMsg = `未找到人员资源行: ${personnelName}, StageID: ${stageId}`
        this.$message.error(errorMsg)
        return { success: false, error: errorMsg }
      }
      
      // ========== 直接使用存储过程计算好的工时，不再调整 ==========
      params.push({
        "Quantity": workHours,  // 直接使用传入的 workHours（来自存储过程）
        "BaseType": 202,
        "BaseEntry": Number(data.订单编号),
        "BaseLine": personnelLine.LineNumber,
        "LineType": "dlt_Resource",
        "WarehouseCode": '',
        "U_ResName": data.操作人
      })
      
      console.log(`添加人员工时单据: ${personnelName}, LineNumber: ${personnelLine.LineNumber}, 工时: ${workHours}分钟`)
      return { success: true }
    },
async addPersonnelTimeSheet3(data, order, stageId, workHours, params, isAssistant) {
  const personnelName = data.操作人
  
  console.log(`查找人员资源: ${personnelName}, StageID: ${stageId}`)
  
  const personnelResource = await this.getResourceVisCode(personnelName)
  if (!personnelResource) {
    const errorMsg = `未找到人员资源: ${personnelName}`
    this.$message.error(errorMsg)
    return { success: false, error: errorMsg }
  }
  
  const personnelLine = order.ProductionOrderLines.find(item =>
    item.ItemType === 'pit_Resource' &&
    item.ItemNo === personnelResource.visCode &&
    item.StageID === stageId
  )
  
  if (!personnelLine || !personnelLine.LineNumber) {
    const errorMsg = `未找到人员资源行: ${personnelName}, StageID: ${stageId}`
    this.$message.error(errorMsg)
    return { success: false, error: errorMsg }
  }
  
  // ========== 直接使用传入的工时，不再调整 ==========
  params.push({
    "Quantity": workHours,
    "BaseType": 202,
    "BaseEntry": Number(data.订单编号),
    "BaseLine": personnelLine.LineNumber,
    "LineType": "dlt_Resource",
    "WarehouseCode": '',
    "U_ResName": data.操作人
  })
  
  console.log(`添加人员工时单据: ${personnelName}, LineNumber: ${personnelLine.LineNumber}, 工时: ${workHours}分钟`)
  return { success: true }
},
    // 更新数据库校验状态
    async updateValidationStatus(data) {
      var 总时长 = this.editForm.总时长
      var param = [
        ['orderAID', this.currentTask.AID],
        ['开始时间', this.editForm.开始时间],
        ['结束时间', this.editForm.结束时间],
        ['总时长', 总时长],
        ['操作人', this.getCurrentUser()],
        ['最后编辑人', this.getCurrentUser()],
        ['当日班次最小标准工时', this.editForm.当日班次最小标准工时]
      ];
      var Data = this.CreateData('11', '工时校验_保存校验记录', param)
      await this.ExecDatabase(Data)
    },
    // ============ 保存校验记录 ============
    /**
     * 保存校验记录到数据库
     * @param {Object} record - 记录对象
     */
    async saveValidationRecord(record) {
      try {
        var param = [
          ['AID列表', record.AID],
          ['操作人', this.getCurrentUser()],
          ['最后编辑人', this.getCurrentUser()]
        ]
        var Data = this.CreateData('11', '工时校验_批量保存校验记录', param)
        await this.ExecDatabase(Data)
        
        console.log(`AID ${record.AID} 校验记录已保存`)
        return { success: true }
      } catch (error) {
        console.error(`AID ${record.AID} 保存校验记录失败:`, error)
        return { success: false, error: error.message }
      }
    },
    async saveValidationRecord2(rows) {
      console.log(rows)
      let aids = rows.map(item => item.AID)
      try {
        var param = [
          ['AID列表', aids],
          ['操作人', this.getCurrentUser()],
          ['最后编辑人', this.getCurrentUser()]
        ]
        var Data = this.CreateData('11', '工时校验_批量保存校验记录', param)
        await this.ExecDatabase(Data)
        
        console.log(`AID ${aids} 校验记录已保存`)

        this.searchTable()
      } catch (error) {
        console.error(`AID ${aids} 保存校验记录失败:`, error)
        this.searchTable()
      }
    },
    // ============ 标记单条记录为已校验 ============
    /**
     * 将记录标记为已校验
     * @param {number} aid - 记录ID
     */
    async markAsValidated(aid) {
      try {
        var param = [
          ['orderAID', aid],
          ['操作人', this.getCurrentUser()],
          ['最后编辑人', this.getCurrentUser()]
        ]
        var Data = this.CreateData('11', '工时校验_保存校验记录', param)
        await this.ExecDatabase(Data)
        console.log(`AID ${aid} 标记为已校验`)
        return { success: true }
      } catch (error) {
        console.error(`AID ${aid} 标记已校验失败:`, error)
        return { success: false, error: error.message }
      }
    },
    // ============ 批量校验 ============
    // 修改原有的 batchValidate 方法
    // 修改 batchValidate 方法
// ============ 批量校验 ============
async batchValidate() {
  if (this.multipleSelection.length === 0) {
    this.$message.warning('请选择要校验的记录')
    return
  }
  
  // 过滤出未校验的记录
  const unvalidatedRecords = this.multipleSelection.filter(item => !item.已校验)
  
  if (unvalidatedRecords.length === 0) {
    this.$message.warning('选中的记录都已校验过')
    return
  }
  
  this.$confirm(`确定要校验选中的 ${unvalidatedRecords.length} 条未校验记录吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    this.loading = true
    
    try {
      // 分离订单3886和其他订单
      const skipRecords = unvalidatedRecords.filter(item => item.订单编号 == 3886)
      const normalRecords = unvalidatedRecords.filter(item => item.订单编号 != 3886)
      console.log(111,normalRecords)
      let totalSuccess = 0
      let totalFail = 0
      const messages = []
      
      // ========== 1. 处理订单3886的记录（只更新数据库，不上传SAP） ==========
      if (skipRecords.length > 0) {
        const skipAIDList = skipRecords.map(item => item.AID).join(',')
        var skipParam = [
          ['AID列表', skipAIDList],
          ['操作人', this.getCurrentUser()],
          ['最后编辑人', this.getCurrentUser()]
        ]
        var skipData = this.CreateData('11', '工时校验_批量保存校验记录', skipParam)
        await this.ExecDatabase(skipData)
        messages.push(`订单3886: ${skipRecords.length}条直接校验`)
        totalSuccess += skipRecords.length
      }
      // 2. 使用存储过程处理其他订单
      // 修改 batchValidate 中的处理逻辑
if (normalRecords.length > 0) {
  const aidArray = normalRecords.map(item => item.AID)
  const spResult = await this.callBatchValidateSP(aidArray)
  
  if (!spResult.success) {
    totalFail += normalRecords.length
    this.$message.error(`存储过程调用失败: ${spResult.error}`)
  } else {
    console.log('spResult:', spResult)
    
    // ========== 获取 Details 数组 ==========
    const details = spResult.resultDetails?.Details || []
    
    console.log('Details 数组:', details)
    console.log('Details 长度:', details.length)
    
    // 筛选成功和失败的记录
    const successDetails = details.filter(d => d.Success === true)
    const failDetails = details.filter(d => !d.Success)
    
    console.log('成功记录:', successDetails)
    console.log('失败记录:', failDetails)
    
    // 记录存储过程层面的失败
    if (failDetails.length > 0) {
      totalFail += failDetails.length
      const failMessages = failDetails.map(d => `AID ${d.AID}: ${d.Message}`).join('; ')
      this.$message.warning(`存储过程计算失败: ${failMessages}`)
    }
    
    // ========== 逐条上传SAP ==========
    let uploadSuccessCount = 0
    let uploadFailCount = 0
    
    for (const detail of successDetails) {
      const record = normalRecords.find(r => r.AID === detail.AID)
      if (!record) continue
      
      try {
        // 1. 上传SAP（传入 detail 中的 UploadMinutes）
        const uploadResult = await this.uploadToSAP(record, detail)
        
        // 2. 只有上传成功才标记为已校验
        if (uploadResult.success) {
          this.currentTask = record
          console.log(record)
          await this.saveValidationRecord(record)
          uploadSuccessCount++
          console.log(`AID ${record.AID} 上传SAP成功，已标记为已校验`)
        } else {
          uploadFailCount++
          // 不标记为已校验，错误信息已在 uploadToSAP 中通过 $message 显示
          console.error(`AID ${record.AID} 上传SAP失败，未标记为已校验`)
        }
      } catch (error) {
        uploadFailCount++
        console.error(`AID ${record.AID} 上传SAP异常:`, error)
      }
      
      await new Promise(resolve => setTimeout(resolve, 300))
    }
    
    totalSuccess += uploadSuccessCount
    totalFail += uploadFailCount
    messages.push(`SAP上传: 成功${uploadSuccessCount}条, 失败${uploadFailCount}条`)
    
    // 显示比例系数信息（可选）
    const ratioGroups = spResult.resultDetails?.RatioGroups || []
    if (ratioGroups.length > 0) {
      console.log('比例系数信息:', ratioGroups)
    }
  }
}
      
      
      // ========== 3. 汇总结果 ==========
      if (totalFail === 0 && totalSuccess>0) {
        this.$message.success(`批量校验完成！成功: ${totalSuccess}条`)
      } else {
        this.$message.info(`批量校验完成！成功: ${totalSuccess}条, 失败: ${totalFail}条`)
      }
      
      // 刷新表格
      this.searchTable()
      this.multipleSelection = []
      
    } catch (error) {
      console.error('批量校验失败:', error)
      this.$message.error('批量校验失败：' + error.message)
    } finally {
      this.loading = false
    }
  })
},


    // // ============ 新增工时记录 ============
    // addWorkTimeRecord() {
    //   this.addRecordForm = {
    //     操作类别: '',
    //     订单编号: '',
    //     产品编码: '',
    //     产品名称: '',
    //     工序名称: '',
    //     工位名称: '',
    //     操作人: '',
    //     操作数值: '',
    //     开始时间: '',
    //     结束时间: '',
    //     操作内容: '',
    //     操作描述: '',
    //     工位ID: '',
    //     工序ID: ''
    //   }
    //   this.processList = []
    //   this.addRecordDialogVisible = true
    //   this.$nextTick(() => {
    //     this.$refs.addRecordForm.clearValidate()
    //   })
    // },
    
    // // 提交新增记录
    // 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 param = [
    //         ['操作类别', this.addRecordForm.操作类别],
    //         ['订单编号', this.addRecordForm.订单编号],
    //         ['物料编号', this.addRecordForm.产品编码],
    //         ['物料描述', this.addRecordForm.产品名称],
    //         ['工序名称', this.addRecordForm.工序名称],
    //         ['工位名称', this.addRecordForm.工位名称],
    //         ['操作人', this.addRecordForm.操作人],
    //         ['开始时间', this.addRecordForm.开始时间],
    //         ['结束时间', this.addRecordForm.结束时间],
    //         ['操作内容', this.addRecordForm.操作内容],
    //         ['操作描述', this.addRecordForm.操作描述],
    //         ['TaskAID', this.addRecordForm.工序ID]
    //       ]
          
    //       var Data = this.CreateData('11', '工时校验_新增操作记录', param)
    //       this.ExecDatabase(Data).then(response => {
    //         this.$message.success('新增成功')
    //         this.addRecordDialogVisible = false
    //         this.searchTable()
    //       }).catch(error => {
    //         this.$message.error('新增失败：' + error.message)
    //       }).finally(() => {
    //         this.addRecordLoading = false
    //       })
    //     }
    //   })
    // }
  }
}
</script>

<style scoped>
.search-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.show-text {
  white-space: nowrap;
}

.custom-tabs {
  margin-top: 10px;
}

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

::v-deep .row-without-endtime {
  background-color: #f56c6c !important;
  color: #000000 !important;
}
/* 新增样式：工时超过33000秒的行 */
::v-deep .row-time-exceed {
  background-color: #f56c6c !important;
  color: #ffffff !important;
}

/* 新增样式：结束时间小于昨天的行 */
::v-deep .row-time-old {
  background-color: #deac50 !important;
  color: #000000 !important;
}

/* 可选：添加悬停效果，让颜色更美观 */
/* ::v-deep .el-table__body tr.row-time-exceed:hover > td {
  background-color: #cc0000 !important;
}

::v-deep .el-table__body tr.row-time-old:hover > td {
  background-color: #ff8c00 !important;
}*/
</style>