<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="!!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.总时长 || 0) / 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> -->
            </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>
      
      <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
      },
      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: '',
    }
  },
  
  mounted() {
    this.searchTable()
    this.loadOrderList('') 
    this.loadPersonnelList()
    this.getCheckerList();
  },
  
  methods: {
    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}获取失败`)
        return null
      } catch (error) {
        this.$message.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 exists = updatedStages.some(item => 
          item.Name === element.工序名称 && 
          item.StageID === stageId
        )
        
        if (!exists) {
          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
      }
      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 {
        // await this.submitMaterialRequisition(this.editForm)
        await this.updateValidationStatus(this.editForm)
        this.$message.success('校验成功')
        this.editDialogVisible = false
        this.searchTable()
      } catch (error) {
        this.$message.error('校验失败：' + error.message)
      } finally {
        this.editSubmitLoading = false
      }
    },
    
    // ============ 工时校验主函数 ============
    // async submitMaterialRequisition(data) {
    //   try {
    //     this.getCurrentTime()
    //     console.log('开始提交工时校验，数据:', data)
        
    //     // 1. 获取工序数据和订单数据（并行）
    //     const [processData, orderResult] = await Promise.all([
    //       this.getProcessDataAsync(data.订单编号),
    //       getB1("/ProductionOrders", {
    //         "$filter": `AbsoluteEntry eq ${data.订单编号}`
    //       })
    //     ])
        
    //     if (!orderResult.data.value || orderResult.data.value.length === 0) {
    //       throw new Error('未找到对应的生产订单')
    //     }
        
    //     const order = orderResult.data.value[0]
        
    //     // 2. 计算StageID偏移量
    //     const jia = this.calculateStageOffset(order.ProductionOrderLines)
        
    //     // 3. 找到当前工序
    //     const currentProcess = processData.find(item => 
    //       item.工序名称 === data.工序名称
    //     )
        
    //     if (!currentProcess) {
    //       throw new Error(`未找到工序: ${data.工序名称}`)
    //     }
        
    //     const currentStageId = currentProcess.工艺顺序 + jia
    //     console.log('当前工序StageID:', currentStageId)
        
    //     // 4. 准备要添加的资源（仅当前工序）
    //     const resourcesToAdd = await this.prepareResourcesToAdd(data, currentProcess, currentStageId)
        
    //     // 5. 更新SAP：添加工序和资源
    //     await this.updateSapWithAllStagesAndResources(data.订单编号, order, processData, jia, resourcesToAdd)
        
    //     // 6. 创建工时单据（仅当前工序）
    //     // await this.createTimeSheet(data, order, currentStageId)
    //     let updatedOrder = order
    //     if (hasUpdated) {
    //       // 等待一下让SAP更新完成
    //       await new Promise(resolve => setTimeout(resolve, 500))
          
    //       const reorderResult = await getB1("/ProductionOrders", {
    //         "$filter": `AbsoluteEntry eq ${data.订单编号}`
    //       })
          
    //       if (reorderResult.data.value && reorderResult.data.value.length > 0) {
    //         updatedOrder = reorderResult.data.value[0]
    //         console.log('重新获取订单数据成功')
    //       }
    //     }
        
    //     // 7. 更新数据库校验状态
    //     await this.updateValidationStatus(data)
        
    //   } catch (error) {
    //     console.error('提交工时校验失败:', error)
    //     throw error
    //   }
    // },
    
    // 准备要添加的资源（仅当前工序）
    async prepareResourcesToAdd(data, currentProcess, stageId) {
  const resources = []
  console.log(data)
  
  // 获取正常设备资源
  const equipmentResource = await this.getResourceVisCode(currentProcess.工位名称)
  if (equipmentResource) {
    resources.push({
      type: 'equipment',
      itemName: currentProcess.工位名称,
      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 = `辅助-${currentProcess.工位名称}`
    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.操作类别 && data.操作类别.includes('加班') & data.操作内容==='辅助结束'){
  //   const AssistaddworkName = `辅助-加班-${data.操作人}`
  //   const Assistaddwork = await this.getResourceVisCode(AssistaddworkName)  // 修正这里
  //   if (Assistaddwork) {
  //     resources.push({
  //       type: 'personnel',
  //       itemName: AssistaddworkName,
  //       itemNo: Assistaddwork.visCode,
  //       stageId: stageId,
  //       isAssistant: true
  //     })
  //   }
  // }
  
  console.log('准备添加的资源:', resources)
  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, // 当前工序的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
          })
          
          if(!aaa.success){
            this.$message.error(`工时ID${record.AID} , ${aaa.message}`)
            return false
          }else{
            if (stagesResult.hasNewStage) {
              message += '添加工序成功'
            }
            if (resourcesResult.hasNewResource) {
              message += (message ? '，' : '') + '添加资源成功'
            }
            let message = ''
            
            return true // 表示已更新
          }
        } else {
          console.log('没有新的工序或资源需要添加')
          return false // 表示未更新
        }
        
      } catch (error) {
        console.error('更新SAP失败:', error)
        throw new Error('更新SAP工序和资源失败: ' + error.message)
      }
    },
    
    // 创建工时单据（仅当前工序）
    // async createTimeSheet(data, order, stageId) {
    //   const params = []
      
    //   // 计算工时（小时）
    //   let workHours = 0
    //   if (data.加工工时 > 0) {
    //     workHours = Number(data.加工工时) / 3600
    //   } else if (data.总时长 > 0) {
    //     workHours = Number(data.总时长) / 3600
    //   }
      
    //   if (workHours <= 0) {
    //     console.warn('工时小于等于0，不创建工时单据')
    //     return
    //   }
    //   console.log(data.操作类别,data.加工工时,data.总时长 )
    //   // 根据操作类型确定要创建哪些工时单据
    //   if (data.操作类别 === '报工') {
    //     if (data.加工工时 > 0 && data.总时长 > 0) {
    //       // 机加报工设备：设备和人员都有工时
    //       await this.addEquipmentTimeSheet(data, order, stageId, workHours, params, false)
    //       await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, false)
    //     } else if (data.加工工时 === 0 && data.总时长 > 0) {
    //       // 机加报工人员：只有人员工时
    //       await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, false)
    //     }
    //   } else if (data.操作类别 === '辅助结束') {
    //     if (data.加工工时 > 0 && data.总时长 > 0) {
    //       // 机加辅助设备：辅助设备和辅助人员都有工时
    //       await this.addEquipmentTimeSheet(data, order, stageId, workHours, params, true)
    //       await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, true)
    //     } else if (data.加工工时 === 0 && data.总时长 > 0) {
    //       // 机加辅助人员：只有辅助人员工时
    //       await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, true)
    //     }
    //   }
    //   console.log(params)
    //   // 创建工时单据
    //   if (params.length > 0) {
    //     console.log('创建工时单据，参数:', params)
        
    //     const result = await postB1("/InventoryGenExits", {
    //       "DocDate": this.currentdate,
    //       "DocDueDate": this.currentdate,
    //       "Comments": '',
    //       "DocumentLines": params
    //     })
        
    //     if (result.success) {
    //       this.$message.success(`创建了${params.length}个工时记录`)
    //     } else {
    //       throw new Error('创建工时单据失败')
    //     }
    //   } else {
    //     console.warn('没有需要创建的工时单据')
    //   }
    // },
  // async createTimeSheet(data, order, stageId) {
  //     const params = []
      
  //     // 计算工时（分钟）
  //     let workHours = 0
  //     if (data.加工工时 > 0) {
  //       workHours = Number(data.加工工时) / 60
  //     } else if (data.总时长 > 0) {
  //       workHours = Number(data.总时长) / 60
  //     }
      
  //     if (workHours <= 0) {
  //       console.warn('工时小于等于0，不创建工时单据')
  //       return
  //     }
      
  //     console.log(data.操作类别, data.加工工时, data.总时长)
      
  //     // 根据操作类型确定要创建哪些工时单据
  //     if (data.操作类别 === '报工') {
  //       if (data.加工工时 || 0 > 0 && data.总时长 > 0) {
  //         // 机加报工设备：设备和人员都有工时
  //         await this.addEquipmentTimeSheet(data, order, stageId, workHours, params, false)
  //         //await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, false)
  //       } else if (data.加工工时 || 0  === 0 && data.总时长 > 0) {
  //         // 机加报工人员：只有人员工时
  //         await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, false)
  //       }
  //     } else if (data.操作类别 === '辅助结束') {
  //       if (data.加工工时 || 0  > 0 && data.总时长 > 0) {
  //         // 机加辅助设备：辅助设备和辅助人员都有工时
  //         await this.addEquipmentTimeSheet(data, order, stageId, workHours, params, true)
  //         // await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, true)
  //       } else if (data.加工工时 || 0  === 0 && data.总时长 > 0) {
  //         // 机加辅助人员：只有辅助人员工时
  //         await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, true)
  //       }
  //     }else if (data.操作类别 === '加班') {
  //       if  (data.加工工时 || 0  === 0 && data.总时长 > 0) {
  //         // 机加辅助人员：只有辅助人员工时
  //         await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, true)
  //       }
  //     }
      
  //     console.log('准备创建的工时单据参数:', params)
      
  //     // 创建工时单据
  //     if (params.length > 0) {
  //       console.log('创建工时单据，参数:', params)
        
  //       try {
  //         const result = await postB1("/InventoryGenExits", {
  //           "DocDate": this.currentdate,
  //           "DocDueDate": this.currentdate,
  //           "Comments": '',
  //           "DocumentLines": params
  //         })
  //         console.log(result)
  //         if (result.success) {
  //           this.$message.success(`创建了${params.length}个工时记录`)
  //           console.log('工时单据创建成功')
  //         } else {
  //           console.error('工时单据创建失败:', result)
  //           throw new Error('创建工时单据失败: ' + JSON.stringify(result))
  //         }
  //       } catch (error) {
  //         console.error('调用工时单据API失败:', error)
  //         throw error
  //       }
  //     } else {
  //       console.warn('没有需要创建的工时单据，可能原因：')
  //       console.warn('- 工时计算为0')
  //       console.warn('- 未找到对应的资源行')
  //       console.warn('- 操作类型不匹配')
  //     }
  // },
      // 添加设备工时单据
    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) {
        console.warn(`未找到设备资源: ${equipmentName}`)
        return
      }
      console.log(333,equipmentResource)
      const equipmentLine = order.ProductionOrderLines.find(item =>
        item.ItemType === 'pit_Resource' &&
        item.ItemNo === equipmentResource.visCode &&
        item.StageID === stageId
      )
      console.log(444,equipmentLine)
      if (equipmentLine && equipmentLine.LineNumber) {
        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}分钟`)
      }
    },
    // 添加人员工时单据
    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) {
        console.warn(`未找到人员资源: ${personnelName}`)
        return
      }
      
      const personnelLine = order.ProductionOrderLines.find(item =>
        item.ItemType === 'pit_Resource' &&
        item.ItemNo === personnelResource.visCode &&
        item.StageID === stageId
      )
      
      if (personnelLine && personnelLine.LineNumber) {
        // 根据班次标准工时调整工时
        let actualWorkHours = workHours
        const minStandardHours = data.当日班次最小标准工时
        
        // 如果班次最小标准工时不为0且不为8，则按比例调整工时
        if (minStandardHours !== undefined && minStandardHours !== null && minStandardHours !== 0 && minStandardHours !== 8) {
          actualWorkHours = workHours * (minStandardHours / 8)
          console.log(`工时调整: 原工时=${workHours}分钟, 班次标准工时=${minStandardHours}小时, 调整后工时=${actualWorkHours}分钟`)
        }
        
        params.push({
          "Quantity": actualWorkHours,
          "BaseType": 202,
          "BaseEntry": Number(data.订单编号),
          "BaseLine": personnelLine.LineNumber,
          "LineType": "dlt_Resource",
          "WarehouseCode": '',
          "U_ResName": data.操作人
        })
        console.log(`添加人员工时单据: ${personnelName}, LineNumber: ${personnelLine.LineNumber}, 工时: ${actualWorkHours}分钟`)
      }
    },
    // async addPersonnelTimeSheet2(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) {
    //     console.warn(`未找到人员资源: ${personnelName}`)
    //     return
    //   }
      
    //   const personnelLine = order.ProductionOrderLines.find(item =>
    //     item.ItemType === 'pit_Resource' &&
    //     item.ItemNo === personnelResource.visCode &&
    //     item.StageID === stageId
    //   )
      
    //   if (personnelLine && personnelLine.LineNumber) {
    //     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}分钟`)
    //   }
    // },
    async addPersonnelTimeSheet3(data, order, stageId, workHours, params, isAssistant) {
      const personnelName = data.操作人
      
      console.log(`查找人员资源: ${personnelName}, StageID: ${stageId}`)
      
      const personnelResource = await this.getResourceVisCode(personnelName)
      if (!personnelResource) {
        console.warn(`未找到人员资源: ${personnelName}`)
        return
      }
      
      const personnelLine = order.ProductionOrderLines.find(item =>
        item.ItemType === 'pit_Resource' &&
        item.ItemNo === personnelResource.visCode &&
        item.StageID === stageId
      )
      
      if (personnelLine && personnelLine.LineNumber) {
        // 根据班次标准工时调整工时
        let actualWorkHours = workHours
        const minStandardHours = data.当日班次最小标准工时
        
        // 如果班次最小标准工时不为0且不为8，则按比例调整工时
        if (minStandardHours !== undefined && minStandardHours !== null && minStandardHours !== 0 && minStandardHours !== 8) {
          actualWorkHours = workHours * (minStandardHours / 8)
          console.log(`工时调整: 原工时=${workHours}分钟, 班次标准工时=${minStandardHours}小时, 调整后工时=${actualWorkHours}分钟`)
        }
        
        params.push({
          "Quantity": actualWorkHours,
          "BaseType": 202,
          "BaseEntry": Number(data.订单编号),
          "BaseLine": personnelLine.LineNumber,
          "LineType": "dlt_Resource",
          "WarehouseCode": '',
          "U_ResName": data.操作人
        })
        console.log(`添加人员工时单据: ${personnelName}, LineNumber: ${personnelLine.LineNumber}, 工时: ${actualWorkHours}分钟`)
      }
    },
    // 更新数据库校验状态
    async updateValidationStatus(data) {
      // var param = [
      //   ['orderAID', data.AID || this.currentTask.AID],

      //   ['操作人', this.getCurrentUser()],
      //   ['最后编辑人', this.getCurrentUser()]
      // ]
      var 加工工时 = this.editForm.加工工时
      var 总时长 = this.editForm.总时长
      var 工时 = 0
      if(加工工时 == 0){
          工时 = 总时长
      }else{
          工时 = 加工工时
      }
      console.log(加工工时,总时长)
      var param = [
        ['orderAID', this.currentTask.AID],
        ['开始时间', this.editForm.开始时间],
        ['结束时间', this.editForm.结束时间],
        ['加工工时', 加工工时],
        ['总时长', 总时长],
        ['操作人', this.getCurrentUser()],
        ['最后编辑人', this.getCurrentUser()]
      ];
      var Data = this.CreateData('11', '工时校验_保存校验记录', param)
      await this.ExecDatabase(Data)
    },
    
    // ============ 批量校验 ============
    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)
          
          // 处理订单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)
            this.$message.info(`订单3886的记录（${skipRecords.length}条）已直接校验，未上传SAP`)
          }
          
          // 处理其他订单的记录（正常上传SAP）
          if (normalRecords.length > 0) {
            await this.batchsap(normalRecords)
          }
          
          // 刷新表格
          this.searchTable()
          this.multipleSelection = []
          
          // if (skipRecords.length > 0 && normalRecords.length === 0) {
          //   this.$message.success(`成功校验 ${skipRecords.length} 条记录（订单3886，未上传SAP）`)
          // }
        } catch (error) {
          this.$message.error('批量校验失败：' + error.message)
        } finally {
          this.loading = false
        }
      })
    },
    
    // 批量处理工时校验
