<template>
  <div>
    <!-- <div class="headerbox">
      <div class="logo"></div>
      <div class="logname">操作人：{{ logusername() }}</div>
    </div> -->
    <div style="display: flex">
      <el-card style="width: 90%">
        <div class="search-container">
          <span class="show-text">任务ID:</span>
          <el-input
            v-model="TaskAID"
            placeholder="请输入任务ID"
            clearable
            style="width: 150px; margin-right: 10px"
            @change="searchTable()"
          />
          <span class="show-text">生产订单:</span>
          <el-input
            v-model="orderNo2"
            placeholder="请输入生产订单"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <span class="show-text">计划号:</span>
          <el-input
            v-model="plannum"
            placeholder="请输入计划号"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <span class="show-text">销售订单:</span>
          <el-input
            v-model="salenum"
            placeholder="请输入销售订单"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <span class="show-text">物料编码:</span>
          <el-input
            v-model="productCode2"
            placeholder="请输入零件编码"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <span class="show-text">物料名称:</span>
          <el-input
            v-model="productname2"
            placeholder="请输入零件名称"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <!-- <span class="show-text">计划开工:</span>
          <el-date-picker
            v-model="completionTime"
            :clearable="false"
            end-placeholder="结束时间"
            format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始时间"
            style="width: 280px; vertical-align: top"
            type="datetimerange"
            value-format="yyyy-MM-dd"
          /> -->
          <span class="show-text">任务状态:</span>
          <el-select
            v-model="productionStatus2"
            clearable
            placeholder="请选择状态"
            style="width: 150px; margin-right: 10px"
          >
            <el-option label="全部" value="10" />
            <el-option label="待执行" value="0" />
            <el-option label="可执行" value="1" />
            <el-option label="已开工" value="2" />
            <el-option label="已完成" value="4" />
          </el-select>
          <el-button
            :disabled="loading"
            icon="el-icon-search"
            plain
            type="primary"
            @click="searchTable()"
            >查询</el-button
          >
          <el-checkbox-group v-model="Doing" @change = "Doingform" style="margin: 20px;">
            <el-checkbox  v-for="item in Doingoptions" :key="item.工位号" :label="item.指南工位号" :value="item.工位号"> </el-checkbox>
          </el-checkbox-group>
          
        </div>
        <el-table
          v-loading="loading"
          :data="tableData"
          :height="'500px'"
          border
          element-loading-background="rgba(0, 0, 0, 0.2)"
          element-loading-spinner="el-icon-loading"
          highlight-current-row
          size="mini"
          style="width: 100%; margin-top: 20px"
          tooltip-effect="dark"
          @row-click="handleRowClick"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            align="center"
            label="序号"
            type="index"
            width="50"
            fixed
          />
          <el-table-column
            align="center"
            prop="订单号"
            label="生产订单"
            width="80"
            fixed
          />
          <el-table-column
            align="center"
            prop="合同号"
            label="销售订单"
            width="80"
          />
          <el-table-column
            align="center"
            prop="计划号"
            label="计划号"
            width="80"
          />
          <el-table-column
            align="center"
            prop="零件编码"
            label="物料编码"
            width="160"
          />
          <el-table-column
            align="center"
            prop="零件名称"
            label="物料名称"
            width="160"
          />
          
          <!-- <el-table-column
            align="center"
            prop="齐套"
            label="齐套"
            width="80"
          /> -->
          <el-table-column
            align="center"
            label="齐套"
            width="80"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <div
                :style="getScoreStyle(scope.row.齐套)"
                class="score-cell"
              >
                {{ scope.row.齐套 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="发料状态"
            width="80"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <div
                :style="getScoreStyle(scope.row.发料状态)"
                class="score-cell"
              >
                {{ scope.row.发料状态 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="拣配"
            width="80"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <div
                :style="getScoreStyle(scope.row.拣配状态)"
                class="score-cell"
              >
                {{ scope.row.拣配状态 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            width=" 120"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="miss(scope.row)">缺料</el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="加急数量"
            width=" 120"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="Urgent(scope.row)">{{scope.row.加急总数}}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="分配数"
            label="分配数"
            width="60"
          />
          <el-table-column
            align="center"
            prop="完成数量"
            label="送检数"
            width="60"
          />
          <el-table-column
            align="center"
            label="任务状态"
            width="80"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <div
                :style="getScoreStyle(scope.row.任务状态)"
                class="score-cell"
              >
                {{ scope.row.任务状态 }}
              </div>
            </template>
          </el-table-column>
          
          <!-- <el-table-column
            align="center"
            prop="订单行号"
            label="工序顺序"
            width="80"
          /> -->
          <el-table-column
            align="center"
            prop="指派对象"
            label="指派对象"
            width="80"
          />
          <el-table-column align="center" label="计划开始" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.计划开始)}}</template>
          </el-table-column>
          <el-table-column align="center" label="计划完成" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.计划完成)}}</template>
          </el-table-column>
          <el-table-column align="center" label="二次派工" width="100">
            <template slot-scope="scope">{{ scope.row.二次派工名称 }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="工序名称"
            label="工序名称"
            width="80"
          
          />
          <el-table-column
            align="center"
            prop="上序合格数"
            label="上序合格数"
            width="80"
          
          />
          <!-- <el-table-column align="center" label="开工时间" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.开工时间)}}</template>
          </el-table-column> -->
          <!-- <el-table-column align="center" label="加工状态" width="80">
            <template slot-scope="scope">{{ scope.row.加工状态 }}</template>
          </el-table-column> -->
          <!-- 
          <el-table-column
            align="center"
            prop="收料"
            label="收料数"
            width="60"
          />
          
          

          
          <el-table-column align="center" label="优先" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.优先 === '是'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="首检" label="首检" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.首检 === 'OK'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="序检" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.序检 === 'OK'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column> -->
        </el-table>
      </el-card>
      <div style="width: 10%">
        <div class="bottombox">
          <div
            :class="['grid-btn', { 'grid-btn-disabled': workStartLoading }]"
            style="width: 100%; margin-top: 30px"
            @click="workStart()"
          >
            {{ workStartLoading ? '开始中...' : '开始' }}
          </div>
          <div
            class="grid-btn"
            style="width: 100%; margin-top: 30px"
            @click="workEnd()"
          >
            结束
          </div>
          <!-- <div
            class="grid-btn"
            style="width: 100%; margin-top: 30px"
            @click="pause()"
          >
            暂停
          </div> -->
          <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="sendCheck()">送检</div>
          
          <div
            class="grid-btn"
            style="width: 100%; margin-top: 30px"
            @click="abnormal()"
          >
            异常工时
          </div>
          <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="ReturnWarehouse()">退库</div>
          <div class="grid-btn" style="width: 100%; margin-top: 30px" @click="MaterialRequisition()">领料</div>
        </div>
        
      </div>
      
    </div>
    <div class="footbox">
          <!-- <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="miss()"
          >
            缺料
          </div> -->
          <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="firstCheck()"
          >
            首检自检
          </div>
          <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="processCheck()"
          >
            序检自检
          </div>
          <div class="grid-btn" style="margin-left: 50px" @click="receiveCheck()">收检</div>
          <!-- <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="checkRecord()"
          >
            检验记录
          </div> -->
          <div class="grid-btn" style="margin-left: 50px" @click="Abnormalcontrol()">异常管控</div>
          <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="getprocessdraw()"
          >
            工艺图纸
          </div>
          <div
            class="grid-btn"
            style="margin-left: 50px"
            @click="getitemdraw()"
          >
            零件图纸
          </div>
      
        </div>
    <!-- 首检自检弹框 -->
    <el-dialog
      :visible.sync="firstCheckVisible"
      ref="firstCheckForm"
      :model="firstCheckNumber"
      label-width="140px"
      title="首检自检"
      style="text-align: center"
      width="60%"
    >
      <el-form
        ref="checkForm"
        :model="firstCheckData"
        label-position="right"
        label-width="140px"
        size="mini"
      >
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料名称</span>
              <span class="info-value">{{ firstCheckData.物料描述 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">销售订单</span>
              <span class="info-value">{{ firstCheckData.合同号 }}</span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料编号</span>
              <span class="info-value">{{ firstCheckData.物料编号 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">生产订单</span>
              <span class="info-value">{{ firstCheckData.订单编号 }}</span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">工序名称</span>
              <span class="info-value">{{ firstCheckData.工序名称 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检测数量</span>
              <span class="info-value">
                <el-input
                  v-model="firstCheckData.检测数量"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">合格数</span>
              <span class="info-value">
                <el-input
                  v-model="firstCheckData.合格数"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">不合格数</span>
              <span class="info-value">
                <el-input
                  v-model="unqualifiedCount"
                  size="mini"
                  readonly
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">计划生产数</span>
              <span class="info-value">
                {{ firstCheckData.计划数量 }}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label"></span>
              <span class="info-value"></span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">检验人</span>
              <span class="info-value">{{ firstCheckData.检验人 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检验时间</span>
              <span class="info-value">
                <el-date-picker
                  v-model="firstCheckData.检验时间"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <!-- 当前检测信息显示 -->
          <div style="margin: 10px 0; font-weight: bold">
            当前检测第 {{ currentPage }} 件 / 共
            {{ firstCheckData.检测数量 }} 件
          </div>

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

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

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

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

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

          <div class="info-container">
            <div class="info-item">
              <span class="info-label">检验人</span>
              <span class="info-value">{{ receiveCheckData.检验人 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">检验时间</span>
              <span class="info-value">
                <el-date-picker
                  v-model="receiveCheckData.检验时间"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  style="width: 200px"
                />
              </span>
            </div>
          </div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">计划生产数</span>
              <span class="info-value">
                {{ receiveCheckData.计划生产数 }}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">已检验数量</span>
              <span class="info-value">
                {{ receiveCheckData.已检验数量 }}
              </span>
            </div>
          </div>
          <div class="info-container">
            <span class="info-label">备注</span>
            <span class="info-value">
              <el-input
                v-model="receiveCheckData.备注"
                type="textarea"
                :rows="1"
                resize="vertical"
                size="mini"
                style="width: 100%"
              />
            </span>
          </div>
        </div>
      </el-form>
      <div class="dialog-footer" style="padding: 10px">
        <div
          style="
            margin-bottom: 20px;
            display: flex;
            justify-self: center;
            align-items: center;
          "
        >
          <el-button
            type="primary"
            @click="submitReceiveCheckData"
            style="min-width: 120px"
            >确定</el-button
          >
          <el-button @click="receiveCheckVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="assistendVisible"
      title="送检"
      width="600px"
      center
    >
      <el-form
        ref="assistendForm"
        :model="assistendData"
        label-width="140px"
        size="mini"
      >
        <el-form-item label="生产订单">
          <el-input v-model="assistendData.订单号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="零件编码">
          <el-input v-model="assistendData.零件编码" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="计划数量">
          <el-input v-model="assistendData.计划生产数" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="当前时间">
          <el-input v-model="this.currentTime" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="送检数">
          <el-input
            v-model="assistNumber"
            type="number"
            @change="funassistNum"
          />
        </el-form-item>
        <el-form-item label="操作工位">
          <el-input v-model="assistendData.指派对象" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="this.$store.state.user.name" :rows="2" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assistendVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendInspection()">确 定</el-button>
      </div>
    </el-dialog>
    <!--异常工时-->
    <el-dialog
      :visible.sync="abnormalVisible"
      title="异常工时"
      width="62%"
      center
    >
      <el-button icon="el-icon-add" plain type="primary" @click="addWorkTimeRecord" style="width: auto;" >新增异常工时</el-button>
      <el-table
        v-loading="loading"
        :data="abnormaltableData"
        :height="'50vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
        @row-click="handleRowClick2"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="50"
          fixed
        />
        <el-table-column
          align="center"
          prop="指派对象"
          label="人员"
          width="80"
          fixed
        />
        <el-table-column
          align="center"
          prop="订单号"
          label="生产订单"
          width="80"
          fixed
        />
        <el-table-column
          align="center"
          prop="操作类别"
          label="类型"
          width="80"
          fixed
        />
        <el-table-column
          align="center"
          prop="产品编码"
          label="物料编码"
          width="120"
        />
        <el-table-column
          align="center"
          prop="产品名称"
          label="物料名称"
          width="120"
        />
        <el-table-column
          align="center"
          prop="工序名称"
          label="工序名称"
          width="80"
        />
        <el-table-column align="center" label="开始时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.开始时间) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="结束时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.结束时间) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="加工工时" width="100">
          <template slot-scope="scope">
            {{ scope.row.总工时 || 0 }}秒
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="最后编辑人"
          label="最后编辑人"
          width="100"
        />
        <el-table-column align="center" label="最后编辑时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.最后编辑时间) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="editTask(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

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

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

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

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">关闭</el-button>
        <el-button
          v-if="!currentTask.已校验"
          type="primary"
          @click="submitEditForm"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 退库弹窗 -->
      <el-dialog
        :visible.sync="ReturnWarehousepop"
        title="退库单"
        width="1300px"
        center
        :close-on-click-modal="false"
      >
        <el-form ref="ReturnWarehouseForm" :model="ReturnWarehouseForm" size="mini">
          <el-form-item  v-for="item in ReturnWarehouseForm" :key="item.编码" >
            <div class="info-container" >
              <div class="info-item">
                <span class="info-label">物料名称</span>
                <span class="info-value">
                  <el-input
                    v-model="item.名称"
                    size="mini"
                    readonly
                    style="width: 200px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">物料编号</span>
                <span class="info-value">
                  <el-input
                    v-model="item.编码"
                    size="mini"
                    style="width: 250px"
                    readonly
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">发料数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.数量"
                    size="mini"
                    style="width: 100px"
                    readonly
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">退库数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.退库数量"
                    size="mini"
                    style="width: 100px"
                    
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">备注</span>
                <span class="info-value">
                  <el-input
                    v-model="item.LineText"
                    size="mini"
                    style="width: 100px"
                    
                  />
                </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="ReturnWarehousepop = false">关闭</el-button>
          <el-button
            type="primary"
            @click="submitReturnWare"
          >
            确 定
          </el-button>
        </div>
      </el-dialog>
    <!-- 领料弹窗 -->
      <el-dialog
        :visible.sync="MaterialRequisitionpop"
        title="领料单"
        width="1200px"
        center
        :close-on-click-modal="false"
      >
        <el-form ref="MaterialRequisitionForm" :model="MaterialRequisitionForm" size="mini">
          <el-form-item  v-for="item in MaterialRequisitionForm.lines" :key="item.ItemNo" >
            <div class="info-container" >
              <div class="info-item">
                <span class="info-label" style="width: 80px">物料名称</span>
                <span class="info-value">
                  <el-input
                    v-model="item.ItemName"
                    size="mini"
                    readonly
                    style="width: 300px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.Quantity"
                    size="mini"
                    style="width: 150px"
                  />
                </span>
              </div>
              <!-- <div class="info-item">
                <span class="info-label" style="width: 80px">拣配数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.拣配数量"
                    size="mini"
                    style="width: 150px"
                    readonly
                  />
                </span>
              </div> -->
              <div class="info-item">
                <span class="info-label" style="width: 80px">发料数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.IssuedQuantity"
                    size="mini"
                    style="width: 150px"
                    readonly
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">备注</span>
                <span class="info-value">
                  <el-input
                    v-model="item.LineText"
                    size="mini"
                    style="width: 150px"
                  />
                </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="MaterialRequisitionpop = false">关闭</el-button>
          <el-button
            type="primary"
            @click="submitMaterialRequisition(MaterialRequisitionForm.lines)"
          >
            确 定
          </el-button>
        </div>
      </el-dialog>
    <!-- 缺料弹框 -->
     <el-dialog
        :visible.sync="misspop"
        title="缺料单"
        width="1200px"
        center
        :close-on-click-modal="false"
      >
        <el-form ref="missForm" :model="missForm" size="mini">
          <el-form-item  v-for="item in missdata" :key="item.ItemCode" >
            <div class="info-container" >
              <div class="info-item">
                <span class="info-label">物料名称</span>
                <span class="info-value">
                  <el-input
                    v-model="item.U_Name"
                    size="mini"
                    readonly
                    style="width: 200px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">物料编号</span>
                <span class="info-value">
                  <el-input
                    v-model="item.ItemCode"
                    size="mini"
                    readonly
                    style="width: 200px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.缺货数量"
                    size="mini"
                    style="width: 100px"
                  />
                </span>
              </div>
              
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="misspop = false">关闭</el-button>
        </div>
      </el-dialog>
    <!-- 报工结束弹框 -->
    <el-dialog
      :visible.sync="workendVisible"
      title="报工结束"
      width="600px"
      center
    >
      <el-form
        ref="assistendForm"
        :model="workendData"
        label-width="140px"
        size="mini"
      >
        <el-form-item label="生产订单">
          <el-input v-model="workendData.订单号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="销售订单">
          <el-input v-model="workendData.合同号" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="零件编码">
          <el-input v-model="workendData.零件编码" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="当前时间">
          <el-input v-model="this.currentTime" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="操作工位">
          <el-input v-model="workendData.指派对象" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="this.$store.state.user.name" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="workendData.备注" :rows="2" />
        </el-form-item>
        <el-form-item label="工序说明">
          <el-input v-model="workendData.工序说明" :rows="2" />
        </el-form-item>
        <el-form-item label="异常说明">
          <el-input v-model="workendData.异常说明" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="workendVisible = false">取 消</el-button>
        <el-button type="primary" @click="workendForm()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="seeVisible" title="图纸" center width="1200px" overflow="scroll" >
      <div id="el-dialog__body" style="min-height: 500px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="seeVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
        :visible.sync="UrgentVisible"
        title="加急明细"
        width="1200px"
        center
        :close-on-click-modal="false"
      >
        <el-form ref="Urgentarr" :model="Urgentarr" size="mini">
          <el-form-item  v-for="item in Urgentarr" :key="item.订单编号" >
            <div class="info-container" >
              <div class="info-item">
                <span class="info-label" style="width: 80px">生产订单</span>
                <span class="info-value">
                  <el-input
                    v-model="item.订单编号"
                    size="mini"
                    readonly
                    style="width: 300px"
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">加急数量</span>
                <span class="info-value">
                  <el-input
                    v-model="item.加急数量"
                    size="mini"
                    style="width: 150px"
                    readonly
                  />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label" style="width: 80px">物料编号</span>
                <span class="info-value">
                  <el-input
                    v-model="item.物料编号"
                    size="mini"
                    style="width: 150px"
                    readonly
                  />
                </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="UrgentVisible = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 加班弹窗 -->
    <el-dialog
      title="加班确认"
      :visible.sync="overtimeDialogVisible"
      width="550px"
      :close-on-click-modal="false"
      :before-close="handleOvertimeClose"
    >
      <el-form>
        <!-- 是否加班 -->
        <el-form-item label="是否加班" required>
          <el-radio-group v-model="isOvertime" @change="onOvertimeChange">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 日期类型选择 -->
        <el-form-item label="日期类型">
          <el-radio-group v-model="selectedOption" size="default" @change="onStatusChange">
            <el-radio label="工作日" border>工作日</el-radio>
            <el-radio label="休息日" border>休息日</el-radio>
            <el-radio label="法定休息日" border>法定休息日</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 加班人员 -->
        <el-form-item label="加班人员">
          <el-select 
            v-model="overtimePerson" 
            placeholder="请选择加班人员"
            filterable
            multiple
            style="width: 100%"
            :disabled="isOvertime !== 1"
          >
            <el-option
              v-for="item in overtimeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <!-- 特殊加班人员 -->
        <el-form-item label="特殊工时人员">
          <el-select 
            v-model="tsovertimePersons" 
            placeholder="请选择特殊工时人员"
            filterable
            multiple
            style="width: 100%"
            :disabled="isOvertime !== 1"
          >
            <el-option
              v-for="item in overtimeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <!-- 班次标准工时 -->
        <el-form-item label="班次标准工时(H)">
          <el-input-number 
            v-model="shiftStandardHours" 
            :min="0" 
            :max="24"
            style="width: 100%"
            :disabled="isOvertime !== 1"
          />
        </el-form-item>
        
        <!-- 提示信息 -->
        <div v-if="isOvertime === 1 && (!overtimePerson || overtimePerson.length === 0) && (!tsovertimePersons || tsovertimePersons.length === 0)" style="color: #f56c6c; font-size: 12px; margin-top: 5px">
          请至少选择一名加班人员或特殊工时人员
        </div>
      </el-form>
      <span slot="footer">
        <el-button @click="overtimeDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmOvertime"
          :disabled="isOvertime === 1 && (!overtimePerson || overtimePerson.length === 0) && (!tsovertimePersons || tsovertimePersons.length === 0)"
        >
          确定
        </el-button>
      </span>
    </el-dialog>
    
    
  </div>
</template>

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

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

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


      abnormalControlDialogVisible: false,
      //异常管控相关数据
      orderNo: '',
      contractNo: '',
      productCode: '',
      productName: '',
      processName: '',
      completionTime: [],
      productionStatus: '',
      
      tableData5: [],
      activeTab: 'pending',
      tableOrderNum: '',
      tableProductCode: '',
      tableProductName: '',
      tableProcessName: '',
      selectedRow: '',
      loading: false,
      imgDialogFormVisible: false,
      
      // 转办相关数据
      transferDialogVisible: false,
      transferLoading: false,
      
      // 完结相关数据
      completeDialogVisible: false,
      completeLoading: false,
      
      //currentTask: null,
      currentProcess: null,
      selectProcess: null,
      
      transferForm: {
        newApproverId: '',
        newApproverName: '',
        reason: ''
      },
      
      completeForm: {
        reason: '',
        result: 'completed'
      },
      
      createDialogVisible: false,
      handleDialogVisible: false,
      detailDialogVisible: false,
      submitting: false,
      
      filters: {
        pending: { keyword: '', priority: '', type: '' },
        initiated: { keyword: '', status: '' }
      },
      
      newProcessForm: {
        type: '',
        priority: 'normal',
        title: '',
        description: '',
        approvers: []
      },
      
      formRules: {
        title: [{ required: true, message: '请输入流程标题', trigger: 'blur' }],
        description: [{ required: true, message: '请输入流程描述', trigger: 'blur' }]
      },
      
      handleForm: {
        result: 'approved',
        comment: ''
      },
      
      userList: [],
      
      stats: {
        pending: 0,
        initiated: 0,
        completed: 0,
      },
      
      // 数据
      pendingTasks: [],
      initiatedProcesses: [],
      processedTasks: [],
      users: [],
      Abnormalcontrolpop:false,
      ReturnWarehousepop:false,
      ReturnWarehouseForm:{
        名称:'',
        编码:'',
        数量:'',
        退库数量:''
      },
      MaterialRequisitionpop:false,
      MaterialRequisitionForm:{},
      downPDF:MESDownFile,
      pausePreviousState:{},
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前时间之后的日期
          return time.getTime() > Date.now();
        },
      },
      
      // 人员时间记录相关
      userTimeRecords: {}, // 存储用户开始时间记录 { taskAID: { userId: startTime } }
      userTimeRecords2:{},
      // 新增相关数据
      orderList: [], // 订单列表
      processList: [], // 工序列表
      
      // 新增工时记录
      addRecordDialogVisible: false,
      addRecordLoading: false,
      addRecordForm: {
        操作类别: '',
        订单编号: '',
        产品编码: '',
        产品名称: '',
        工序名称: '',
        指派对象: '',
        开始时间: '',
        结束时间: '',
        操作内容: '',
        操作描述: ''
      },
      addRecordRules: {
        操作类别: [{ required: true, message: '请选择操作类别', trigger: 'change' }],
        订单编号: [{ required: true, message: '请选择订单编号', trigger: 'change' }],
        工序名称: [{ required: true, message: '请选择工序名称', trigger: 'change' }],
        指派对象: [{ required: true, message: '请输入操作人员', trigger: 'blur' }],
        开始时间: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        结束时间: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      },
      currentTime:'',
      currentdate:'',

      missForm:{
        ItemCode: "",
        U_Name: "",
        缺货数量: 0
      },
      missdata:[],
      misspop:false,
      workendData:{},
      workendVisible:false,
      seeVisible:false,
      UrgentVisible: false,
      Urgentarr: {},
      processname2:'',
      TaskAID2:'',

      //新增报工加班
      shiftConfig: [], // 班次配置
      overtimePerson: '', // 加班人员
      overtimeHours: '', // 加班时长
      isOvertime: false, // 是否加班
      overtimeDialogVisible: false,
      overtimeOptions: [],
      overtimeResolve: null,
      overtimeReject: null,
      currentShift: null, // 保存当前班次信息
      selectedOvertimePerson:'',
      shiftEndTimeStr:'',
      selectedOperatorsName:'',
      selectedOption: '工作日',   // 日期类型选项
      isRestDay: 0,               // 是否休息日
      isLegalRestDay: 0,          // 是否法定休息日
      isOvertime: 0,              // 是否加班
      tsovertimePersons: [],      // 特殊加班人员
      shiftStandardHours: 8,      // 班次标准工时
    };
    
  },
  created() {
    
    var now = new Date();
    var start = new Date(
      Date.UTC(now.getFullYear() , now.getMonth()-1, now.getDate(), 0, 0, 0)
    )
      .toISOString()
      .replace("T", " ")
      .replace(".000Z", "");
    var end = new Date(
      Date.UTC(now.getFullYear(), now.getMonth()+1, now.getDate(), 23, 59, 59)
    )
      .toISOString()
      .replace("T", " ")
      .replace(".000Z", "");
    this.completionTime = [start, end];
    this.rptDate = end;
    this.searchTable();
    this.getCurrentTime();
    this.getDoing();
    this.getProcessList();
    this.loadOrderList('')
    // this.getBind()
    setInterval(this.getCurrentTime, 1000);
    setInterval(this.searchTable, 300000);
  },
  computed: {
    ...mapGetters([
      'id',
      'name',
      'token'
    ]),
    getBind(){
      var param = [['操作人ID', this.$store.state.user.id]]
      var Data = this.CreateData('11', '生产管理_获取人员绑定', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response.data)
        response.data.forEach(element => {
          this.Doing.push(element.工位名称)
          this.searchTable();
        });
      })
    },
    filteredPendingTasks() {
      let tasks = this.pendingTasks;
      if (this.filters.pending.keyword) {
        tasks = tasks.filter(task => 
          task.流程标题.includes(this.filters.pending.keyword)
        );
      }
      if (this.filters.pending.priority) {
        tasks = tasks.filter(task => task.优先级 == this.filters.pending.priority);
      }
      return tasks;
    },
    
    filteredInitiatedProcesses() {
      let processes = this.initiatedProcesses;
      if (this.filters.initiated.keyword) {
        processes = processes.filter(process => 
          process.流程标题.includes(this.filters.initiated.keyword)
        );
      }
      if (this.filters.initiated.status) {
        processes = processes.filter(process => process.状态 === this.filters.initiated.status);
      }
      return processes;
    },
    unqualifiedCount() {
      // 计算有多少页至少有一个不合格项
      let unqualifiedPages = 0;
      if (this.inspectionData && this.inspectionData.length > 0) {
        for (let page = 0; page < this.inspectionData.length; page++) {
          const pageData = this.inspectionData[page];
          if (pageData && pageData.some((item) => item.检测结果 === "0")) {
            unqualifiedPages++;
          }
        }
      }
      return unqualifiedPages;
      
    },
    
    betweenProcessUnqualifiedCount() {
      let unqualifiedPages = 0;
      if (
        this.betweenProcessInspectionData &&
        this.betweenProcessInspectionData.length > 0
      ) {
        for (
          let page = 0;
          page < this.betweenProcessInspectionData.length;
          page++
        ) {
          const pageData = this.betweenProcessInspectionData[page];
          if (pageData && pageData.some((item) => item.检测结果 === "0")) {
            unqualifiedPages++;
          }
        }
      }
      return unqualifiedPages;
    },
  },
  methods: {
    handletaskChange(process){
      console.log(process)
      const res  = this.processList.find(item=>(item.TaskAID === process))
      console.log(res)
      this.processname2 = res.工序名称
      this.TaskAID2 = process
    },
    Urgent(row){
      var param = []
      param.push(["物料编号",row.零件编码])
      this.UrgentVisible = true
      var Data = this.CreateData("11", "加急订单_加急明细查询",param);
      this.ExecDatabase(Data).then((response) => {
        this.Urgentarr = response.data
      });
    },
    // 获取用户进行中的任务记录
// 获取用户进行中的任务记录
async getUserTaskRecords2() {
  try {
    const userName = this.getUserName();
    const param = [];
    param.push(["用户ID", userName]);
    
    const Data = this.CreateData("11", "MES_人员工时记录_获取进行中任务2", param);
    const response = await this.ExecDatabase(Data);
    
    if (response.data && response.data.length > 0) {
      // 清空之前的记录
      this.userTimeRecords = {};
      
      // 将数据库中的数据转换为 userTimeRecords 格式
      response.data.forEach(record => {
        const taskAID = record.TaskAID;
        const userName = record.UserName || record.操作人;
        const startTime = record.StartTime || record.开始时间;
        
        if (!this.userTimeRecords[taskAID]) {
          this.userTimeRecords[taskAID] = {};
        }
        this.userTimeRecords[taskAID][userName] = startTime;
      });
      
      console.log("用户进行中任务记录加载成功:", this.userTimeRecords);
    } else {
      this.userTimeRecords = {};
    }
  } catch (error) {
    console.error("获取用户任务记录失败:", error);
    this.userTimeRecords = {};
  }
},
async getUserTaskRecords() {
  try {
    const userName = this.getUserName();
    const param = [];
    param.push(["用户ID", userName]);
    
    const Data = this.CreateData("11", "MES_人员工时记录_获取进行中任务", param);
    const response = await this.ExecDatabase(Data);
    
    if (response.data && response.data.length > 0) {
      // 清空之前的记录
      this.userTimeRecords = {};
      
      // 将数据库中的数据转换为 userTimeRecords 格式
      response.data.forEach(record => {
        const taskAID = record.TaskAID;
        const userName = record.UserName || record.操作人;
        const startTime = record.StartTime || record.开始时间;
        
        if (!this.userTimeRecords[taskAID]) {
          this.userTimeRecords[taskAID] = {};
        }
        this.userTimeRecords[taskAID][userName] = startTime;
      });
      
      console.log("用户进行中任务记录加载成功:", this.userTimeRecords);
    } else {
      this.userTimeRecords = {};
    }
  } catch (error) {
    console.error("获取用户任务记录失败:", error);
    this.userTimeRecords = {};
  }
},

// 检查用户是否已开始特定任务
// isUserStarted(taskAID) {
//   const userName = this.getUserName();
//   return (
//     this.userTimeRecords[taskAID] && 
//     this.userTimeRecords[taskAID][userName]
//   );
// },
isUserStarted(taskAID) {
  const userName = this.getUserName();
  // 检查是否有任何任务包含当前用户的记录
  const hasStarted = Object.values(this.userTimeRecords).some(
    record => record && record[userName]
  );
  return hasStarted; // 如果找到返回 false，没找到返回 true
},
isUserStarted2(taskAID) {
  const userName = this.getUserName();
  if(this.userTimeRecords[taskAID]){
    return 1
  }else{
    return 0
  }
},
// 获取开始时间
getUserStartTime(taskAID) {
  const userName = this.getUserName();
  if (this.userTimeRecords[taskAID] && this.userTimeRecords[taskAID][userName]) {
    return this.userTimeRecords[taskAID][userName];
  }
  return null;
},

// 获取当前用户名
getUserName() {
  return this.$store.state.user.name;
},

// 获取当前用户ID
getUserId() {
  return this.$store.state.user.id;
},
    loadOrderList(orderId) {
      var param = []
      param.push(['订单编号',orderId])
      var Data = this.CreateData('11', '工时校验_获取订单列表', param)
      this.ExecDatabase(Data).then(response => {
        this.orderList = response.data || []
      }).catch(error => {
        console.error('加载订单列表失败:', error)
        this.orderList = []
      })
    },
    // 提交新增记录（修改后的）
    submitAddRecord() {
      this.$refs.addRecordForm.validate((valid) => {
        if (valid) {
          this.addRecordLoading = true
          
          // 计算工时（秒）
          let workTime = 0
          if (this.addRecordForm.开始时间 && this.addRecordForm.结束时间) {
            const start = new Date(this.addRecordForm.开始时间)
            const end = new Date(this.addRecordForm.结束时间)
            const diff = end.getTime() - start.getTime()
            workTime = Math.round(diff / 1000)
          }
          
          const recordData = {
            ...this.addRecordForm,
            工时: workTime,
            操作人: this.getCurrentUser(),
            报工日期: new Date().toISOString().split('T')[0]
          }
          
          // 调用新增API
          var param = [
            ['操作类别', this.addRecordForm.操作类别],
            ['订单编号', this.addRecordForm.订单编号],
            ['物料编号', this.addRecordForm.产品编码],
            ['物料描述', this.addRecordForm.产品名称],
            ['工序名称', this.processname2],
            // ['工位名称', this.addRecordForm.指派对象], // 使用指派对象作为工位名称
            ['操作人', this.getCurrentUser()],
            ['开始时间', this.addRecordForm.开始时间],
            ['结束时间', this.addRecordForm.结束时间],
            ['操作内容', this.addRecordForm.操作内容],
            ['操作描述', this.addRecordForm.操作描述],
            ['TaskAID', this.TaskAID2],
          ]
          console.log(param)
          var Data = this.CreateData('11', '异常工时_新增操作记录', param)
          this.ExecDatabase(Data).then(response => {
            this.$message.success('新增成功')
            this.addRecordDialogVisible = false
            this.abnormalTable() // 刷新表格
          }).catch(error => {
            this.$message.error('新增失败：' + error.message)
          }).finally(() => {
            this.addRecordLoading = false
          })
        }
      })
    },
    handleOrderChange(orderId) {
      if (orderId) {
        // 自动填充零件编码和零件名称
        this.loadOrderList(orderId)
        const selectedOrder = this.orderList.find(order => order.订单编号 == orderId)
        if (selectedOrder) {
          this.addRecordForm.产品编码 = selectedOrder.零件编码
          this.addRecordForm.产品名称 = selectedOrder.零件名称
        }
        
        // 加载该订单的工序列表
        this.loadProcessList(orderId)
      } else {
        this.addRecordForm.产品编码 = ''
        this.addRecordForm.产品名称 = ''
        this.processList = []
      }
    },
    loadProcessList(orderId) {
      var param = [['订单编号', orderId]]
      var Data = this.CreateData('11', '工时校验_获取订单工序', param)
      this.ExecDatabase(Data).then(response => {
        this.processList = response.data || []
        // 如果只有一个工序，自动选择
        if (this.processList.length === 1) {
          this.addRecordForm.工序名称 = this.processList[0].工序名称
          this.addRecordForm.TaskAID = this.processList[0].TaskAID
        }
      }).catch(error => {
        console.error('加载工序列表失败:', error)
        this.processList = []
      })
    },
    addWorkTimeRecord() {
      var row = this.selectedRow
      this.addRecordForm = {
        操作类别: '',
        订单编号: row.订单号,
        产品编码: row.零件编码,
        产品名称: row.零件名称,
        工序名称: row.工序名称,
        指派对象: this.$store.state.user.name,
        开始时间: '',
        结束时间: '',
        操作内容: '',
        操作描述: '',
        TaskAID: Number(row.TaskAID)
      }
      this.processname2 = row.工序名称
      this.TaskAID2 = row.TaskAID
      this.processList = []
      this.addRecordDialogVisible = true
    },
    funassistNum(num) {
      this.assistNumber = num;
    },
    tableRowClassName({ row, rowIndex }) {
      const isUrgent = row.优先 === '是' || row.加急 === '加急' ;
      if (isUrgent) {
        return 'priority-row';
      }
      return '';
    },
    getDoing() {
      var Data = this.CreateData("11", "MES_登录_工位与名称_查询");
      this.ExecDatabase(Data).then((response) => {
        this.loading = false;
        if (response.data.length !== 0) {
          this.Doingoptions = response.data;
        }
      });
    },
    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getScoreStyle(bgcolor) {
      if (bgcolor == "可执行" || bgcolor == "是" || bgcolor == "发料齐套" || bgcolor == "已拣配" ) {
        return {
          backgroundColor: "#f0f9eb",
          color: "#67c23a",
        };
      } else if (bgcolor == "已完成") {
        return {
          backgroundColor: "#ecf5ff",
          color: "#409eff",
        };
      } else if (bgcolor == "已开工" || bgcolor == "否" || bgcolor == "发料缺件" || bgcolor == "未拣配") {
        return {
          backgroundColor: "#fdf6ec",
          color: "#e6a23c",
        };
      } else if (bgcolor == "开始加工"  ||  bgcolor == "辅助开始") {
        return {
          backgroundColor: "#f0f9eb",
          color: "#67c23a",
        };
      } else if (bgcolor == "暂停") {
        return {
          backgroundColor: "#fdf6ec",
          color: "#e6a23c",
        };
      } else if (bgcolor == "报工" ||  bgcolor == "辅助结束") {
        return {
          backgroundColor: "#ecf5ff",
          color: "#409eff",
        };
      }
      
    },
    getProcessList() {
      this.processList2 = [];
      var Data = this.CreateData("11", "Prog_MES_LoadProcess");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.processList2.push({
            label: response.data[i].工序名称,
            value: response.data[i].工艺编号,
          });
        }
      });
    },
    // searchTable() {
    //   this.getUserTaskRecords2()
    //   this.loading = true;
    //   this.tableData = [];
    //   var param = [];
    //   param.push(["TaskAID", this.TaskAID || 0]);
    //   param.push(["订单号", this.orderNo2 || 0]);
    //   param.push(["零件编号", this.productCode2]);
    //   param.push([
    //     "计划开工_Start",
    //      "",
    //   ]);
    //   param.push([
    //     "计划开工_End",
    //     "",
    //   ]);
    //   param.push(["生产状态", this.productionStatus2 || -1]);
    //   param.push(["工位名称", this.Doing]);
    //   param.push(["用户ID" , this.$store.state.user.id]);
    //   param.push(["计划号", this.plannum]);
    //   param.push(["销售订单", this.salenum]);
    //   var Data = this.CreateData("11", "MES_ProductCenter_GetTask_zp", param);
    //   this.ExecDatabase(Data)
    //     .then((response) => {
    //       this.loading = false;

    //       // 完整的优先级映射
    //       const priorityLevel = {
    //         '高': 3,
    //         '中': 2, 
    //         '低': 1,
    //         '是': 1,
    //         '否': 0,
    //         '加急': 4,
    //         '紧急': 4,
    //         '一般': 2
    //       };
          
    //       if (response.data && response.data.length !== 0) {
          
    //         this.tableData = response.data;
            
    //         this.tableData.sort((a, b) => {
    //           const userName = this.getUserName();
    //           const aStarted = this.isUserStarted2(a.TaskAID);
    //           const bStarted = this.isUserStarted2(b.TaskAID);
    //           if (aStarted && !bStarted) return -1; // a已开始，b未开始，a排前面
    //           if (!aStarted && bStarted) return 1;  // b已开始，a未开始，b排前面
    //           // 1. 首先按任务状态排序（2 > 1 > 0）
    //           // const statusOrder = { '已开工': 3 }; // 2最高，1次之，0最低
    //           // const aStatus = statusOrder[a.任务状态] || 0;
    //           // const bStatus = statusOrder[b.任务状态] || 0;

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

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

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

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

    //           if (aPriority !== bPriority) {
    //             return bPriority - aPriority;
    //           }
    //           const aqtCode = a.齐套 === '是';
    //           const bqtCode = b.齐套 === '是';
    //           if (aqtCode && !bqtCode) return -1;
    //           if (!aqtCode && bqtCode) return 1;
    //           // 4. 按计划开始时间排序（早的在前）
    //           const aStartTime = a.计划开始 ? new Date(a.计划开始).getTime() : Infinity;
    //           const bStartTime = b.计划开始 ? new Date(b.计划开始).getTime() : Infinity;

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

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

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

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

    //处理表格行点击事件
    async searchTable() {
  this.loading = true;
  this.tableData = [];
  
  try {
    // 先获取用户任务记录
    await this.getUserTaskRecords2();
    
    var param = [];
    param.push(["TaskAID", this.TaskAID || 0]);
    param.push(["订单号", this.orderNo2 || 0]);
    param.push(["零件编号", this.productCode2]);
    param.push(["零件名称", this.productname2]);
    param.push(["计划开工_Start", ""]);
    param.push(["计划开工_End", ""]);
    param.push(["生产状态", this.productionStatus2 || -1]);
    param.push(["工位名称", this.Doing]);
    param.push(["用户ID", this.$store.state.user.id]);
    param.push(["计划号", this.plannum]);
    param.push(["销售订单", this.salenum]);
    
    var Data = this.CreateData("11", "MES_ProductCenter_GetTask_zp", param);
    const response = await this.ExecDatabase(Data);
    
    this.loading = false;
    
    // 完整的优先级映射
    const priorityLevel = {
      '高': 3,
      '中': 2, 
      '低': 1,
      '是': 1,
      '否': 0,
      '加急': 4,
      '紧急': 4,
      '一般': 2
    };
    
    if (response.data && response.data.length !== 0) {
      this.tableData = response.data;
      
      // 创建已开始任务的Set（只要TaskAID在userTimeRecords中就优先）
      const startedTaskSet = new Set();
      const userTimeRecords = this.userTimeRecords || {};
      
      Object.keys(userTimeRecords).forEach(taskAID => {
        startedTaskSet.add(Number(taskAID));
      });
      
      this.tableData.sort((a, b) => {
        // 1. 优先按TaskAID是否在userTimeRecords中排序（匹配的排在前面）
        const aStarted = startedTaskSet.has(a.TaskAID);
        const bStarted = startedTaskSet.has(b.TaskAID);
        
        if (aStarted && !bStarted) return -1;
        if (!aStarted && bStarted) return 1;
        
        // 2. 然后按加急状态排序
        const aIsUrgent = a.加急 === '加急';
        const bIsUrgent = b.加急 === '加急';
        
        if (aIsUrgent && !bIsUrgent) return -1;
        if (!aIsUrgent && bIsUrgent) return 1;
        
        // 3. 按优先级排序（数值大的在前）
        const aPriority = priorityLevel[a.优先] || 0;
        const bPriority = priorityLevel[b.优先] || 0;
        
        if (aPriority !== bPriority) {
          return bPriority - aPriority;
        }
        
        // 4. 按齐套状态排序
        const aqtCode = a.齐套 === '是';
        const bqtCode = b.齐套 === '是';
        if (aqtCode && !bqtCode) return -1;
        if (!aqtCode && bqtCode) return 1;
        
        // 5. 按计划开始时间排序（早的在前）
        const aStartTime = a.计划开始 ? new Date(a.计划开始).getTime() : Infinity;
        const bStartTime = b.计划开始 ? new Date(b.计划开始).getTime() : Infinity;
        
        if (aStartTime !== bStartTime) {
          return aStartTime - bStartTime;
        }
        
        // 6. 优先级相同，按订单号排序
        const aOrderNo = String(a.订单号 || '');
        const bOrderNo = String(b.订单号 || '');
        
        if (aOrderNo !== bOrderNo) {
          return aOrderNo.localeCompare(bOrderNo);
        }
        
        // 7. 订单号相同，按拆分内码排序
        const aSplitCode = Number(a.订单拆分内码) || 0;
        const bSplitCode = Number(b.订单拆分内码) || 0;
        return aSplitCode - bSplitCode;
      });
    } else {
      console.log("没有获取到数据");
      this.tableData = [];
    }
  } catch (error) {
    this.loading = false;
    console.error("请求失败:", error);
  }
},
    handleRowClick(row) {
      console.log(this);
      this.selectedRow = row;
      this.taskstate = row.任务状态;
      this.taskprogress = (parseInt(row.完成数量) / parseInt(row.分配数)) * 100;
      this.WorkTimeSum(row.TaskAID);
    },
    WorkTimeSum(row) {
      var param = [];
      param.push([
        "计划开工_Start",
        this.completionTime ? this.completionTime[0] : "",
      ]);
      param.push([
        "计划开工_End",
        this.completionTime ? this.completionTime[1] : "",
      ]);
      var Data = this.CreateData("11", "MES_ProductTask_WorkTimeSum", param);
      this.ExecDatabase(Data)
        .then((response) => {
          console.log(response.data);
          response.data.forEach((item) => {
            if (item.TaskAID == row) {
              this.startworktime = item.总工时;
            }
          });
        })
        .catch(() => {});
    },
    formatDate(date) {
      if (!date) return "";
      return date.split(" ").length > 1 ? date.split(" ")[0] : date;
    },
    logusername() {
      return this.name;
    },
    Doingform(value){
      console.log(value)
      this.station = ''
    },
    miss(row){
      // var row = this.selectedRow;
      // if (!row) {
      //   this.$message.warning("请先选择一行数据");
      //   return;
      // }
      const params = [];
      params.push(["ItemCode", row.零件编码]);
      params.push(["订单号", row.订单号]);
      const Data = this.CreateData("11", "生产管理_装配中心_缺料查询", params);
      this.ExecDatabase(Data).then((response) => {
        this.misspop = true
        this.missdata = response.data 
      })

    },
    // 开始按钮 - 记录人员开始时间
    // 开始按钮 - 记录人员开始时间
async workStart() {
  if (this.workStartLoading) {
    return;
  }
  var row = this.selectedRow;
  if (!row) {
    this.$message.warning("请先选择一行数据");
    return;
  }
  
  const taskAID = row.TaskAID;
  const userName = this.getUserName();
  const userId = this.getUserId();
  // 检查是否已经有开始记录
  if (this.isUserStarted(taskAID)) {
    this.$message.warning(`您已经开始了任务`);
    return;
  }
  
  this.workStartLoading = true;
  try {
    // 记录开始时间到数据库
    const params = [];
    params.push(["TaskAID", taskAID]);
    params.push(["用户ID", userId]); // 用户ID参数
    params.push(["用户名", userName]); // 用户名参数
    params.push(["操作人", userName]); // 操作人参数
    
    const Data = this.CreateData("12", "MES_人员工时记录_开始", params);
    const response = await this.ExecDatabase(Data);
    
    if (response.data && response.data[0] && response.data[0].result === "1") {
      // 更新本地记录
      if (!this.userTimeRecords[taskAID]) {
        this.userTimeRecords[taskAID] = {};
      }
      this.userTimeRecords[taskAID][userName] = this.currentTime;
      
      this.$message.success("开始操作成功，已记录开始时间");
      this.searchTable();
      
      // 重新获取任务记录，确保数据一致性
      this.getUserTaskRecords();
    } else {
      this.$message.error("开始操作失败: " + (response.data[0]?.message || "未知错误"));
    }
  } catch (error) {
    this.$message.error("开始操作失败: " + error.message);
  } finally {
    this.workStartLoading = false;
  }
},

    // 结束按钮 - 记录人员结束时间
// 结束按钮 - 记录人员结束时间
async workEnd() {
  var row = this.selectedRow;
  if (!row) {
    this.$message.warning("请先选择一行数据");
    return;
  }
  
  const taskAID = row.TaskAID;
  const userName = this.getUserName();
  const userId = this.getUserId();
  
  // 检查是否有对应的开始记录
  const startTime = this.getUserStartTime(taskAID);
  if (!startTime) {
    this.$message.warning("请先开始此任务");
    return;
  }
  
  // 显示报工结束弹框
  this.workendData = row;
  this.workendVisible = true;
},

// 判断当前时间所属班次
determineShift(currentDateTime, shiftConfig) {
  // const current = this.timeToMinutes(currentDateTime);
  
  // for (const shift of shiftConfig) {
  //   const start = shift.开始时间.Hours * 60 + (shift.开始时间.Minutes || 0);
  //   const end = shift.结束时间.Hours * 60 + (shift.结束时间.Minutes || 0);
    
  //   // 白班：开始时间 < 结束时间
  //   if (current >= start && current <= end) {
  //     return shift;
  //   }
  // }
  return shiftConfig.find(item => item.班次名称 === "白班");
},
checkOvertime(currentDateTime, currentShift, shiftConfig) {
  if (!currentShift || !currentShift.结束时间) {
    return false;
  }
  
  // 将当前时间转换为Date对象
  const currentDate = new Date(currentDateTime.replace(' ', 'T'));
  
  // 获取班次结束时间并设置
  const endTimeObj = currentShift.结束时间;
  const shiftEndDate = new Date(currentDate);
  shiftEndDate.setHours(endTimeObj.Hours, endTimeObj.Minutes || 0, 0, 0);
  
  // 直接比较当前时间是否超过班次结束时间
  return currentDate > shiftEndDate;
},
// 将时间字符串转换为分钟数
timeToMinutes(dateTimeStr) {
  if (!dateTimeStr) return 0;
  
  // 如果是完整的日期时间字符串，提取时间部分
  if (dateTimeStr.includes(' ')) {
    const timePart = dateTimeStr.split(' ')[1]; // 获取 "15:39:11"
    const [hours, minutes] = timePart.split(':').map(Number);
    return hours * 60 + (minutes || 0);
  } 
  // 如果只有时间部分
  else {
    const [hours, minutes] = dateTimeStr.split(':').map(Number);
    return hours * 60 + (minutes || 0);
  }
},

// 显示加班人员选择对话框
showOvertimeDialog() {
  return new Promise((resolve, reject) => {
    // 计算加班时长
    const currentShift = this.currentShift;
    const timeSpan = this.calculateOvertimeHours(
      this.formatDateTime(this.currentTime), 
      currentShift.结束时间
    );
    this.overtimeHours = this.formatOvertimeHours(timeSpan);
    this.overtimeOptions = this.getOvertimePersonOptions();
    this.overtimePerson = '';
    this.overtimeResolve = resolve;
    this.overtimeReject = reject;
    this.overtimeDialogVisible = true;
  });
},

// 显示加班确认弹窗
showSimpleOvertimeDialog() {
  return new Promise((resolve, reject) => {
    // 设置默认值
    this.isOvertime = 0;  // 默认不加班
    this.selectedOption = '工作日';  // 默认工作日
    this.isRestDay = 0;
    this.isLegalRestDay = 0;
    this.overtimePerson = [this.getCurrentUser()];  // 默认加班人员为当前用户
    this.tsovertimePersons = [];  // 特殊加班人员默认为空
    this.shiftStandardHours = 8;  // 班次标准工时默认8小时
    // 加载加班人员选项
    this.overtimeOptions = this.getOvertimePersonOptions();
    
    this.overtimeResolve = resolve;
    this.overtimeReject = reject;
    this.overtimeDialogVisible = true;
  });
},

// 确认加班
confirmOvertime() {
  // 根据 selectedOption 设置 isRestDay 和 isLegalRestDay
  this.isRestDay = (this.selectedOption === '休息日' || this.selectedOption === '法定休息日') ? 1 : 0
  this.isLegalRestDay = (this.selectedOption === '法定休息日') ? 1 : 0
  
  // 如果选择加班，必须至少选择一种加班人员
  if (this.isOvertime === 1) {
    const hasOvertimePersons = this.overtimePerson && this.overtimePerson.length > 0
    const hasSpecialPersons = this.tsovertimePersons && this.tsovertimePersons.length > 0
    
    if (!hasOvertimePersons && !hasSpecialPersons) {
      this.$message.error('请至少选择一名加班人员或特殊加班人员');
      return;
    }
  }
  
  if (this.overtimeResolve) {
    // 合并所有加班人员（仅当选择加班时）
    let allPersons = []
    let ordinaryPersons = []
    let specialPersons = []
    
    if (this.isOvertime === 1) {
      ordinaryPersons = this.overtimePerson || []
      specialPersons = this.tsovertimePersons || []
      allPersons = [...ordinaryPersons]
      specialPersons.forEach(person => {
        if (!allPersons.includes(person)) {
          allPersons.push(person)
        }
      })
    }
    
    this.overtimeResolve({
      isOvertime: this.isOvertime,
      isRestDay: this.isRestDay,
      isLegalRestDay: this.isLegalRestDay,
      persons: allPersons,
      ordinaryPersons: ordinaryPersons,
      specialPersons: specialPersons,
      shiftStandardHours: this.shiftStandardHours || 8,
    });
  }
  
  this.overtimeDialogVisible = false;
  this.overtimeResolve = null;
  this.overtimeReject = null;
},
// 日期类型变化时的处理
onStatusChange(value) {
  this.isRestDay = (value === '休息日' || value === '法定休息日') ? 1 : 0
  this.isLegalRestDay = (value === '法定休息日') ? 1 : 0
},

// 是否加班变化时的处理
onOvertimeChange(value) {
  if (value === 0) {
    // 选择不加班时，清空加班人员
    this.overtimePerson = [];
    this.tsovertimePersons = [];
  }
},
handleOvertimeClose(done) {
  if (this.overtimeReject) {
    this.overtimeReject('cancel');
  }
  this.overtimeResolve = null;
  this.overtimeReject = null;
  done();
},

formatOvertimeHours(timeSpan) {
  console.log (timeSpan)
  if (timeSpan.TotalHours >= 1) {
    if (timeSpan.Minutes === 0) {
      return `${timeSpan.Hours}小时`;
    } else {
      return `${timeSpan.Hours}小时${timeSpan.Minutes}分钟`;
    }
  } else {
    return `${Math.round(timeSpan.TotalMinutes)}分钟`;
  }
},
// 获取加班人员选项
getOvertimePersonOptions() {
  // 这里可以从接口获取可加班人员列表
  // 暂时返回示例数据
  return [{ value: this.$store.state.user.name, label: this.$store.state.user.name }]
},

// 计算加班时长
calculateOvertimeHours(currentDateTime, shiftEndTime) {
  const current = new Date(currentDateTime.replace(' ', 'T'));
  const endTime = new Date(currentDateTime.replace(' ', 'T'));
  
  // 设置结束时间为班次结束时间
  endTime.setHours(shiftEndTime.Hours, shiftEndTime.Minutes || 0, 0);
  console.log(endTime,current)
  // 如果结束时间小于当前时间，说明可能是跨天班次，需要调整日期
  if (endTime < current) {
    // 如果是跨天班次，且当前时间在凌晨，结束时间应该是当天
    // 但如果当前时间是晚上，结束时间应该是第二天
    // 凌晨时段，结束时间是当天
      endTime.setDate(endTime.getDate());
    
  }
  console.log(endTime,current)
  const diffMs = current - endTime; // 毫秒差
  const diffMinutes = Math.floor(Math.abs(diffMs) / (1000 * 60));
  const hours = Math.floor(diffMinutes / 60);
  const minutes = diffMinutes % 60;
  console.log(Math.floor(hours / 24))
  console.log(hours)
  console.log(minutes)
  return {
    Days: Math.floor(hours / 24),
    Hours: hours % 24,
    Minutes: minutes,
    Seconds: 0,
    TotalHours: diffMinutes / 60,
    TotalMinutes: diffMinutes
  };
},

// 报工结束弹框确认
async workendForm() {
  try {
    var row = this.selectedRow;
    if (!row) {
      this.$message.warning("请先选择一行数据");
      return;
    }
    
    const taskAID = row.TaskAID;
    const userName = this.getUserName();
    const userId = this.getUserId();
    const startTime = this.getUserStartTime(taskAID);
    
    if (!startTime) {
      this.$message.warning("未找到开始记录，请先开始任务");
      return;
    }
    
    // 加班相关变量
    let overtimeResult = null
    let ordinaryPersons = ''
    let specialPersons = ''
    let isOvertime = 0
    let isRestDay = 0
    let isLegalRestDay = 0
    let shiftStandardHours = 8
    
    // 直接弹出加班确认弹窗
    try {
      overtimeResult = await this.showSimpleOvertimeDialog()
      
      if (overtimeResult) {
        isOvertime = overtimeResult.isOvertime || 0
        isRestDay = overtimeResult.isRestDay || 0
        isLegalRestDay = overtimeResult.isLegalRestDay || 0
        ordinaryPersons = overtimeResult.ordinaryPersons ? overtimeResult.ordinaryPersons.join(',') : ''
        specialPersons = overtimeResult.specialPersons ? overtimeResult.specialPersons.join(',') : ''
        shiftStandardHours = overtimeResult.shiftStandardHours || 8
      }
    } catch (error) {
      console.log('用户取消了加班弹框:', error)
      return
    }
    
    // 结束记录到数据库
    const params = [];
    params.push(["TaskAID", taskAID]);
    params.push(["用户ID", userId]);
    params.push(["用户名", userName]);
    params.push(["操作人", userName]);
    params.push(["备注", this.workendData.备注]);
    params.push(["工序说明", this.workendData.工序说明]);
    params.push(["异常说明", this.workendData.异常说明]);
    params.push(["本次检数", 0]);
    params.push(["是否加班", isOvertime]);
    params.push(["加班人员", ordinaryPersons]);
    params.push(["特殊加班人员", specialPersons]);
    params.push(["是否休息日", isRestDay]);
    params.push(["是否法定休息日", isLegalRestDay]);
    params.push(["班次标准工时", shiftStandardHours]);
    
    const Data6 = this.CreateData("12", "MES_人员工时记录_结束", params);
    const response = await this.ExecDatabase(Data6);
    
    if (response.data && response.data[0] && response.data[0].result === "1") {
      // 清除本地记录
      if (this.userTimeRecords[taskAID]) {
        delete this.userTimeRecords[taskAID][userName];
        if (Object.keys(this.userTimeRecords[taskAID]).length === 0) {
          delete this.userTimeRecords[taskAID];
        }
      }
      
      this.$message.success("结束操作成功，工时已记录");
      this.workendVisible = false;
      this.workendData = {};
      this.searchTable();
      
      // 重新获取任务记录
      this.getUserTaskRecords();
    } else {
      this.$message.error("结束操作失败: " + (response.data[0]?.message || "未知错误"));
    }
  } catch (error) {
    this.$message.error("结束操作失败: " + error.message);
  }
},

    // 暂停按钮
    // pause() {
    //   var row = this.selectedRow;
    //   if (!row) {
    //     this.$message.warning("请先选择一行数据");
    //     return;
    //   }
      
    //   const params = [];
    //   params.push(["TaskAID", row.TaskAID]);
    //   params.push(["optor", this.$store.state.user.name]);
    //   const Data = this.CreateData("12", "MES_ProductTask_Rest", params);
    //   this.ExecDatabase(Data)
    //     .then(() => {
    //       this.$message.success("暂停操作成功");
    //       this.searchTable();
    //     })
    //     .catch(() => {
    //       this.$message.error("保存失败");
    //     });
    // },

    // 送检按钮
    sendInspection() {
      var row = this.selectedRow;
      if (!row) {
        this.$message.warning("请先选择一行数据");
        return;
      }
      if(!this.assistNumber){
        this.$message.warning("请输入数量");
        return;
      }
      if(this.assistNumber>row.分配数 - row.完成数量){
        this.$message.warning("数量输入错误");
        return;
      }
      // 检查是否全部完成
      const isCompleted = parseInt(row.完成数量) == parseInt(row.分配数);
      
      const params = [];
      params.push(["TaskAID", row.TaskAID]);
      params.push(["optor", this.$store.state.user.name]);
      params.push(["recievCount", this.assistNumber]); // 送检剩余数量
      
      const Data = this.CreateData("12", "MES_ProductTask_SendInspection", params);
      this.ExecDatabase(Data)
        .then((response) => {
          if (response.data && response.data[0] && response.data[0].result === "1") {
            this.assistendVisible = false
            this.assistNumber = 0
            if (isCompleted) {
              this.$message.success("送检成功，任务已完成");
            } else {
              this.$message.success("送检成功，质检任务已生成");
            }
            this.searchTable();
          } else {
            this.$message.error("送检操作失败");
          }
        })
        .catch((error) => {
          this.$message.error("送检操作失败: " + error.message);
        });
    },

    sendCheck() {
      var row = this.selectedRow;
      console.log(row)
      if(row){
        this.assistendVisible = true
        this.assistendData.零件名称 = row.零件名称
        this.assistendData.订单号 = row.订单号
        this.assistendData.零件编码 = row.零件编码
        this.assistendData.工序名称 = row.工序名称
        this.assistendData.计划生产数 = row.分配数;
        this.assistendData.TaskAID = row.TaskAID;
        this.assistendData.指派对象 = row.指派对象;

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

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

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

      const data = this.CreateData(
        "12",
        "MES_QulityInspection_ReceiveCheck",
        param
      );

      this.ExecDatabase(data)
        .then((response) => {
          if (response.data[0].result === "1") {
            this.$message({
              message: "收检数据提交成功",
              type: "success",
            });
            this.receiveCheckVisible = false;
            this.searchTable(); // 刷新主表数据
          } else {
            this.$message({
              message: "收检数据提交失败：" + response.data[0].message,
              type: "error",
            });
          }
        })
        .catch((error) => {
          this.$message({
            message: "收检数据提交失败: " + error,
            type: "error",
          });
        });
    },

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

      var Data = this.CreateData("11", "加工中心_修改工时_保存修改记录", param);
      this.ExecDatabase(Data).then((response) => {
        this.$message.success("校验成功");
        this.editDialogVisible = false;
        this.abnormalTable();
      });
    },
    calculateWorkTime() {
      if (this.editForm.开始时间 && this.editForm.结束时间) {
        const start = new Date(this.editForm.开始时间);
        const end = new Date(this.editForm.结束时间);
        const diff = end.getTime() - start.getTime();
        this.editForm.加工工时 = Math.round(diff / 1000); // 转换为秒
      } else {
        this.editForm.加工工时 = 0;
      }
    },
    handleRowClick2(row) {
      this.currentTask = row;
    },
    getCurrentUser() {
      console.log(this);
      return this.$store.state.user.name;
    },
    abnormalForm() {
      this.abnormalVisible = false;
    },
    ReturnWarehouse(){
      this.ReturnWarehousepop = true
      var row = this.selectedRow;
      if(row == ''){
        return this.$message.error('请先选择任务')
      }
      var param = []
      param[0] = ['生产订单号',row.订单号]
      var Data = this.CreateData('11', '生产管理_加工中心_生产发料查询', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response)
        // this.ReturnWarehouseForm = response.data
        // this.ReturnWarehouseForm.forEach(element => {
        //   element.退库数量 = 0
        // });
        this.ReturnWarehouseForm = response.data.map(element => ({
          ...element,
          退库数量: 0
        }))
      })
    },
    async MaterialRequisition(){
      var row = this.selectedRow;
      console.log(row)
      if(row == ''){
         return this.$message.error('请先选择任务')
      }
      
      // var param = []
      // param[0] = ['编码',row.零件编码]
      var result = await getB1("/ProductionOrders",{"$filter":"AbsoluteEntry eq "+this.selectedRow.订单号})
      if (result.success) {
        console.log('请求成功');
        console.log('数据:', result.data); // ✅ 这就是你要的数据

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

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

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

      return result;
    },
        handleInspectionCountChange(count) {
      if (count > 0) {
        // 初始化检测数据数组
        this.inspectionData = [];
        for (let i = 0; i < count; i++) {
          // 为每个检测项创建副本
          this.inspectionData.push(
            JSON.parse(JSON.stringify(this.tableData2)).map((item) => {
              return {
                ...item,
                检测结果: "1", // 默认选中"合格"
                实测值: "",
              };
            })
          );
        }
        this.currentPage = 1; // 重置到第一页
      } else {
        this.inspectionData = [];
      }
    },
    // 获取当前页的数据
    getCurrentPageData() {
      const pageIndex = this.currentPage - 1;

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

        return this.inspectionData[pageIndex];
      }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return newItem;
          });

          this.inspectionData.push(pageData);
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  }
};
</script>

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

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

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

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

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

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

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

.grid-btn-disabled {
  cursor: not-allowed;
  opacity: 0.65;
  box-shadow: none;
  pointer-events: none;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

::v-deep .el-checkbox__label {
    display: inline-block;
    padding-left: 10px;
    line-height: 16px;
    font-size: 14px;
    font-weight: bold;
    margin-top: 10px;
}
</style>
