<template>
  <div>
    <el-card>
      <div>
        <el-menu mode="horizontal" :default-active="activeIndex" router>
          <!-- <el-menu-item index="/QualityManagement/CheckTask/firstSpecial"
            >首检专检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/processSpecial"
            >序检专检</el-menu-item
          > -->
          <el-menu-item index="/QualityManagement/CheckTask/final"
            >终检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/purchaseIncoming"
            >采购入库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/salesReturn"
            >销售退货检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/materialReturn"
            >原材料退库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/OtherInbound"
            >其他入库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/processReceive"
            >序检收检</el-menu-item
          >
        </el-menu>
      </div>
    </el-card>
    <el-card>
      <div class="search-container" @keyup.enter="searchTable">
        <span class="show-text">生产订单:</span>
        <el-input
          v-model="orderNo"
          placeholder="请输入生产订单"
          clearable
          style="width: 150px; margin-right: 10px"
          @click="searchTable()"
        />
        <span class="show-text">销售订单:</span>
        <el-input
          v-model="contractNo"
          placeholder="请输入销售订单"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">物料名称:</span>
        <el-input
          v-model="partName"
          placeholder="请输入物料名称"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">物料编码:</span>
        <el-input
          v-model="partNo"
          placeholder="请输入物料编号"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <!-- <span class="show-text">检测日期:</span>
        <el-date-picker
          v-model="inspectionDate"
          :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-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"
        /> -->

        <!-- <br />
        <br /> -->
        <span class="show-text">属性</span>
        <el-select
          v-model="attribute"
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option label="装配" value="2" />
          <el-option label="机加" value="1" />
          <el-option label="全部" value="0" />
        </el-select>
        <span class="show-text">检测结果</span>
        <el-select
          v-model="inspectionResult"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option label="合格" value="1" />
          <el-option label="不合格" value="0" />
        </el-select>
        <span class="show-text">检测人:</span>
        <el-select
          v-model="checker"
          placeholder="请选择检测人"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in checkerList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span class="show-text">检测状态</span>
        <el-select
          v-model="checkstatus"
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option label="全部" value="2" />
          <el-option label="已完成" value="1" />
          <el-option label="未完成" value="0" />
        </el-select>
        <!--  <span class="show-text">检测类别:</span>
        <el-select
          v-model="type"
          placeholder="请选择检测类别"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <el-button
          :disabled="loading"
          icon="el-icon-search"
          plain
          type="primary"
          @click="searchTable()"
          >查询
        </el-button>
        <!-- <el-button
          type="success"
          icon="el-icon-download"
          plain
          :disabled="tableData.length === 0"
          @click="exportToExcel"
          >导出</el-button
        > -->
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        :height="'67vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="50"
          fixed
        />
        <el-table-column
          align="center"
          label="销售订单"
          width="100"
          prop="合同号"
        />
        <el-table-column
          align="center"
          label="生产订单"
          width="100"
          prop="计划号"
        />
        <el-table-column
          align="center"
          label="物料名称"
          width="100"
          prop="零件名称"
        />
        <el-table-column
          align="center"
          label="物料编码"
          width="100"
          prop="零件编码"
        />
        <el-table-column
          align="center"
          label="工序名称"
          width="80"
          prop="工序名称"
        />
        <el-table-column
          align="center"
          label="工位名称"
          width="80"
          prop="工位名称"
        />

        <el-table-column
            align="center"
            label="加急数量"
            width=" 120"
          >
            <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"
          label="完成数量"
          width="100"
          prop="完成数量"
        />
        <el-table-column
          align="center"
          label="检验数量"
          width="120"
          prop="检验数量"
        />
        <el-table-column
          align="center"
          label="检验合格数量"
          width="110"
          prop="合格数"
        />
        <el-table-column
          align="center"
          label="检验不合格数量"
          width="120"
          prop="不合格数"
        />
        <el-table-column
          align="center"
          label="检验操作人"
          width="130"
          prop="检测人"
        />

        <el-table-column
          align="center"
          label="检验时间"
          width="180"
          prop="检测时间"
        />
        <el-table-column
          align="center"
          label="检测说明"
          width="180"
          prop="检测说明"
        />
        <el-table-column
          align="center"
          label="供应商"
          width="80"
          prop="供应商"
        />
        <el-table-column
          align="center"
          label="采购收货单"
          width="100"
          prop="采购收货单"
        />
        <el-table-column label="操作" align="center" width="350" fixed="right">
          <template slot-scope="scope">
            <el-button
              class="operation-btn"
              type="primary"
              size="mini"
              @click="receiveCheck(scope.row)"
              >收检</el-button
            >
            <el-button
              class="operation-btn"
              type="primary"
              size="mini"
              @click="getitemdraw(scope.row)"
              >零件图纸</el-button
            >
            <el-button
              class="operation-btn"
              type="primary"
              size="mini"
              @click="getitemdraw2(scope.row)"
              >工艺图纸</el-button
            >
          </template>

        </el-table-column>
      </el-table>
    </el-card>

    <!-- 收检对话框 -->
    <el-dialog
      title="收检"
      :visible.sync="receiveCheckVisible"
      width="60%"
      style="text-align: center"
    >
      <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>
        <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>
        <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>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 送检数量</span>
              <el-input-number
                v-model="receiveCheckData.检测数量"
                size="mini"
                :min="0"
                :max="receiveCheckData.完成数量 -  receiveCheckData.已检验数量"
                style="width: 200px"
                @change="handleQualifiedChange2"
              />
              <!-- <span class="info-value">{{ receiveCheckData.完成数量 - receiveCheckData.检测数量 }}</span> -->
            </div>
            <div class="info-item">
              <span class="info-label"> 合格数</span>
              <span class="info-value">{{ receiveCheckData.检测数量 - receiveCheckData.不合格数 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 不合格数</span>
              <el-input-number
                v-model="receiveCheckData.不合格数"
                size="mini"
                :min="0"
                :max="receiveCheckData.检测数量 "
                style="width: 200px"
                @change="handleQualifiedChange"
              />

            </div>
            <div class="info-item">
              <span class="info-label"> 检验人</span>
              <el-select
                v-model="receiveCheckData.检测人"
                placeholder="请选择检验人"
                clearable
                style="width: 200px"
                filterable
              >
                <el-option
                  v-for="item in checkerList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 检验时间</span>

              <el-date-picker
                v-model="receiveCheckData.检测时间"
                type="datetime"
                placeholder="选择检验时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 120px"
                class="info-value"
              />
            </div>
            <div class="info-item">
              <span class="info-label"> 放行数量</span>

              <el-input
                v-model="receiveCheckData.放行数量"
                type="number"
                style="width: 120px"
                class="info-value"
              />
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 检测说明</span>

              <el-input
                v-model="receiveCheckData.检测说明"
                type="textarea"
                :rows="2"
                placeholder="请输入检测说明"
                style="width: 120px"
                class="info-value"
              />
            </div>
          </div>
        </div>
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="confirmReceiveCheck" :loading="submitLoading"
    :disabled="submitLoading">确 定</el-button>
        <el-button @click="receiveCheckVisible = false" :disabled="submitLoading">取 消</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 :visible.sync="seeVisible" title="图纸" center width="1200px" overflow="scroll" >
        <div id="el-dialog__body" style="min-height: 500px;"></div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="seeVisible = false">关闭</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
// 引入xlsx库
import * as XLSX from "xlsx";
import { postB1 } from '@/api/b1s';
import { getB1 } from '@/api/b1s';
import { seepdf, initPDFKeyboardShortcuts, setZoom } from '@/utils/pdf';
import { MESDownFile } from '@/utils/request'
export default {
  data() {
    return {
      contractNo: "",
      orderNo: "",
      partNo: "",
      partName: "",
      completionTime: "",
      inspectionDate: "",
      type: "",
      typeList: [],
      checker: "",
      checkerLabel: "",
      checkerList: [],
      inspectionResult: "",
      tableData: [],
      loading: false,
      selectedRow: null,
      receiveCheckVisible: false,
      receiveCheckData: {
        // 基本信息（从行数据获取）
        零件名称: "",
        内部合同号: "",
        零件编码: "",
        计划号: "",
        工序名称: "",
        计划完成时间: "",
        计划生产数: 0,
        TaskAID: "",

        // 收检数据（用户输入）
        检测人: "",
        检测时间: "",
        检测说明: "",
      },
      checkstatus:'0',
      attribute:'0',
      UrgentVisible: false,
      Urgentarr: {},
      seeVisible:false,
      downPDF:MESDownFile,
      submitLoading: false,
    };
  },
  created() {
    this.getTypeList();
    this.getCheckerList();
    this.searchTable();
  },
  computed: {
    activeIndex() {
      return this.$route.path;
    },
  },
  methods: {
    getitemdraw(row) {
      var param = [];
      param[0] = ['物料编号', row.零件编码];
      var Data = this.CreateData('11', '工艺管理_图纸维护_查看图纸', param);
      this.ExecDatabase(Data).then(response => {
          console.log(response)
          if (response.data.length > 0) {
            var pdfSrc =""+this.downPDF+""+ response.data[0].uid+".pdf"

            window.open(pdfSrc,'_blank')
          }else {
            this.$message.error('未上传图纸');
          }
        })

    },
    getitemdraw2(row) {
      var param = [];
      param[0] = ['物料编号', row.零件编码];
      var Data = this.CreateData('11', '工艺管理_工艺维护_查看图纸', param);
      this.ExecDatabase(Data).then(response => {
          console.log(response)
          if (response.data.length > 0) {
            var pdfSrc =""+this.downPDF+""+ response.data[0].uid+".pdf"

            window.open(pdfSrc,'_blank')
          }else {
            this.$message.error('未上传图纸');
          }
        })

    },
    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
      });
    },
    getTypeList() {
      this.typeList = [];
      var Data = this.CreateData("11", "查询字典");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          if (response.data[i].数据类别 === "检测类型") {
            this.typeList.push({
              label: response.data[i].词条名称,
              value: response.data[i].词条编号,
            });
          }
        }
      });
    },
    getCheckerList() {
      this.checkerList = [];
      var Data = this.CreateData("11", "人员管理_人员信息查询_质检部门_查询");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.checkerList.push({
            label: response.data[i].Personnel_Name,
            value: response.data[i].Personnel_Number,
          });
        }
      });
    },
    tableRowClassName({ row, rowIndex }) {
      console.log(row.加急状态)
      const isUrgent =  row.加急状态 === 1 ;
      if (isUrgent) {
        return 'priority-row';
      }
      return '';
    },
    searchTable() {
      // 开始加载状态，清空表格数据和选中行
      this.loading = true;
      this.tableData = [];

      // 构建基础查询参数
      var param = [];
      param.push(["合同号", this.contractNo]);
      param.push(["订单号", this.orderNo]);
      param.push(["零件编号", this.partNo]);
      param.push(["零件名称", this.partName]);
      // 添加完工日期范围参数
      param.push([
        "完工日期_Start",
        this.completionTime ? this.completionTime[0] : "",
      ]);
      param.push([
        "完工日期_End",
        this.completionTime ? this.completionTime[1] : "",
      ]);
      // 添加检测日期范围参数
      param.push([
        "检测日期_Start",
        this.inspectionDate ? this.inspectionDate[0] : "",
      ]);
      param.push([
        "检测日期_End",
        this.inspectionDate ? this.inspectionDate[1] : "",
      ]);
      param.push(["检测结果", this.inspectionResult]);
      const selectedChecker = this.checkerList.find(
        (item) => item.value === this.checker
      );
      param.push(["检测人", selectedChecker ? selectedChecker.label : ""]);
      param.push(["检测类别", this.type]);
      param.push(["检测状态", this.checkstatus]);
      param.push(["属性", this.attribute]);

      // 调用封装方法生成请求数据 - 使用新的存储过程名称
      var Data = this.CreateData(
        "11",
        "质量管理_质量检验_收检记录_查询",
        param
      );

      // 执行数据库请求
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          console.log(response.data);
          if (response.data && response.data.length !== 0) {
            this.tableData = response.data;
            this.tableData.sort((a, b) => {
              const aIsUrgent = a.加急状态 === 1;
              const bIsUrgent = b.加急状态 === 1;

              if (aIsUrgent && !bIsUrgent) return -1;
              if (!aIsUrgent && bIsUrgent) return 1;
            })
          } else {
            this.tableData = [];
            this.$message.info("未查询到相关数据");
          }
        })
        .catch((error) => {
          this.loading = false;
          console.error("查询失败:", error);
          this.$message.error("查询失败");
        });
    },

    receiveCheck(row) {
      // 打开收检对话框并填充数据
      this.receiveCheckVisible = true;

      // 从行数据填充基本信息
      this.receiveCheckData = {
        // 基本信息（从行数据获取）
        零件名称: row.零件名称 || "",
        内部合同号: row.内部合同号 || "",
        零件编码: row.零件编码 || "",
        计划号: row.计划号 || "",
        工序名称: row.工序名称 || "",
        计划生产数: row.计划生产数 || 0,
        TaskAID: row.TaskAID || "",
        已检验数量 : row.检验数量 || 0,
        // 收检数据（用户输入）
        检测数量: row.完成数量 - row.检验数量 || 0,
        完成数量: row.完成数量 || 0,
        合格数: row.完成数量 - row.检验数量||0,
        不合格数:  0,
        检测人: row.检测人 || "",
        检测时间: this.formatDateTime(new Date()),
        检测说明: "",
        工位名称: row.工位名称 || "",
      };
      console.log(this.receiveCheckData);
    },

    handleQualifiedChange(value) {
      // 自动计算不合格数
      this.receiveCheckData.合格数 = this.receiveCheckData.检测数量 - value;
    },
    handleQualifiedChange2(value) {
      // 自动计算不合格数
      this.receiveCheckData.合格数 = value - this.receiveCheckData.不合格数;
    },
    confirmReceiveCheck() {
      // 验证表单
      if (this.submitLoading) {
        this.$message.warning('正在提交中，请勿重复操作');
        return;
      }
      if (
        this.receiveCheckData.完成数量-this.receiveCheckData.检测数量 < 0
      ) {
        this.$message.warning("请输入有效的检测数量");
        return;
      }

      if (!this.receiveCheckData.检测人) {
        this.$message.warning("请选择检验人");
        return;
      }

      if (!this.receiveCheckData.检测时间) {
        this.$message.warning("请选择检验时间");
        return;
      }
      console.log(this.receiveCheckData.检测数量, this.receiveCheckData.合格数 , this.receiveCheckData.不合格数)
      if (this.receiveCheckData.检测数量 != this.receiveCheckData.合格数 + this.receiveCheckData.不合格数) {
        this.$message.warning("数量输入错误");
        return;
      }

      // 调用存储过程保存数据
      this.saveReceiveCheck();
    },
    async saveReceiveCheck() {
  // 设置提交状态为true，防止重复提交
  this.submitLoading = true;

  var 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.放行数量]);
  param.push(["工位名称", this.receiveCheckData.工位名称]);
  console.log(param);

  try {
    if(this.receiveCheckData.工位名称 == '外协' && this.receiveCheckData.合格数 > 0){
      var result = await postB1("/QueryService_PostQuery",{
        "QueryPath": "$crossjoin(PurchaseOrders,PurchaseOrders/DocumentLines)",
        "QueryOption": "$expand=PurchaseOrders($select=DocEntry, DocNum,CardCode,CardName),PurchaseOrders/DocumentLines($select=ItemCode,LineNum,Price,U_WWOworID,U_WWOrstHS,LineStatus)&$filter=PurchaseOrders/DocEntry eq PurchaseOrders/DocumentLines/DocEntry and PurchaseOrders/DocumentLines/U_WWOworID eq "+this.receiveCheckData.计划号+""
      })
      if (result.success) {
        if(result.data.value.length>0){
          let processed = false;
          let failedElement = null;
          for (const element of result.data.value) {
            console.log(this.receiveCheckData.工序名称)
            console.log(element['PurchaseOrders/DocumentLines'].U_WWOrstHS)
            console.log(element['PurchaseOrders/DocumentLines'].LineStatus)
            // console.log(this.receiveCheckData.合格数 <= element['PurchaseOrders/DocumentLines'].RemainingOpenQuantity)

            if( this.receiveCheckData.工序名称 == element['PurchaseOrders/DocumentLines'].U_WWOrstHS && element['PurchaseOrders/DocumentLines'].LineStatus == 'O'){
              var CardCode = element.PurchaseOrders.CardCode
              var CardName = element.PurchaseOrders.Cardname
              var DocEntry = element.PurchaseOrders.DocEntry
              var LineNum = element['PurchaseOrders/DocumentLines'].LineNum

              // 创建采购收货单
              const deliveryResult = await postB1(
                "/PurchaseDeliveryNotes",
                {
                  "CardCode" : CardCode,
                  "CardName" : CardName,
                  "DocDate" : this.formatDate(this.receiveCheckData.检测时间),
                  "DocumentLines": [
                      {
                        "BaseEntry" : DocEntry,
                        "BaseLine"  : LineNum,
                        "BaseType"  : 22,
                        "Quantity"  : this.receiveCheckData.合格数,
                        "U_WWPassedQty"  : this.receiveCheckData.不合格数,
                      }
                  ]
                }
              )
              console.log(deliveryResult.data.DocEntry,deliveryResult)
              if (deliveryResult.data.DocEntry) {
                processed = true;
                break;
              }else{
                failedElement = element; // 记录创建失败的element
                break;
              }
            }
          }
          if (!processed) {
            const errorElement = failedElement || (result.data.value.length > 0 ? result.data.value[0] : null);

            if (errorElement) {
              const docEntry = errorElement['PurchaseOrders'].DocEntry;
              const processName = errorElement['PurchaseOrders/DocumentLines'].U_WWOrstHS;
              const lineStatus = errorElement['PurchaseOrders/DocumentLines'].LineStatus;
              const state = lineStatus == 'O' ? '正常' : '已入库'; // 给个更明确的状态显示
              if(this.receiveCheckData.工序名称 === processName){
                this.$message.error(`SAP单据号:${docEntry}, 工序名称:${processName}, 状态:${state}`);
              }else{
                this.$message.error('质检失败:外协采购订单未创建');
              }
            } else {
              this.$message.error('外协采购订单创建失败');
            }
            return
          }
        } else {
          this.$message.error('质检失败:外协采购订单未创建');
          this.submitLoading = false;
          return;
        }
      } else {
        throw new Error('外协订单查询失败');
      }
    }

    // 执行收检操作
    var Data = this.CreateData("12", "质量管理_序检收检_新增", param);
    const response = await this.ExecDatabase(Data);

    if (
      response.data &&
      response.data[0] &&
      response.data[0].result === "1"
    ) {
      this.$message.success("收检操作成功");
      this.receiveCheckVisible = false;
      // 刷新表格数据
      await this.searchTable();
    } else {
      throw new Error("收检操作失败");
    }
  } catch (error) {
    console.error("收检操作失败:", error);
    this.$message.error("收检操作失败: " + (error.message || '未知错误'));
  } finally {
    // 无论成功或失败，都要重置提交状态
    console.log(111)
    this.submitLoading = false;
  }
},
    // async saveReceiveCheck() {
    //   // 设置提交状态为true，防止重复提交
    //   this.submitLoading = true;
    //   var 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.放行数量]);
    //   console.log(param);
    //   if(this.receiveCheckData.工位名称 == '外协'){
    //     var result = await postB1("/QueryService_PostQuery",{
    //       "QueryPath": "$crossjoin(PurchaseOrders,PurchaseOrders/DocumentLines)",
    //       "QueryOption": "$expand=PurchaseOrders($select=DocEntry, DocNum,CardCode,CardName),PurchaseOrders/DocumentLines($select=ItemCode,LineNum,Price,U_WWOworID,U_WWOrstHS,LineStatus)&$filter=PurchaseOrders/DocEntry eq PurchaseOrders/DocumentLines/DocEntry and PurchaseOrders/DocumentLines/U_WWOworID eq "+this.receiveCheckData.计划号+""
    //     })
    //   }else{
    //     var Data = this.CreateData("12", "质量管理_序检收检_新增", param);
    //     this.ExecDatabase(Data)
    //       .then((response) => {
    //         if (
    //           response.data &&
    //           response.data[0] &&
    //           response.data[0].result === "1"
    //         ) {
    //           this.$message.success("收检操作成功");
    //           this.receiveCheckVisible = false;
    //           // 刷新表格数据
    //           this.searchTable();
    //         } else {
    //           this.$message.error("收检操作失败");
    //         }
    //       })
    //       .catch((error) => {
    //         console.error("收检操作失败:", error);
    //         this.$message.error("收检操作失败");
    //       });
    //   }
    //   if (result.success) {
    //     if(result.data.value.length>0){
    //       result.data.value.forEach(element => {
    //         console.log(this.receiveCheckData.工序名称)
    //         console.log(element['PurchaseOrders/DocumentLines'].U_WWOrstHS)
    //         console.log(element['PurchaseOrders/DocumentLines'].LineStatus)
    //         console.log(this.receiveCheckData.工序名称 == element['PurchaseOrders/DocumentLines'].U_WWOrstHS & element['PurchaseOrders/DocumentLines'].LineStatus == 'O')
    //         if( this.receiveCheckData.工序名称 == element['PurchaseOrders/DocumentLines'].U_WWOrstHS & element['PurchaseOrders/DocumentLines'].LineStatus == 'O' ){
    //           var CardCode = element.PurchaseOrders.CardCode
    //           var CardName = element.PurchaseOrders.Cardname
    //           var DocEntry = element.PurchaseOrders.DocEntry
    //           var LineNum = element['PurchaseOrders/DocumentLines'].LineNum
    //           postB1(
    //             "/PurchaseDeliveryNotes",
    //             {
    //               "CardCode" : CardCode,
    //               "CardName" : CardName,
    //               "DocDate" : this.formatDate(this.receiveCheckData.检测时间),
    //               "DocumentLines": [
    //                   {
    //                     "BaseEntry" : DocEntry,
    //                     "BaseLine"  : LineNum,
    //                     "BaseType"  : 22,
    //                     "Quantity"  : this.receiveCheckData.合格数,
    //                     "U_WWPassedQty"  : this.receiveCheckData.不合格数,
    //                   }
    //               ]
    //             }
    //           )
    //           var Data = this.CreateData("12", "质量管理_序检收检_新增", param);
    //           this.ExecDatabase(Data)
    //             .then((response) => {
    //               if (
    //                 response.data &&
    //                 response.data[0] &&
    //                 response.data[0].result === "1"
    //               ) {
    //                 this.$message.success("收检操作成功");
    //                 this.receiveCheckVisible = false;
    //                 // 刷新表格数据
    //                 this.searchTable();
    //               } else {
    //                 this.$message.error("收检操作失败");
    //               }
    //             })
    //             .catch((error) => {
    //               console.error("收检操作失败:", error);
    //               this.$message.error("收检操作失败");
    //             });
    //         }
    //       });


    //     } else {
    //       this.$message.error('质检失败:外协采购订单未创建');
    //     }

    //   }

    // },

    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 导出Excel功能
    exportToExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning("没有数据可导出");
        return;
      }

      try {
        // 准备导出数据
        const exportData = this.tableData.map((item, index) => {
          return {
            序号: index + 1,
            合同号: item.内部合同号 || "",
            订单编号: item.计划号 || "",
            零件名称: item.零件名称 || "",
            零件编码: item.零件编码 || "",
            工序名称: item.工序名称 || "",
            计划生产数: item.计划生产数 || 0,
            检验数量: item.检验数量 || 0,
            检验合格数量: item.合格数 || 0,
            检验不合格数量: item.不合格数 || 0,
            检验操作人: item.检测人 || "",
            检验时间: item.检测时间 || "",
          };
        });

        // 创建工作簿
        const wb = XLSX.utils.book_new();

        // 创建工作表
        const ws = XLSX.utils.json_to_sheet(exportData);

        // 设置列宽
        const colWidth = [
          { wch: 8 }, // 序号
          { wch: 15 }, // 合同号
          { wch: 15 }, // 订单编号
          { wch: 20 }, // 零件名称
          { wch: 15 }, // 零件编码
          { wch: 12 }, // 工序名称
          { wch: 12 }, // 计划生产数
          { wch: 10 }, // 检验数量
          { wch: 15 }, // 检验合格数量
          { wch: 15 }, // 检验不合格数量
          { wch: 12 }, // 检验操作人
          { wch: 20 }, // 检验时间
        ];
        ws["!cols"] = colWidth;

        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "序检收检记录");

        // 生成文件名（包含当前时间）
        const fileName = `序检收检记录_${this.formatDateForFileName(
          new Date()
        )}.xlsx`;

        // 导出文件
        XLSX.writeFile(wb, fileName);

        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败");
      }
    },
    formatDate(date) {
      if (!date) return "";
      return date.split(" ").length > 1 ? date.split(" ")[0] : date;
    },
    // 格式化日期用于文件名
    formatDateForFileName(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}${month}${day}_${hours}${minutes}${seconds}`;
    },
  },
};
</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;
}
</style>
<style >
::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;
}
.search-container {
  margin-bottom: 20px;
}
.show-text {
  margin-right: 5px;
  line-height: 32px;
}
.operation-cell {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.operation-btn {
  flex: 1;
  margin: 0 5px;
  padding: 0;
  min-width: 0;
}
.active {
  color: skyblue;
  margin-left: 5px;
}

.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;
}
</style>