async batchsap(batchdata) {
  this.getCurrentTime()
  let successCount = 0
  let failCount = 0
  let successAIDs = []
  // 按操作人分组处理
  const operatorGroups = {}
  
  // 1. 先将数据按操作人分组
  batchdata.forEach(item => {
    const operator = item.操作人
    if (!operatorGroups[operator]) {
      operatorGroups[operator] = []
    }
    operatorGroups[operator].push(item)
  })
  
  // 2. 按操作人分别处理
  // for (const operator in operatorGroups) {
  //   const operatorRecords = operatorGroups[operator]
    
  //   try {
  //     console.log(`处理操作人 ${operator} 的 ${operatorRecords.length} 条记录`)

  //     // 按日期分组（同一天的数据一起处理更高效）
  //     const recordsByDate = {}
      
  //     operatorRecords.forEach(record => {
  //       const recordDate = record.开始时间 ? record.开始时间.split(' ')[0] : this.currentdate
  //       if (!recordsByDate[recordDate]) {
  //         recordsByDate[recordDate] = []
  //       }
  //       recordsByDate[recordDate].push(record)
  //     })
      
  //     console.log(`操作人 ${operator} 的记录分布在 ${Object.keys(recordsByDate).length} 个日期`)

  //     // 获取选中记录中最早的开始时间和最晚的结束时间所在的日期
  //     // 假设所有记录都是同一天的
  //     const firstRecord = operatorRecords[0]
  //     const recordDate = firstRecord.开始时间 ? firstRecord.开始时间.split(' ')[0] : this.currentdate
      
  //     // ===== 新增：查询该操作人当天的所有报工记录 =====
  //     const todayStart = `${recordDate} 00:00:00`
  //     const todayEnd = `${recordDate} 23:59:59`
      
  //     var queryParam = [
  //       ['操作人', operator],
  //       ['开始时间', todayStart],
  //       ['结束时间', todayEnd],
        
  //     ]
  //     var queryData = this.CreateData('11', '工时校验_获取操作人当天报工记录', queryParam)
  //     const response = await this.ExecDatabase(queryData)
      
  //     // 计算该操作人当天的所有报工总时间（秒）
  //     let todayTotalSeconds = 0
  //     if (response.data && response.data.length > 0) {
  //       response.data.forEach(record => {
  //         // 使用总时长或加工工时
  //         todayTotalSeconds += (record.总时长)
  //       })
  //     }
      
  //     // 加上选中记录中的报工时间（因为查询可能不包括未保存的记录？）
  //     // 但通常数据库已经包含了这些记录，所以不需要重复添加
      
  //     console.log(`操作人 ${operator} 当天所有报工总时间: ${todayTotalSeconds}秒 = ${todayTotalSeconds/60}分钟`)
  //     // ============================================
      
  //     // 3. 找出该操作人的所有记录，按TaskAID分类
  //     const recordsByTask = {}
  //     const abnormalRecords = [] // 异常记录
  //     const normalRecords = [] // 正常记录（报工、辅助结束、加班）
      
  //     operatorRecords.forEach(record => {
  //       if (record.操作类别 === '异常') {
  //         abnormalRecords.push(record)
  //       } else {
  //         normalRecords.push(record)
  //         if (record.TaskAID) {
  //           if (!recordsByTask[record.TaskAID]) {
  //             recordsByTask[record.TaskAID] = []
  //           }
  //           recordsByTask[record.TaskAID].push(record)
  //         }
  //       }
  //     })
      
  //     // 4. 计算每个TaskAID的异常总时间
  //     const abnormalTimeByTask = {}
  //     abnormalRecords.forEach(abnormal => {
  //       if (abnormal.TaskAID) {
  //         const abnormalMinutes = (abnormal.总时长 || 0) / 60 // 秒转分钟
  //         abnormalTimeByTask[abnormal.TaskAID] = (abnormalTimeByTask[abnormal.TaskAID] || 0) + abnormalMinutes
  //       }
  //     })
      
  //     console.log('异常时间按TaskAID:', abnormalTimeByTask)
      
  //     // 5. 计算实际总时间（从勾选记录中扣除异常）- 用于调整每个记录的值
  //     // 注意：这个totalActualMinutes只用于计算比例系数在记录间的分配
  //     // 实际比例系数应该用当天所有报工总时间
  //     let totalSelectedActualMinutes = 0
  //     const processedRecords = []
      
  //     normalRecords.forEach(record => {
  //       // 先打印原始值
  //       console.log('原始记录值:', {
  //         操作类别: record.操作类别,
  //         总时长: record.总时长,
  //         加工工时: record.加工工时,
  //         类型: typeof record.总时长,
  //         绑定设备数: record.绑定设备数
  //       })
        
  //       // 跳过加班记录，不参与比例计算
  //       if (record.操作类别 && record.操作类别.includes('加班')) {
  //         // 直接计算 recordMinutes
  //         const recordMinutes = (record.总时长 ) / 60
  //         console.log('直接计算 recordMinutes=', recordMinutes)
          
  //         const newRecord = {
  //           ...record,
  //           originalMinutes: recordMinutes,
  //           actualMinutes: recordMinutes,
  //           recordMinutes: recordMinutes
  //         }
  //         console.log('新记录对象 originalMinutes=', newRecord.originalMinutes)
  //         processedRecords.push(newRecord)
  //         return
  //       }
        
  //       // 报工和辅助结束参与比例计算
  //       const recordMinutes = (record.总时长 ) / 60
  //       let actualMinutes = recordMinutes
        
  //       // 如果是报工，扣除对应TaskAID的异常时间
  //       if (record.操作类别 === '报工' && record.TaskAID) {
  //         const abnormalMinutes = abnormalTimeByTask[record.TaskAID] || 0
  //         actualMinutes = Math.max(0, recordMinutes - abnormalMinutes)
  //         console.log(`报工记录 ${record.TaskAID}: 原${recordMinutes}分钟 - 异常${abnormalMinutes}分钟 = 实际${actualMinutes}分钟`)
  //       } else {
  //         console.log(`${record.操作类别}记录: ${recordMinutes}分钟`)
  //       }
        
  //       totalSelectedActualMinutes += actualMinutes
  //       processedRecords.push({
  //         ...record,
  //         actualMinutes: actualMinutes,
  //         originalMinutes: recordMinutes
  //       })
  //     })
      
  //     console.log(`操作人 ${operator} 的勾选记录实际总时间: ${totalSelectedActualMinutes}分钟`)
      
  //     // 6. 计算比例系数 - 使用当天所有报工总时间
  //     let ratio = 1
  //     const todayTotalMinutes = todayTotalSeconds / 60
  //     if (todayTotalMinutes > 0) {
  //       ratio = (8 * 60) / todayTotalMinutes
  //       console.log(`比例系数: 480 / ${todayTotalMinutes} = ${ratio}`)
  //     } else {
  //       console.log(`当天报工总时间为0，使用比例系数1`)
  //     }
  //     // 7. 处理每条记录（创建工时单据）
  //     for (const record of processedRecords) {
  //       try {
  //         console.log(`开始处理记录: ${record.操作类别}, originalMinutes=${record.originalMinutes}`) // 添加日志
          
  //         if (record.订单编号 == 3886) {
  //           console.log(`订单号 ${record.订单编号} 为3886，跳过SAP上传，直接更新数据库状态`)
  //           successAIDs.push(record.AID)
  //           successCount++
  //           continue  // 直接跳过，不执行后续的SAP相关代码
  //         }
  //         // 获取工序数据和订单数据
  //         const [processData, orderResult] = await Promise.all([
  //           this.getProcessDataAsync(record.订单编号),
  //           getB1("/ProductionOrders", {
  //             "$filter": `AbsoluteEntry eq ${record.订单编号}`
  //           })
  //         ])
  //         console.log(orderResult.data.value.length)
  //         if (orderResult.data.value.length === 0) {
  //           this.$message.error(`未找到订单 ${record.订单编号}，批量校验终止`)
  //           throw new Error(`未找到订单 ${record.订单编号}，批量校验终止`)
  //         }
          
  //         const order = orderResult.data.value[0]
          
  //         // 计算StageID偏移量
  //         const jia = this.calculateStageOffset(order.ProductionOrderLines)
          
  //         // 找到当前工序
  //         const currentProcess = processData.find(item => 
  //           item.工序名称 === record.工序名称
  //         )
          
  //         if (!currentProcess) {
  //           this.$message.error(`订单 ${record.订单编号} 未找到工序 ${record.工序名称}`)
  //           console.warn(`订单 ${record.订单编号} 未找到工序 ${record.工序名称}，跳过`)
  //           failCount++
  //           continue
  //         }
          
  //         const currentStageId = currentProcess.工艺顺序 + jia
          
  //         // 准备要添加的资源
  //         let resourcesToAdd = []
          
  //         if (record.操作类别 === '报工') {
  //           // 报工：设备 + 人员
  //           const equipmentResource = await this.getResourceVisCode(record.工位名称)
  //           console.log('111'+equipmentResource)
  //           if (equipmentResource) {
  //             resourcesToAdd.push({
  //               type: 'equipment',
  //               itemName: record.工位名称,
  //               itemNo: equipmentResource.visCode,
  //               stageId: currentStageId,
  //               isAssistant: false
  //             })
  //           }
            
  //           const personnelResource = await this.getResourceVisCode(record.操作人)
  //           if (personnelResource) {
  //             resourcesToAdd.push({
  //               type: 'personnel',
  //               itemName: record.操作人,
  //               itemNo: personnelResource.visCode,
  //               stageId: currentStageId,
  //               isAssistant: false
  //             })
  //           }
  //         } else if (record.操作类别 === '辅助结束') {
  //           // 辅助结束：辅助设备 + 辅助人员
  //           const assistantEquipmentName = `辅助-${record.工位名称}`
  //           const assistantEquipment = await this.getResourceVisCode(assistantEquipmentName)
  //           if (assistantEquipment) {
  //             resourcesToAdd.push({
  //               type: 'equipment',
  //               itemName: assistantEquipmentName,
  //               itemNo: assistantEquipment.visCode,
  //               stageId: currentStageId,
  //               isAssistant: true
  //             })
  //           }
            
  //           const assistantPersonnelName = `辅助-${record.操作人}`
  //           const assistantPersonnel = await this.getResourceVisCode(assistantPersonnelName)
  //           if (assistantPersonnel) {
  //             resourcesToAdd.push({
  //               type: 'personnel',
  //               itemName: assistantPersonnelName,
  //               itemNo: assistantPersonnel.visCode,
  //               stageId: currentStageId,
  //               isAssistant: true
  //             })
  //           }
  //         } 
  //         // else if (record.操作类别 && record.操作类别.includes('加班') &  record.操作内容 === '辅助结束') {
  //         //   // 加班：只有人员
  //         //   const currentProcess = processData.find(item => 
  //         //     item.工序名称 === record.工序名称
  //         //   )
            
  //         //   if (currentProcess) {
  //         //     // 调用 prepareResourcesToAdd 方法来添加加班资源
  //         //     const resourcesFromMethod = await this.prepareResourcesToAdd(record, currentProcess, currentStageId)
  //         //     resourcesToAdd = [...resourcesFromMethod]
  //         //     console.log('通过 prepareResourcesToAdd 添加的加班资源:', resourcesFromMethod)
  //         //   } else {
  //         //     // 原来的方法作为备用
  //         //     const overtimePersonnelName = `辅助-加班-${record.操作人}`
  //         //     const overtimePersonnel = await this.getResourceVisCode(overtimePersonnelName)
  //         //     if (overtimePersonnel) {
  //         //       resourcesToAdd.push({
  //         //         type: 'personnel',
  //         //         itemName: overtimePersonnelName,
  //         //         itemNo: overtimePersonnel.visCode,
  //         //         stageId: currentStageId,
  //         //         isAssistant: true
  //         //       })
  //         //     }
  //         //   }
  //         // }
  //         else if (record.操作类别 && record.操作类别.includes('加班') ) {
  //           // 加班：只有人员
  //           const currentProcess = processData.find(item => 
  //             item.工序名称 === record.工序名称
  //           )
            
  //           if (currentProcess) {
  //             // 调用 prepareResourcesToAdd 方法来添加加班资源
  //             const resourcesFromMethod = await this.prepareResourcesToAdd(record, currentProcess, currentStageId)
  //             resourcesToAdd = [...resourcesFromMethod]
  //             console.log('通过 prepareResourcesToAdd 添加的加班资源:', resourcesFromMethod)
  //           } else {
  //             // 原来的方法作为备用
  //             const overtimePersonnelName = `加班-${record.操作人}`
  //             const overtimePersonnel = await this.getResourceVisCode(overtimePersonnelName)
  //             if (overtimePersonnel) {
  //               resourcesToAdd.push({
  //                 type: 'personnel',
  //                 itemName: overtimePersonnelName,
  //                 itemNo: overtimePersonnel.visCode,
  //                 stageId: currentStageId,
  //                 isAssistant: true
  //               })
  //             }
  //           }
  //         }else if (record.操作类别 === '开始加工') {

  //           const assistantPersonnelName = `${record.操作人}`
  //           const assistantPersonnel = await this.getResourceVisCode(assistantPersonnelName)
  //           if (assistantPersonnel) {
  //             resourcesToAdd.push({
  //               type: 'personnel',
  //               itemName: assistantPersonnelName,
  //               itemNo: assistantPersonnel.visCode,
  //               stageId: currentStageId,
  //               isAssistant: true
  //             })
  //           }
  //         }
          
  //         // 更新SAP：添加工序和资源
  //         const hasUpdated = await this.updateSapWithAllStagesAndResources(
  //           record.订单编号, 
  //           order, 
  //           processData, 
  //           jia, 
  //           resourcesToAdd,
  //           record
  //         )
          
  //         // 重新获取订单数据（如果更新了SAP）
  //         let updatedOrder = order
  //         if (hasUpdated) {
  //           await new Promise(resolve => setTimeout(resolve, 500))
  //           const reorderResult = await getB1("/ProductionOrders", {
  //             "$filter": `AbsoluteEntry eq ${record.订单编号}`
  //           })
  //           if (reorderResult.data.value && reorderResult.data.value.length > 0) {
  //             updatedOrder = reorderResult.data.value[0]
  //           }
  //         }
          
  //         // 计算要上传的工时
  //         let uploadMinutes = 0
          
  //         if (record.操作类别 && record.操作类别.includes('加班')) {
  //           // 加班直接用原工时
  //           uploadMinutes = record.originalMinutes
  //           console.log(`加班记录: 原工时 ${uploadMinutes}分钟`)
  //         } else {
  //           // 报工和辅助结束按比例调整
  //           uploadMinutes = (record.actualMinutes || 0) * ratio
  //           console.log(`${record.操作类别}记录: 实际${record.actualMinutes}分钟 × 比例${ratio} = ${uploadMinutes}分钟`)
  //         }
          
  //         if (uploadMinutes <= 0) {
  //           this.$message.error("工时小于等于0,请修改")
  //           continue
  //         }
          
  //         // 创建工时单据
  //         const params = []
  //         const TaskAIDparams = []
  //         // if (record.操作类别 === '报工') {
  //         //   // 报工：设备和人员都有工时
  //         //   await this.addEquipmentTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, false)
  //         //   await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, false)
  //         // } else if (record.操作类别 === '辅助结束') {
  //         //   // 辅助结束：辅助设备和辅助人员都有工时
  //         //   await this.addEquipmentTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
  //         //   await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
  //         // } else if (record.操作类别 === '加班') {
  //         //   // 加班：只有人员工时
  //         //   await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
  //         // }
  //         if (record.操作类别 === '报工') {
  //           if (record.加工工时 || 0 > 0 && record.总时长 > 0) {
  //             const equipmentHours = (record.加工工时/ 60 || 0) 
  //             // 机加报工设备：设备工时
  //             await this.addEquipmentTimeSheet(record, updatedOrder, currentStageId, equipmentHours, params, false)
  //             // await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, false)
  //             //await this.addPersonnelTimeSheet(data, order, stageId, workHours, params, false)
  //           } else if (record.加工工时 || 0  === 0 && record.总时长 > 0) {
  //             // 机加报工人员：只有人员工时
  //             await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, false)
  //           }
  //         } else if (record.操作类别 === '开始加工') {
  //           if (record.加工工时 || 0  >= 0 && record.总时长 > 0) {
  //             const equipmentHours = (record.加工工时/ 60 || 0) 
  //             await this.addPersonnelTimeSheet3(record, updatedOrder, currentStageId, uploadMinutes, params, true)
  //           } 
  //         }else if (record.操作类别 === '辅助结束') {
  //           if (record.加工工时 || 0  > 0 && record.总时长 > 0) {
  //             // 机加辅助设备：辅助设备和辅助人员都有工时
  //             const equipmentHours = (record.加工工时/ 60 || 0) 
  //             await this.addEquipmentTimeSheet(record, updatedOrder, currentStageId, equipmentHours, params, true)
  //             // await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
  //           } else if (record.加工工时 || 0  === 0 && record.总时长 > 0) {
  //             // 机加辅助人员：只有辅助人员工时
  //             await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
  //           }
  //         }else if (record.操作类别 && record.操作类别.includes('加班')  & record.操作内容 === '辅助结束') {
  //           if  (record.加工工时 || 0  === 0 && record.总时长 > 0) {
  //             // 机加辅助人员：只有辅助人员工时
  //             await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
  //           }
  //         }else if (record.操作类别 && record.操作类别.includes('加班')  & record.操作内容 != '辅助结束') {
  //           if  (record.加工工时 || 0  === 0 && record.总时长 > 0) {
  //             // 机加辅助人员：只有辅助人员工时
  //             await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
  //           }
  //         }
  //         // 提交工时单据
  //         if (params.length > 0) {
  //           const startDate = record.开始时间 ? record.开始时间.split(' ')[0] : this.currentdate;
  //           const result = await postB1("/InventoryGenExits", {
  //             "DocDate": startDate,
  //             "DocDueDate": startDate,
  //             "Comments": '',
  //             "DocumentLines": params
  //           })
            
  //           if (result.success) {
  //             console.log(`创建了${params.length}个工时记录`)
  //             successAIDs.push(record.AID)
  //           }else{
  //             this.$message.error('工时上传失败')
  //             return
  //           }
  //         }
          
  //         successCount++
  //         await new Promise(resolve => setTimeout(resolve, 300))
          
  //       } catch (error) {
  //         console.error(`处理记录失败:`, error)
  //         failCount++
  //       }
  //     }
      
  //     // 8. 处理异常记录（只更新数据库状态）
  //     if (abnormalRecords.length > 0) {
  //       const aidList = abnormalRecords.map(item => item.AID).join(',')
  //       var param = [
  //         ['AID列表', aidList],
  //         ['操作人', this.getCurrentUser()],
  //         ['最后编辑人', this.getCurrentUser()]
  //       ]
  //       var Data = this.CreateData('11', '工时校验_批量保存校验记录', param)
  //       await this.ExecDatabase(Data)
  //       console.log(`更新了${abnormalRecords.length}条异常记录的状态`)
  //     }
      
  //   } catch (error) {
  //     console.error(`处理操作人 ${operator} 失败:`, error)
  //     failCount += operatorRecords.length
  //   }
  // }
  // 2. 按操作人分别处理
  for (const operator in operatorGroups) {
    const operatorRecords = operatorGroups[operator]
    
    try {
      console.log(`处理操作人 ${operator} 的 ${operatorRecords.length} 条记录`)
      
      // 按日期分组（同一天的数据一起处理更高效）
      const recordsByDate = {}
      
      operatorRecords.forEach(record => {
        const recordDate = record.开始时间 ? record.开始时间.split(' ')[0] : this.currentdate
        if (!recordsByDate[recordDate]) {
          recordsByDate[recordDate] = []
        }
        recordsByDate[recordDate].push(record)
      })
      
      console.log(`操作人 ${operator} 的记录分布在 ${Object.keys(recordsByDate).length} 个日期`)
      
      // 按日期分别处理
      for (const recordDate in recordsByDate) {
        const dateRecords = recordsByDate[recordDate]
        
        console.log(`处理日期 ${recordDate} 的 ${dateRecords.length} 条记录`)
        
        // ===== 查询该操作人在该日期的所有报工记录 =====
        const todayStart = `${recordDate} 00:00:00`
        const todayEnd = `${recordDate} 23:59:59`
        
        var queryParam = [
          ['操作人', operator],
          ['开始时间', todayStart],
          ['结束时间', todayEnd],
        ]
        var queryData = this.CreateData('11', '工时校验_获取操作人当天报工记录', queryParam)
        const response = await this.ExecDatabase(queryData)
        
        // 计算该操作人在该日期的所有报工总时间（秒）
        let todayTotalSeconds = 0
        if (response.data && response.data.length > 0) {
          response.data.forEach(record => {
            todayTotalSeconds += (record.总时长 || 0)
          })
        }
        
        console.log(`操作人 ${operator} 在 ${recordDate} 的所有报工总时间: ${todayTotalSeconds}秒 = ${todayTotalSeconds/60}分钟`)
        
        // ===== 处理该日期的记录 =====
        
        // 找出该日期的所有记录，按TaskAID分类
        const recordsByTask = {}
        const abnormalRecords = [] // 异常记录
        const normalRecords = [] // 正常记录（报工、辅助结束、加班、开始加工）
        
        dateRecords.forEach(record => {
          if (record.操作类别 === '异常') {
            abnormalRecords.push(record)
          } else {
            normalRecords.push(record)
            if (record.TaskAID) {
              if (!recordsByTask[record.TaskAID]) {
                recordsByTask[record.TaskAID] = []
              }
              recordsByTask[record.TaskAID].push(record)
            }
          }
        })
        
        // 计算每个TaskAID的异常总时间
        const abnormalTimeByTask = {}
        abnormalRecords.forEach(abnormal => {
          if (abnormal.TaskAID) {
            const abnormalMinutes = (abnormal.总时长 || 0) / 60 // 秒转分钟
            abnormalTimeByTask[abnormal.TaskAID] = (abnormalTimeByTask[abnormal.TaskAID] || 0) + abnormalMinutes
          }
        })
        
        console.log(`日期 ${recordDate} 异常时间按TaskAID:`, abnormalTimeByTask)
        
        // 计算实际总时间（从勾选记录中扣除异常）
        let totalSelectedActualMinutes = 0
        const processedRecords = []
        
        normalRecords.forEach(record => {
          console.log('原始记录值:', {
            操作类别: record.操作类别,
            总时长: record.总时长,
            加工工时: record.加工工时,
            绑定设备数: record.绑定设备数
          })
          
          // 跳过加班记录，不参与比例计算
          if (record.操作类别 && record.操作类别.includes('加班')) {
            const recordMinutes = (record.总时长 || 0) / 60
            console.log('加班记录，直接使用原工时:', recordMinutes)
            
            processedRecords.push({
              ...record,
              originalMinutes: recordMinutes,
              actualMinutes: recordMinutes
            })
            return
          }
          
          // 报工和辅助结束参与比例计算
          const recordMinutes = (record.总时长 || 0) / 60
          let actualMinutes = recordMinutes
          
          // 如果是报工，扣除对应TaskAID的异常时间
          if (record.操作类别 === '报工' && record.TaskAID) {
            const abnormalMinutes = abnormalTimeByTask[record.TaskAID] || 0
            actualMinutes = Math.max(0, recordMinutes - abnormalMinutes)
            console.log(`报工记录 ${record.TaskAID}: 原${recordMinutes}分钟 - 异常${abnormalMinutes}分钟 = 实际${actualMinutes}分钟`)
          } else {
            console.log(`${record.操作类别}记录: ${recordMinutes}分钟`)
          }
          
          totalSelectedActualMinutes += actualMinutes
          processedRecords.push({
            ...record,
            actualMinutes: actualMinutes,
            originalMinutes: recordMinutes
          })
        })
        
        console.log(`日期 ${recordDate} 勾选记录实际总时间: ${totalSelectedActualMinutes}分钟`)
        
        // 计算该日期的比例系数
        let ratio = 1
        const todayTotalMinutes = todayTotalSeconds / 60
        if (todayTotalMinutes > 0) {
          ratio = (8 * 60) / todayTotalMinutes
          console.log(`日期 ${recordDate} 比例系数: 480 / ${todayTotalMinutes} = ${ratio}`)
        } else {
          console.log(`日期 ${recordDate} 报工总时间为0，使用比例系数1`)
        }
        
        // 处理该日期的每条记录（创建工时单据）
        for (const record of processedRecords) {
          try {
            console.log(`开始处理记录: 日期=${recordDate}, 类别=${record.操作类别}, 原始分钟=${record.originalMinutes}`)
            
            if (record.订单编号 == 3886) {
              console.log(`订单号 ${record.订单编号} 为3886，跳过SAP上传，直接更新数据库状态`)
              successAIDs.push(record.AID)
              successCount++
              continue
            }
            
            // 获取工序数据和订单数据
            const [processData, orderResult] = await Promise.all([
              this.getProcessDataAsync(record.订单编号),
              getB1("/ProductionOrders", {
                "$filter": `AbsoluteEntry eq ${record.订单编号}`
              })
            ])
            
            if (orderResult.data.value.length === 0) {
              this.$message.error(`未找到订单 ${record.订单编号}，批量校验终止`)
              throw new Error(`未找到订单 ${record.订单编号}，批量校验终止`)
            }
            
            const order = orderResult.data.value[0]
            
            // 计算StageID偏移量
            const jia = this.calculateStageOffset(order.ProductionOrderLines)
            
            // 找到当前工序
            const currentProcess = processData.find(item => 
              item.工序名称 === record.工序名称
            )
            
            if (!currentProcess) {
              this.$message.error(`订单 ${record.订单编号} 未找到工序 ${record.工序名称}`)
              console.warn(`订单 ${record.订单编号} 未找到工序 ${record.工序名称}，跳过`)
              failCount++
              continue
            }
            
            const currentStageId = currentProcess.工艺顺序 + jia
            
            // 准备要添加的资源
            let resourcesToAdd = []
            
            if (record.操作类别 === '报工') {
              // 报工：设备 + 人员
              const equipmentResource = await this.getResourceVisCode(record.工位名称)
              if (equipmentResource) {
                resourcesToAdd.push({
                  type: 'equipment',
                  itemName: record.工位名称,
                  itemNo: equipmentResource.visCode,
                  stageId: currentStageId,
                  isAssistant: false
                })
              }
              
              const personnelResource = await this.getResourceVisCode(record.操作人)
              if (personnelResource) {
                resourcesToAdd.push({
                  type: 'personnel',
                  itemName: record.操作人,
                  itemNo: personnelResource.visCode,
                  stageId: currentStageId,
                  isAssistant: false
                })
              }
            } else if (record.操作类别 === '辅助结束') {
              // 辅助结束：辅助设备 + 辅助人员
              const assistantEquipmentName = `辅助-${record.工位名称}`
              const assistantEquipment = await this.getResourceVisCode(assistantEquipmentName)
              if (assistantEquipment) {
                resourcesToAdd.push({
                  type: 'equipment',
                  itemName: assistantEquipmentName,
                  itemNo: assistantEquipment.visCode,
                  stageId: currentStageId,
                  isAssistant: true
                })
              }
              
              const assistantPersonnelName = `辅助-${record.操作人}`
              const assistantPersonnel = await this.getResourceVisCode(assistantPersonnelName)
              if (assistantPersonnel) {
                resourcesToAdd.push({
                  type: 'personnel',
                  itemName: assistantPersonnelName,
                  itemNo: assistantPersonnel.visCode,
                  stageId: currentStageId,
                  isAssistant: true
                })
              }
            } else if (record.操作类别 && record.操作类别.includes('加班')) {
              // 加班：只有人员
              const currentProcessForOvertime = processData.find(item => 
                item.工序名称 === record.工序名称
              )
              
              if (currentProcessForOvertime) {
                const resourcesFromMethod = await this.prepareResourcesToAdd(record, currentProcessForOvertime, currentStageId)
                resourcesToAdd = [...resourcesFromMethod]
                console.log('通过 prepareResourcesToAdd 添加的加班资源:', resourcesFromMethod)
              } else {
                const overtimePersonnelName = `加班-${record.操作人}`
                const overtimePersonnel = await this.getResourceVisCode(overtimePersonnelName)
                if (overtimePersonnel) {
                  resourcesToAdd.push({
                    type: 'personnel',
                    itemName: overtimePersonnelName,
                    itemNo: overtimePersonnel.visCode,
                    stageId: currentStageId,
                    isAssistant: true
                  })
                }
              }
            } else if (record.操作类别 === '开始加工') {
              const assistantPersonnelName = `${record.操作人}`
              const assistantPersonnel = await this.getResourceVisCode(assistantPersonnelName)
              if (assistantPersonnel) {
                resourcesToAdd.push({
                  type: 'personnel',
                  itemName: assistantPersonnelName,
                  itemNo: assistantPersonnel.visCode,
                  stageId: currentStageId,
                  isAssistant: true
                })
              }
            }
            
            // 更新SAP：添加工序和资源
            const hasUpdated = await this.updateSapWithAllStagesAndResources(
              record.订单编号, 
              order, 
              processData, 
              jia, 
              resourcesToAdd,
              record
            )
            
            // 重新获取订单数据（如果更新了SAP）
            let updatedOrder = order
            if (hasUpdated) {
              await new Promise(resolve => setTimeout(resolve, 500))
              const reorderResult = await getB1("/ProductionOrders", {
                "$filter": `AbsoluteEntry eq ${record.订单编号}`
              })
              if (reorderResult.data.value && reorderResult.data.value.length > 0) {
                updatedOrder = reorderResult.data.value[0]
              }
            }
            
            // 计算要上传的工时 - 使用该日期的比例系数
            let uploadMinutes = 0
            
            if (record.操作类别 && record.操作类别.includes('加班')) {
              // 加班直接用原工时
              uploadMinutes = record.originalMinutes
              console.log(`加班记录: 原工时 ${uploadMinutes}分钟`)
            } else {
              // 报工和辅助结束按比例调整
              uploadMinutes = (record.actualMinutes || 0)  * ratio
              console.log(`${record.操作类别}记录: 实际${record.actualMinutes}分钟 × 比例${ratio} = ${uploadMinutes}分钟`)
            }
            
            if (uploadMinutes <= 0) {
              this.$message.error("工时小于等于0,请修改")
              continue
            }
            
            // 创建工时单据
            const params = []
            
            if (record.操作类别 === '报工') {
              if ((record.加工工时 || 0) > 0 && record.总时长 > 0) {
                const equipmentHours = (record.加工工时 / 60 || 0)
                await this.addEquipmentTimeSheet(record, updatedOrder, currentStageId, equipmentHours, params, false)
              } else if ((record.加工工时 || 0) === 0 && record.总时长 > 0) {
                await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, false)
              }
            } else if (record.操作类别 === '开始加工') {
              if ((record.加工工时 || 0) >= 0 && record.总时长 > 0) {
                await this.addPersonnelTimeSheet3(record, updatedOrder, currentStageId, uploadMinutes, params, true)
              }
            } else if (record.操作类别 === '辅助结束') {
              if ((record.加工工时 || 0) > 0 && record.总时长 > 0) {
                const equipmentHours = (record.加工工时 / 60 || 0)
                await this.addEquipmentTimeSheet(record, updatedOrder, currentStageId, equipmentHours, params, true)
              } else if ((record.加工工时 || 0) === 0 && record.总时长 > 0) {
                await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
              }
            } else if (record.操作类别 && record.操作类别.includes('加班')) {
              if ((record.加工工时 || 0) === 0 && record.总时长 > 0) {
                await this.addPersonnelTimeSheet(record, updatedOrder, currentStageId, uploadMinutes, params, true)
              }
            }
            
            // 提交工时单据
            if (params.length > 0) {
              const startDate = record.开始时间 ? record.开始时间.split(' ')[0] : this.currentdate
              const result = await postB1("/InventoryGenExits", {
                "DocDate": startDate,
                "DocDueDate": startDate,
                "Comments": '',
                "DocumentLines": params
              })
              
              if (result.success) {
                console.log(`创建了${params.length}个工时记录`)
                successAIDs.push(record.AID)
              } else {
                this.$message.error('工时上传失败')
                return
              }
            }
            
            successCount++
            await new Promise(resolve => setTimeout(resolve, 300))
            
          } catch (error) {
            console.error(`处理记录失败:`, error)
            failCount++
          }
        }
        
        // 处理该日期的异常记录（只更新数据库状态）
        if (abnormalRecords.length > 0) {
          const aidList = abnormalRecords.map(item => item.AID).join(',')
          var param = [
            ['AID列表', aidList],
            ['操作人', this.getCurrentUser()],
            ['最后编辑人', this.getCurrentUser()]
          ]
          var Data = this.CreateData('11', '工时校验_批量保存校验记录', param)
          await this.ExecDatabase(Data)
          console.log(`日期 ${recordDate} 更新了${abnormalRecords.length}条异常记录的状态`)
        }
      }
      
    } catch (error) {
      console.error(`处理操作人 ${operator} 失败:`, error)
      failCount += operatorRecords.length
    }
  }
  if (successAIDs.length > 0) {
    const successAIDList = successAIDs.join(',')
    var successParam = [
      ['AID列表', successAIDList],
      ['操作人', this.getCurrentUser()],
      ['最后编辑人', this.getCurrentUser()]
    ]
    var successData = this.CreateData('11', '工时校验_批量保存校验记录', successParam)
    await this.ExecDatabase(successData)
    this.$message.success(`批量处理完成，成功: ${successAIDs.length}条，失败: ${failCount}条`)
  
    // 刷新表格
    this.searchTable()
    this.multipleSelection = []
  }
  // this.$message.success(`批量处理完成，成功: ${successCount}条，失败: ${failCount}条`)
},
    
    // // ============ 新增工时记录 ============
    // 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>