<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="contractNo"
          placeholder="请输入销售订单"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">生产订单:</span>
        <el-input
          v-model="orderNo"
          placeholder="请输入生产订单"
          clearable
          style="width: 150px; margin-right: 10px"
          @change = 'searchTable()'
        />
        <span class="show-text">物料编码:</span>
        <el-input
          v-model="partNo"
          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-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-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-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-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="checkstatus"
          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>
        <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="150"
          prop="零件名称"
        />
        <el-table-column
          align="center"
          label="物料编码"
          width="150"
          prop="零件编码"
        />
        <el-table-column
          align="center"
          label="工序名称"
          width="120"
          prop="工序名称"
        />

        <!-- <el-table-column
          align="center"
          label="计划生产数"
          width="100"
          prop="计划生产数"
        /> -->
        <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"
          label="收检数量"
          width="120"
          prop="检验数量"
        />
        <el-table-column
          align="center"
          label="收检合格数量"
          width="110"
          prop="检验数量_6"
        >
          <template slot-scope="scope">
            {{ scope.row.检验数量_6 - scope.row.不合格数 }}
          </template>
        </el-table-column>
        <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 label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button
              class="operation-btn"
              type="primary"
              size="mini"
              @click="finalCheck(scope.row)"
              >终检</el-button
            >
            <el-button
              class="operation-btn"
              type="success"
              size="mini"
              @click="showFinalCheckHistory(scope.row)"
              >终检记录</el-button
            >
            <!-- <el-button
              class="operation-btn"
              type="primary"
              size="mini"
              @click="Urgent(scope.row)"
              >加急明细</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 终检对话框 -->
    <el-dialog
      title="终检"
      :visible.sync="finalCheckVisible"
      width="60%"
      style="text-align: center"
    >
      <el-form
        ref="finalCheckForm"
        :model="finalCheckData"
        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">{{ finalCheckData.零件名称 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">销售订单</span>
              <span class="info-value">{{ finalCheckData.内部合同号 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">零件编码</span>
              <span class="info-value">{{ finalCheckData.零件编码 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">生产订单</span>
              <span class="info-value">{{ finalCheckData.计划号 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">工序名称</span>
              <span class="info-value">{{ finalCheckData.工序名称 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">已检测数量</span>
              <span class="info-value">{{ finalCheckData.检验数量_8 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 检测数量</span>
              <el-input-number
                v-model="finalCheckData.检测数量"
                size="mini"
                style="width: 200px"
                @change="handleInspectionQuantityChange"
              />
            </div>
            <div class="info-item">
              <span class="info-label"> 合格数</span>
              <span class="info-value">{{ finalCheckData.检测数量 - finalCheckData.不合格数 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 不合格数</span>
              <el-input-number
                v-model="finalCheckData.不合格数"
                size="mini"
                :min="0"
                :max="finalCheckData.检测数量"
                style="width: 200px"
                @change="handleQualifiedChange"
              />
              <!-- <span class="info-value">{{ finalCheckData.不合格数 }}</span> -->
            </div>
            <div class="info-item">
              <span class="info-label"> 检验人</span>
              <el-select
                v-model="finalCheckData.检测人"
                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="finalCheckData.检测时间"
                type="datetime"
                placeholder="选择检验时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 200px"
                class="info-value"
              />
            </div>
            <div class="info-item">
              <span class="info-label"> 放行数量</span>
              <el-input
                v-model="finalCheckData.放行数量"
                type="number"
                style="width: 200px"
                class="info-value"
              />
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 检测说明</span>
              <el-input
                v-model="finalCheckData.检测说明"
                type="textarea"
                :rows="2"
                placeholder="请输入检测说明"
                style="width: 200px"
                class="info-value"
              />
            </div>
          </div>
        </div>
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="saveFinalCheck" :loading="saveLoading" :disabled="saveLoading">{{ saveLoading ? '保存中...' : '确 定' }}</el-button>
        <el-button @click="finalCheckVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 终检记录对话框 -->
    <el-dialog
      title="终检记录"
      :visible.sync="finalCheckHistoryVisible"
      width="90%"
    >
      <el-table
        :data="finalCheckHistoryData"
        border
        size="mini"
        style="width: 100%"
        v-loading="historyLoading"
      >
        <el-table-column align="center" label="序号" type="index" width="50" />
        <el-table-column
          align="center"
          label="销售订单"
          prop="内部合同号"
          width="120"
        />
        <el-table-column
          align="center"
          label="生产订单"
          prop="计划号"
          width="120"
        />
        <el-table-column
          align="center"
          label="物料名称"
          prop="零件名称"
          width="150"
        />
        <el-table-column
          align="center"
          label="零件编码"
          prop="物料编码"
          width="120"
        />
        <el-table-column
          align="center"
          label="工序名称"
          prop="工序名称"
          width="120"
        />
        <!-- <el-table-column
          align="center"
          label="计划生产数"
          prop="计划生产数"
          width="100"
        /> -->
        <el-table-column
          align="center"
          label="送检数量"
          prop="检验数量"
          width="100"
        />
        <el-table-column
          align="center"
          label="合格数"
          prop="合格数"
          width="100"
        />
        <el-table-column
          align="center"
          label="不合格数"
          prop="不合格数"
          width="100"
        />
        <el-table-column
          align="center"
          label="检测人"
          prop="检测人"
          width="120"
        />
        <el-table-column
          align="center"
          label="检测时间"
          prop="检测时间"
          width="180"
        />
        <el-table-column
          align="center"
          label="检测说明"
          prop="检测说明"
          show-overflow-tooltip
        />
      </el-table>
    </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>
  </div>
</template>

<script>
// 引入xlsx库
import * as XLSX from "xlsx";
import {getB1} from '@/api/b1s'
import {patchB1} from '@/api/b1s'
export default {
  data() {
    return {
      saveLoading: false,
      contractNo: "",
      orderNo: "",
      partNo: "",
      partName: "",
      completionTime: "",
      inspectionDate: "",
      type: "",
      typeList: [],
      checker: "",
      checkerLabel: "",
      checkerList: [],
      inspectionResult: "",
      tableData: [],
      loading: false,
      historyLoading: false, // 终检记录加载状态
      selectedRow: null,
      finalCheckVisible: false,
      finalCheckHistoryVisible: false,
      finalCheckHistoryData: [],
      finalCheckData: {
        零件名称: "",
        内部合同号: "",
        零件编码: "",
        计划号: "",
        工序名称: "",
        计划完成时间: "",
        // 计划生产数: 0,
        TaskAID: "",

        // 终检数据（用户输入）
        检测数量: 0,
        合格数: 0,
        不合格数: 0,
        检测人: "",
        检测时间: "",
        检测说明: "",
      },
      checkstatus:"0",
      attribute:'0',
      UrgentVisible: false,
      Urgentarr: {}
    };
  },
  created() {
    this.getTypeList();
    this.getCheckerList();
    this.searchTable();
    // var now = new Date();
    // var start = new Date(
    //   Date.UTC(now.getFullYear() , now.getMonth(), now.getDate())
    // )
    //   .toISOString()
    //   .replace("T", " ")
    //   .replace(".000Z", "");
    // var end = new Date(
    //   Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
    // )
    //   .toISOString()
    //   .replace("T", " ")
    //   .replace(".000Z", "");
    // this.completionTime= [start, end];
  },
  computed: {
    activeIndex() {
      return this.$route.path;
    },
  },
  methods: {
    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 }) {
      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] : "",
      ]);

      console.log("检测结果参数:", this.inspectionResult);
      param.push(["检测结果", this.inspectionResult]);

      const selectedChecker = this.checkerList.find(
        (item) => item.value === this.checker
      );
      param.push(["检测人", selectedChecker ? selectedChecker.label : ""]);
      param.push(["检验状态",this.checkstatus]);
      param.push(["属性",this.attribute]);
      console.log("查询参数:", param);

      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;
            })
            const qualifiedCount = this.tableData.filter(
              (item) => item.检测状态 === 1
            ).length;
            const unqualifiedCount = this.tableData.filter(
              (item) => item.检测状态 === 2
            ).length;
            const uncheckedCount = this.tableData.filter(
              (item) => item.检测状态 === 0
            ).length;
            console.log(
              `统计: 合格${qualifiedCount}条, 不合格${unqualifiedCount}条, 未检测${uncheckedCount}条`
            );
          } else {
            this.tableData = [];
            this.$message.info("未查询到相关数据");
          }
        })
        .catch((error) => {
          this.loading = false;
          console.error("查询失败:", error);
          this.$message.error("查询失败");
        });
    },

    finalCheck(row) {
      this.finalCheckVisible = true;
      console.log(row.检测数量 , row.不合格数)
      // 每次终检都重置数据，允许新增记录
      this.finalCheckData = {
        零件名称: row.零件名称 || "",
        内部合同号: row.内部合同号 || "",
        零件编码: row.零件编码 || "",
        计划号: row.计划号 || "",
        工序名称: row.工序名称 || "",
        检验数量_8: row.检验数量_8 || 0,
        TaskAID: row.TaskAID || "",
        检验数量_6: row.检验数量_6 || 0,
        // 重置终检数据，允许用户输入新的检测数据
        检测数量: row.检验数量_6 - row.检验数量_8|| 0,
        合格数: row.检验数量_6 - row.检验数量_8,
        不合格数: 0,
        检测人: "",
        检测时间: this.formatDateTime(new Date()),
        检测说明: "",
      };
      console.log(this.finalCheckData);
    },

    // 显示终检历史记录
    showFinalCheckHistory(row) {
      this.finalCheckHistoryVisible = true;
      this.loadFinalCheckHistory(row);
    },

    // 加载终检历史记录
    loadFinalCheckHistory(row) {
      this.historyLoading = true;
      this.finalCheckHistoryData = [];

      var param = [];
      param.push(["合同号", row.内部合同号 || ""]);
      param.push(["订单号", row.计划号 || ""]);
      param.push(["零件编号", row.零件编码 || ""]);
      param.push(["零件名称", row.零件名称 || ""]);

      // 如果有检测日期，也传入
      if (this.inspectionDate && this.inspectionDate.length === 2) {
        param.push(["检测日期_Start", this.inspectionDate[0]]);
        param.push(["检测日期_End", this.inspectionDate[1]]);
      }

      // 如果有检测结果，也传入
      if (this.inspectionResult) {
        param.push(["检测结果", this.inspectionResult]);
      }

      // 如果有检测人，也传入
      if (this.checker) {
        const selectedChecker = this.checkerList.find(
          (item) => item.value === this.checker
        );
        param.push(["检测人", selectedChecker ? selectedChecker.label : ""]);
      }

      var Data = this.CreateData(
        "11",
        "质量管理_质量检验_终检记录_查询",
        param
      );

      this.ExecDatabase(Data)
        .then((response) => {
          this.historyLoading = false;
          if (response.data && response.data.length !== 0) {
            this.finalCheckHistoryData = response.data;
            this.$message.success(`查询到${response.data.length}条终检记录`);
          } else {
            this.finalCheckHistoryData = [];
            this.$message.info("未查询到终检记录");
          }
        })
        .catch((error) => {
          this.historyLoading = false;
          console.error("查询终检记录失败:", error);
          this.$message.error("查询终检记录失败");
        });
    },

    handleInspectionQuantityChange(value) {
      // 当检测数量改变时，重新计算不合格数
      // if (value < this.finalCheckData.合格数) {
      //   this.finalCheckData.合格数 = value;
      // }
      this.finalCheckData.合格数 = value - this.finalCheckData.不合格数;
    },

    handleQualifiedChange(value) {
      // 自动计算不合格数
      this.finalCheckData.合格数 = this.finalCheckData.检测数量 - value;
    },

    saveFinalCheck() {
      // 防止重复点击
      if (this.saveLoading) {
        return;
      }

      // 验证表单
      if (!this.finalCheckData.检测数量 || this.finalCheckData.检测数量 <= 0) {
        this.$message.warning("请输入有效的检测数量");
        return;
      }
      
      console.log(this.finalCheckData.检测数量,this.finalCheckData.合格数 , this.finalCheckData.不合格数)
      if (this.finalCheckData.检测数量 != this.finalCheckData.合格数 + this.finalCheckData.不合格数) {
        this.$message.warning("请输入正确的合格数");
        return;
      }

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

      if (!this.finalCheckData.检测时间) {
        this.$message.warning("请选择检验时间");
        return;
      }
      
      console.log(this.finalCheckData.检测数量 , this.finalCheckData.检验数量_8 ,this.finalCheckData.检验数量_6)
      if (this.finalCheckData.检测数量 + this.finalCheckData.检验数量_8 > this.finalCheckData.检验数量_6) {
        this.$message.warning("请输入有效的检测数量");
        return;
      }

      // 设置加载状态，禁用按钮
      this.saveLoading = true;

      // 调用存储过程保存数据
      var param = [];
      param.push(["TaskAID", this.finalCheckData.TaskAID || ""]);
      param.push(["检测类型编号", 8]); // 3代表终检类型
      param.push(["质检类型", "终检"]);
      param.push(["零件名称", this.finalCheckData.零件名称]);
      param.push(["内部合同号", this.finalCheckData.内部合同号]);
      param.push(["零件编码", this.finalCheckData.零件编码]);
      param.push(["计划号", this.finalCheckData.计划号]);
      param.push(["工序名称", this.finalCheckData.工序名称]);
      param.push(["检测数量", this.finalCheckData.检测数量]);
      param.push(["合格数", this.finalCheckData.合格数]);
      param.push(["不合格数", this.finalCheckData.不合格数]);
      param.push(["检测人", this.finalCheckData.检测人]);
      param.push(["检测时间", this.finalCheckData.检测时间]);
      param.push(["检测说明", this.finalCheckData.检测说明]);
      param.push(["放行数量", this.finalCheckData.放行数量]);

      console.log("保存参数:", param);

      var Data = this.CreateData(
        "12",
        "MES_QulityInspection_FinalCheck",
        param
      );

      this.ExecDatabase(Data)
        .then((response) => {
          if (
            response.data &&
            response.data[0] &&
            response.data[0].result === "1"
          ) {
            this.$message.success("终检操作成功");
            this.finalCheckVisible = false;
            // 刷新表格数据
            this.searchTable();
          } else {
            this.$message.error("终检操作失败：" + (response.data[0]?.message || "未知错误"));
          }
        })
        .catch((error) => {
          console.error("终检操作失败:", error);
          this.$message.error("终检操作失败: " + error.message);
        })
        .finally(() => {
          // 无论成功失败，都解除按钮禁用
          this.saveLoading = false;
        });
    },


    async upsap(){
      var param = [];
      // var  result3 = await getB1("ProductionOrders",{
      //   "$filter":"AbsoluteEntry eq "+this.finalCheckData.计划号+""
      // })
      var param = []
      param.push(["订单编号",this.finalCheckData.计划号])
      var Data = this.CreateData("11","工时校验_获取工序和指派对象",param);
      this.ExecDatabase(Data).then((response) => {
        if(response.data.length>0){
          // var AbsoluteEntry = result3.data.value[0].AbsoluteEntry
          // var ProductionOrderLines = result3.data.value[0].ProductionOrderLines
          // var ProductionOrdersStages =  result3.data.value[0].ProductionOrdersStages
          // ProductionOrderLines.forEach(item=>{
          //   if(item.ItemType == 'pit_Item'){
          //     item.StageID = 1
          //   }
          // })
          // response.data.forEach((element,index)=> {
          //   if (!ProductionOrderLines.some(item => item.ItemNo == element.指派对象编号)){
          //     ProductionOrderLines.push({
          //       "ProductionOrderIssueType": "im_Manual",
          //       "Warehouse": "W03",
          //       "ItemType": "pit_Resource",
          //       "ItemName":element.指派对象,
          //       "ItemNo":element.指派对象编号,
          //       "StageID":element.订单行号
          //     });
          //   }
          //   if (!ProductionOrdersStages.some(item => item.Name == element.工序名称)){
          //     ProductionOrdersStages.push({
          //       "DocEntry": AbsoluteEntry,
          //       "Name": element.工序名称,
          //       "StageEntry":element.顺序编号,
          //       "StageID":element.订单行号
          //     })
          //   }
          // });
          // patchB1("ProductionOrders("+AbsoluteEntry+")",{
          //   "AbsoluteEntry": AbsoluteEntry,
          //   "ProductionOrderLines":ProductionOrderLines,
          //   "ProductionOrdersStages":ProductionOrdersStages,
          // })
        }
      })
      // console.log(result3)
      
      
      // 如果需要转成 JSON 字符串
      // const jsonString = JSON.stringify(result, null, 2);
      // console.log(jsonString);
    },
    // transformData(rawArray) {
    // // 先转成对象便于取值
    //   const map = {};
    //   for (const [key, value] of rawArray) {
    //     map[key] = value;
    //   }

    //   const taskItemsArray = map.task_items;
    //   const taskMap = {};
    //   for (const [k, v] of taskItemsArray) {
    //     taskMap[k] = v;
    //   }

    //   const materialsArray = taskMap.task_materials_items;
    //   const materialsMap = {};
    //   for (const [k, v] of materialsArray) {
    //     materialsMap[k] = v;
    //   }
    //   return {
    //     doc_date: new Date().toISOString().split('T')[0], // 或 new Date().toISOString().split('T')[0]
    //     doc_type: '112-21',
    //     external_num: taskMap.external_num,
    //     task_items: [
    //       {
    //         base_type: taskMap.base_type,
    //         external_num: taskMap.external_num,
    //         item_code: taskMap.item_code,
    //         item_name: taskMap.item_name,
    //         whs_code: '', // 原值被清空
    //         manage_type: taskMap.manage_type,
    //         price: taskMap.price,
    //         quantity: taskMap.quantity,
    //         task_materials_items: [
    //           {
    //             item_code: taskMap.item_code, // 新增：继承 item_code
    //             batch_number: '', // 原 null 改为空字符串
    //             quantity: materialsMap.quantity
    //           }
    //         ]
    //       }
    //     ]
    //   };
    // },
// 如果需要转成 JSON 字符串
    
    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("导出失败");
      }
    },

    // 格式化日期用于文件名
    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;
}
.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>