<!-- 四级审核页面：动态获取表格字段、正则表达式 -->
<template>
  <div class="examination secondApprove">
    <div class="common-head-search">
      <el-form :inline="true" :model="search" ref="search">
        <el-form-item label="检验车间" prop="deptNo">
          <el-select v-model="search.deptNo" filterable clearable style="width: 140px" @clear="clearSelect"
            @change="selectClass" size="small">
            <el-option v-for="item in sectionNameType" :key="item.orgCode" :label="item.orgName" :value="item.orgCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检验班组">
          <el-select v-model="search.sectionNo" filterable clearable style="width: 140px" size="small">
            <el-option v-for="item in sectionClassType" :key="item.orgCode" :label="item.orgName" :value="item.orgCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="matClassNo" label="物料类型">
          <el-select v-model="search.matClassNo" @change="selctMatName" clearable style="width: 100%" filterable
            size="small">
            <el-option v-for="item of matClassNameType" :key="item.matClassNo" :label="item.matClassName"
              :value="item.matClassNo">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="matNo" label="物料名称">
          <el-select
            v-model="search.matNo"
            clearable
            style="width: 100%"
            filterable
            size="small"
          >
            <el-option
              v-for="item of matNameType"
              :key="item.matNo"
              :label="item.matName"
              :value="item.matNo"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="委托编号">
          <el-input v-model="search.carNo" @keyup.enter.native="searchData()" size="small" placeholder="请输入查询委托编号"
            style="width: 150px" clearable></el-input>
        </el-form-item>
        <el-form-item label="中心编号">
          <el-input v-model="search.sampleNo" @keyup.enter.native="searchData()" size="small" placeholder="请输入中心编号样号查询"
            style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="创建日期" prop="times">
          <el-date-picker v-model="search.times[0]" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date"
            placeholder="开始日期" size="mini" style="width: 140px" :default-time="'00:00:00'">
          </el-date-picker>
          <span>至</span>
          <el-date-picker v-model="search.times[1]" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date"
            placeholder="结束日期" size="mini" style="width: 140px" :default-time="'23:59:59'">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="goon" size="mini" :disable="disSearch" @click="searchData"
            :loading="loading">查询</el-button>
          <el-button icon="el-icon-refresh" type="info" plain size="mini" :disable="disSearch"
            @click="resetData">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-tabs type="border-card" v-model="activeName">
      <el-tab-pane label="待审核" name="first">
        <span slot="label">待审核<el-badge :max="10" :hidden="tableData11.length == 0" style="margin-top: -18px"
            :value="tableData11.length"></el-badge></span>
        <el-row>
          <el-col :span="4">
            <div class="common-title-div">
              <div class="common-title-name">
                <img style="width: 25px; height: 25px" src="../../../assets/img/imgScreen/logo.png" />
                待审物料
              </div>
              <div></div>
            </div>
            <div class="common-table-div">
              <el-table ref="tableMain11" :height="theight1" v-loading="tableLoading11" :data="tableData11"
                highlight-current-row @row-click="handleCurrentChange11" :header-cell-style="tableHeaderCellStyle"
                :summary-method="getSummaries11" show-summary border style="width: 100%" :icorePanelShown="100"
                :icore-filter-flag="icoreFilterFlag">
                <el-table-column sortable show-overflow-tooltip align="center" min-width="100" prop="MAT_NAME"
                  label="物料名称"></el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :span="20">
            <div class="common-title-div">
              <div class="common-title-name">
                <img style="width: 25px; height: 25px" src="../../../assets/img/imgScreen/logo.png" />
                待审核内容
              </div>
              <div>
                <el-form :inline="true" @submit.native.prevent>
                  <el-form-item>
                    <el-button icon="el-icon-check" type="goon" size="mini" :loading="buttonLoading1"
                      v-privilege="activeMenu + 'audit'" @click="auditEnd">审批通过</el-button>
                    <el-button icon="el-icon-edit" type="goon" size="mini" v-privilege="activeMenu + 'editEntrustType'"
                      @click="editEntrustType">修改委托类型</el-button>
                    <!-- <el-button icon="el-icon-check" type="goon" size="mini" :loading='buttonLoading1' v-privilege="activeMenu + 'audit'" @click="audit">审批</el-button> -->
                    <!-- <el-button icon="el-icon-remove-outline" type="danger" :loading='buttonLoading2' v-privilege="activeMenu + 'cancel'" @click="cancel" size="mini">
                      取消
                    </el-button> -->
                  </el-form-item>
                </el-form>
              </div>
            </div>
            <div class="common-table-div">
              <el-table ref="tableMain12" :height="theight1" v-loading="tableLoading1" :data="tableData1"
                @selection-change="searchFollow1" highlight-current-row :summary-method="getSummaries"
                :header-cell-style="tableHeaderCellStyle" show-summary :span-method="arraySpanMethod" border
                :cell-class-name="selectStyle" style="width: 100%" :icorePanelShown="100"
                :icore-filter-flag="icoreFilterFlag">
                <el-table-column label="NO" fixed="left" align="center" width="45">
                  <template slot-scope="scope">
                    <span :style="{ color: scope.row && scope.row.MSG_RES_FLAG === '失败' ? 'red' : '' }">{{ scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column type="selection" width="45" fixed="left" align="center"></el-table-column>
                <!--                <el-table-column sortable show-overflow-tooltip align="center" width="135" prop="CONTRACT_NO" label="合同号"></el-table-column>-->
                <el-table-column sortable show-overflow-tooltip align="center" min-width="120" prop="RECEIVED_DATE"
                  label="收样日期"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" width="80" prop="ENTR_TYPE_NAME"
                  label="委托类型"></el-table-column>
                <el-table-column v-if="isShowSuppName" sortable show-overflow-tooltip align="center" width="135"
                  prop="SUPP_NAME" label="供应商">
                  <template slot-scope="scope">
                    {{
                      scope.row.SUPP_NAME
                        ? scope.row.SUPP_NAME - 0 === -1
                          ? ""
                          : scope.row.SUPP_NAME
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column v-if="isShowNetNum" sortable show-overflow-tooltip align="center" prop="NET_NUM"
                  width="135" label="发货量">
                  <template slot-scope="scope">
                    {{
                      scope.row.NET_NUM
                        ? scope.row.NET_NUM - 0 === -1
                          ? ""
                          : scope.row.NET_NUM
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="DEPT_NAME"
                  label="检验车间"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="SECTION_NAME"
                  label="检验班组"></el-table-column>
                <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="50" prop="bool"
                  label="状态"></el-table-column>
                <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="100"
                  prop="SAMPLE_NO" label="中心编号"></el-table-column>
                <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="100"
                  prop="CAR_NO" label="委托编号"></el-table-column>
                <el-table-column v-if="isShowMarkNo" sortable show-overflow-tooltip fixed="left" prop="MARK_NO"
                  align="center" min-width="120" label="N码">
                  <template slot-scope="scope">
                    {{
                      scope.row.MARK_NO
                        ? scope.row.MARK_NO - 0 === -1
                          ? ""
                          : scope.row.MARK_NO
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column v-if="isShowEncryNo" sortable show-overflow-tooltip fixed="left" prop="ENCRY_NO"
                  align="center" min-width="100" label="S码">
                  <template slot-scope="scope">
                    {{
                      scope.row.ENCRY_NO
                        ? scope.row.ENCRY_NO - 0 === -1
                          ? ""
                          : scope.row.ENCRY_NO
                        : ""
                    }}
                  </template>
                </el-table-column>
                <!-- <el-table-column v-if="isShowLotsNo" sortable show-overflow-tooltip align="center" min-width="100" prop="LOTS_NO" label="到货批次号">
                  <template slot-scope="scope">
                    {{scope.row.LOTS_NO ? (scope.row.LOTS_NO - 0 === -1 ? '' : scope.row.LOTS_NO) : ''}}
                  </template>
                </el-table-column> -->
                <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="100"
                  prop="MAT_NAME" label="物料名称"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="SAMPLE_TYPE_NAME"
                  label="样品类型"></el-table-column>
                <!-- <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="STD_NAME" label="方法"></el-table-column> -->
                <el-table-column label="分析项目" show-overflow-tooltip>
                  <template v-for="col in cols">
                    <el-table-column sortable :prop="col" show-overflow-tooltip min-width="72" align="center" :key="col"
                      :label="col">
                      <template slot-scope="scope">
                        <span @click.stop="
                          showDataSource(scope.row, scope.row[col])
                          " style="cursor: pointer" :class="{
                            'color-blue': scope.row[col] && !scope.row[col + 'Flag'],
                            'color-danger':
                              (scope.row[col] &&
                              scope.row[col].split('_')[2] &&
                              !scope.row[col].split('_')[3]) || scope.row[col + 'Flag'],
                            'color-warning':
                              scope.row[col] && scope.row[col].split('_')[3],
                          }">
                          {{
                            scope.row[col] || scope.row[col] == "0"
                              ? scope.row[col].split("_")[0]
                              : ""
                          }}
                        </span>
                      </template>
                    </el-table-column>
                  </template>
                </el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="75px" prop="ENTR_MEMO"
                  label="委托备注"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="75px" prop="CREATE_MAN"
                  label="创建人"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="125px" prop="CREATE_TIME"
                  label="创建时间"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="75px" prop="UPDATE_MAN"
                  label="修改人"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="125px" prop="UPDATE_TIME"
                  label="修改时间"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="75px" prop="SEND_BACK_MAN"
                  label="退回人"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="125px" prop="SEND_BACK_REASON"
                  label="退回原因"></el-table-column>
              </el-table>
              <div class="common-foot-style">
                <el-pagination @size-change="handleSizeChangeMain" @current-change="handleCurrentChangeMain"
                  :current-page.sync="pageIndex" :page-sizes="[100, 200, 500, 800, 1000, 1500]" :page-size="pageSize"
                  size="mini" layout="total, sizes, prev, pager, next, jumper" :total="total_main"
                  background></el-pagination>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="已审核" name="second">
        <el-row>
          <el-col :span="4">
            <div class="common-title-div">
              <div class="common-title-name">
                <img style="width: 25px; height: 25px" src="../../../assets/img/imgScreen/logo.png" />
                已审物料
              </div>
            </div>
            <div class="common-table-div">
              <el-table ref="tableMain21" :height="theight1" v-loading="tableLoading21" :data="tableData21"
                highlight-current-row @row-click="handleCurrentChange21" :header-cell-style="tableHeaderCellStyle"
                :summary-method="getSummaries11" show-summary border style="width: 100%" :icorePanelShown="100"
                :icore-filter-flag="icoreFilterFlag">
                <el-table-column sortable show-overflow-tooltip align="center" min-width="100" prop="MAT_NAME"
                  label="物料名称"></el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :span="20">
            <div class="common-title-div">
              <div class="common-title-name">
                <img style="width: 25px; height: 25px" src="../../../assets/img/imgScreen/logo.png" />
                已审核内容
              </div>
              <div>
                <el-form :inline="true" @submit.native.prevent>
                  <el-form-item>
                    <!-- <el-button icon="el-icon-check" type="danger" size="mini" :loading='buttonLoadingBack' @click="rollback">撤回审核</el-button> -->
                    <el-button icon="el-icon-check" type="goon" size="mini" :loading="buttonLoading1" @click="restartSendMsgSourceByResult"
                      v-privilege="activeMenu + 'check'">
                      再次发送电文
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            <div class="common-table-div">
              <el-table ref="tableMain22" :height="theight2" v-loading="tableLoading2" :data="tableData2"
                @selection-change="searchFollow2" highlight-current-row :summary-method="getSummaries"
                :header-cell-style="tableHeaderCellStyle" show-summary :span-method="arraySpanMethod2" border
                style="width: 100%" :icorePanelShown="100" :icore-filter-flag="icoreFilterFlag">
                <el-table-column label="NO" fixed="left" align="center" width="45">
                  <template slot-scope="scope">
                    <span :style="{ color: scope.row && scope.row.MSG_RES_FLAG === '失败' ? 'red' : '' }">
                      {{ scope.$index + 1 }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column type="selection" width="45" fixed="left" align="center"></el-table-column>
                <!--                <el-table-column sortable show-overflow-tooltip align="center" width="135" prop="CONTRACT_NO" label="合同号"></el-table-column>-->
                <el-table-column sortable show-overflow-tooltip align="center" min-width="100" prop="releaseValid"
                  label="状态"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="120" prop="RECEIVED_DATE"
                  label="收样日期"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" width="80" prop="ENTR_TYPE_NAME"
                  label="委托类型"></el-table-column>
                <el-table-column v-if="isShowSuppName" sortable show-overflow-tooltip align="center" width="135"
                  prop="SUPP_NAME" label="供应商">
                  <template slot-scope="scope">
                    {{
                      scope.row.SUPP_NAME
                        ? scope.row.SUPP_NAME - 0 === -1
                          ? ""
                          : scope.row.SUPP_NAME
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column v-if="isShowNetNum" sortable show-overflow-tooltip align="center" width="135"
                  prop="NET_NUM" label="发货量">
                  <template slot-scope="scope">
                    {{
                      scope.row.NET_NUM
                        ? scope.row.NET_NUM - 0 === -1
                          ? ""
                          : scope.row.NET_NUM
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="DEPT_NAME"
                  label="检验车间"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="SECTION_NAME"
                  label="检验班组"></el-table-column>
                <el-table-column fixed="left" sortable show-overflow-tooltip align="center" min-width="100"
                  prop="SAMPLE_NO" label="中心编号"></el-table-column>
                <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="100"
                  prop="CAR_NO" label="委托编号"></el-table-column>
                <el-table-column v-if="isShowMarkNo" sortable show-overflow-tooltip fixed="left" align="center"
                  min-width="120" prop="MARK_NO" label="N码">
                  <template slot-scope="scope">
                    {{
                      scope.row.MARK_NO
                        ? scope.row.MARK_NO - 0 === -1
                          ? ""
                          : scope.row.MARK_NO
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column v-if="isShowEncryNo" sortable show-overflow-tooltip fixed="left" align="center"
                  min-width="100" prop="ENCRY_NO" label="S码">
                  <template slot-scope="scope">
                    {{
                      scope.row.ENCRY_NO
                        ? scope.row.ENCRY_NO - 0 === -1
                          ? ""
                          : scope.row.ENCRY_NO
                        : ""
                    }}
                  </template>
                </el-table-column>
                <!-- <el-table-column v-if="isShowLotsNo" sortable show-overflow-tooltip align="center" min-width="100" prop="LOTS_NO" label="到货批次号">
                  <template slot-scope="scope">
                    {{scope.row.LOTS_NO ? (scope.row.LOTS_NO - 0 === -1 ? '' : scope.row.LOTS_NO) : ''}}
                  </template>
                </el-table-column> -->
                <el-table-column fixed="left" sortable show-overflow-tooltip align="center" min-width="100"
                  prop="MAT_NAME" label="物料名称"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="SAMPLE_TYPE_NAME"
                  label="样品类型"></el-table-column>
                <!-- <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="STD_NAME" label="方法"></el-table-column> -->
                <el-table-column label="分析项目" show-overflow-tooltip>
                  <template v-for="col in cols2">
                    <el-table-column sortable :prop="col" show-overflow-tooltip min-width="72" align="center" :key="col"
                      :label="col">
                      <template slot-scope="scope">
                        <span @click.stop="
                          showDataSource(scope.row, scope.row[col])
                          " style="cursor: pointer">
                          {{
                            scope.row[col] || scope.row[col] == "0"
                              ? scope.row[col].split("_")[0]
                              : ""
                          }}
                        </span>
                      </template>
                    </el-table-column>
                  </template>
                </el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="75px" prop="ENTR_MEMO"
                  label="委托备注"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="100px" prop="AUDIT_MAN"
                  label="二审审核人"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="140px" prop="AUDIT_TIME"
                  label="二审审核时间"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="75px" prop="CREATE_MAN"
                  label="创建人"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="125px" prop="CREATE_TIME"
                  label="创建时间"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="75px" prop="UPDATE_MAN"
                  label="修改人"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="125px" prop="UPDATE_TIME"
                  label="修改时间"></el-table-column>
                <el-table-column sortable show-overflow-tooltip align="center" min-width="125px" prop="MSG_RES_FLAG"
                  label="电文发送状态">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" :content="scope.row.MSG_RES_DETAIL" placement="top">
                      <span>{{ scope.row.MSG_RES_FLAG }}</span>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
              <div class="common-foot-style">
                <el-pagination @size-change="handleSizeChangeMain2" @current-change="handleCurrentChangeMain2"
                  :current-page.sync="pageIndex2" :page-sizes="[100, 200, 500, 800, 1000, 1500]" :page-size="pageSize2"
                  size="mini" layout="total, sizes, prev, pager, next, jumper" :total="total_main2"
                  background></el-pagination>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <!-- 原始数据 -->
    <el-dialog :close-on-click-modal="false" @close="closebatch" width="100%" :visible.sync="batchShow" top="0">
      <div slot="title" class="titleBox">
        <i class="el-icon-document" style="font-size: 20px"></i>
        <span style="margin-left: 10px; font-size: 18px">原始数据</span>
      </div>
      <div class="common-title-name" style="padding-bottom: 3px">
        <el-button icon="el-icon-back" type="danger" size="mini" :loading="backLoading"
          @click="checkErr">审批不通过</el-button>
        <!--         <el-button icon="el-icon-check" type="goon" :loading='submitLoading' @click="checkSuc" size="mini"></el-button> -->
      </div>
      <el-table ref="table13" border :height="theight13" highlight-current-row :data="tableData13"
        :span-method="arraySpanMethod13" @selection-change="searchFollow13" :header-cell-style="tableHeaderCellStyle"
        :summary-method="getSummaries" show-summary>
        <el-table-column type="index" label="NO" width="45" fixed align="center"></el-table-column>
        <el-table-column type="selection" width="45" fixed align="center"></el-table-column>
        <el-table-column show-overflow-tooltip sortable min-width="180" fixed align="center" label="退回原因">
          <template slot-scope="{ row }">
            <el-input v-model="row.logMemo" size="small"></el-input>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip sortable min-width="118" fixed align="center" prop="SAMPLE_NO"
          label="中心编号">
          <template slot-scope="scope">
            <div style="white-space: pre-wrap; word-wrap: break-word" @click.stop="showHistory(scope.row)" :class="{
              'color-danger': scope.row.ERR == '1' && !scope.row.SUB,
              'color-warning': scope.row.SUB == '1',
              'color-blue': scope.row.ERR != '1' && scope.row.SUB != '1',
            }">
              {{ scope.row.SAMPLE_NO }}
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip sortable min-width="125" fixed align="center" prop="MAT_NAME"
          label="物料名称">
          <template slot-scope="scope">
            <div style="white-space: pre-wrap; word-wrap: break-word" :class="{
              'color-danger': scope.row.ERR == '1' && !scope.row.SUB,
              'color-warning': scope.row.SUB == '1',
            }">
              {{ scope.row.MAT_NAME }}
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip sortable min-width="110" fixed align="center" prop="TEST_ITEM_NAME"
          label="测试项目">
          <template slot-scope="scope">
            <div style="white-space: pre-wrap; word-wrap: break-word" :class="{
              'color-danger': scope.row.ERR == '1' && !scope.row.SUB,
              'color-warning': scope.row.SUB == '1',
            }">
              {{ scope.row.TEST_ITEM_NAME }}
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip sortable width="80" fixed align="center" prop="CHECK_TIME" label="提交时间">
          <template slot-scope="scope">
            <div style="white-space: pre-wrap; word-wrap: break-word" :class="{
              'color-danger': scope.row.ERR == '1' && !scope.row.SUB,
              'color-warning': scope.row.SUB == '1',
            }">
              {{ scope.row.CHECK_TIME }}
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip sortable min-width="80" fixed align="center" prop="CREATE_MAN"
          label="提交人">
          <template slot-scope="scope">
            <span :class="{
              'color-danger': scope.row.ERR == '1' && !scope.row.SUB,
              'color-warning': scope.row.SUB == '1',
            }">
              {{ scope.row.CREATE_MAN }}
            </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip min-width="180" align="center" prop="ANLY_ITEM_NAME"
          label="分析项目"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="ANLY_VALUE"
          label="报出值">
         <template slot-scope="scope">
                        <span
                          :class="{
                            'color-blue': !scope.row.isOutOfRange,
                            'color-danger':
                             scope.row.isOutOfRange
                          }">
                          {{
                            scope.row.ANLY_VALUE
                          }}
                        </span>
                      </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="maxValue"
          label="最大值"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="minValue"
          label="最小值"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="REVISE_VALUE"
          label="录入值"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="DAS_VALUE"
          label="采集值"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="CPT_VALUE"
          label="计算值"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="REVISE_VALUE"
          label="修约值"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="90" align="center" prop="UNIT_NAME"
          label="单位"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="FORMULA_NAME"
          label="计算公式"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="REVISE_RULE_NAME"
          label="修约规则"></el-table-column>
        <el-table-column show-overflow-tooltip min-width="100" align="center" prop="isReportName"
          label="是否报出"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="goon" icon="el-icon-remove-outline" @click="closebatch">取消</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改委托类型" :visible.sync="dialogEntrustVisible" width="80%" center>
      <el-table ref="table12" border :data="multipleSelection1">
        <el-table-column type="index" label="NO" fixed="left" align="center" width="45"></el-table-column>
        <el-table-column sortable show-overflow-tooltip align="center" width="100" prop="ENTR_TYPE_NAME" label="委托类型">
          <template slot-scope="scope">
            <el-select v-model="scope.row.entrTypeCode" clearable filterable style="width: 100%" collapse-tags
              size="small">
              <el-option v-for="(item, index) in entrTypeNameType" :key="index" :label="item.baseName"
                :value="item.baseCode">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column v-if="isShowSuppName" sortable show-overflow-tooltip align="center" width="135"
          prop="SUPP_NAME" label="供应商">
          <template slot-scope="scope">
            {{
              scope.row.SUPP_NAME
                ? scope.row.SUPP_NAME - 0 === -1
                  ? ""
                  : scope.row.SUPP_NAME
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="DEPT_NAME"
          label="检验车间"></el-table-column>
        <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="SECTION_NAME"
          label="检验班组"></el-table-column>
        <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="50" prop="bool"
          label="状态"></el-table-column>
        <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="100" prop="SAMPLE_NO"
          label="中心编号"></el-table-column>
        <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="100" prop="CAR_NO"
          label="委托编号"></el-table-column>
        <el-table-column sortable show-overflow-tooltip fixed="left" align="center" min-width="100" prop="MAT_NAME"
          label="物料名称"></el-table-column>
        <el-table-column sortable show-overflow-tooltip align="center" min-width="80" prop="SAMPLE_TYPE_NAME"
          label="样品类型"></el-table-column>
        <el-table-column sortable show-overflow-tooltip align="center" min-width="75px" prop="ENTR_MEMO"
          label="委托备注"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="goon" icon="el-icon-remove-outline" @click="closeDialog">取消</el-button>
        <el-button size="mini" type="primary" icon="el-icon-check" @click="modifyEntrustData">保存</el-button>
      </span>
    </el-dialog>
    <div is="historyAlert" :showFlag="historyShowFlag" :Params="Params" @refresh="refresh"></div>
  </div>
</template>
<script>
import { getCookie, formatDate } from "@/utils/util.js";
import { cookieUserId, cookieUserName } from "@/config/config.js";
import historyAlert from "../../testAnalysis/components/testManagement/historyAlert";
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  components: { historyAlert },
  data() {
    return {
      fromDaiban: null,
      search: {
        deptNo: "",
        sectionNo: "",
        matClassNo: "",
        matNo: "",
        carNo: "",
        sampleTypeCode: "",
        matName: "",
        times: [null, null],
        type: ""
      },
      // rules: {
      //   times: [
      //     {
      //       trigger: ['change', 'blur'],
      //       validator: (rule, value, callback) => {
      //         const startDate = value[0];
      //         const endDate = value[1];
      //         if (!startDate || !endDate) {
      //           return callback(new Error('请选择完整的日期范围'));
      //         }
      //         if (new Date(startDate) > new Date(endDate)) {
      //           return callback(new Error('开始日期不能晚于结束日期'));
      //         }
      //         callback();
      //       }
      //     }],
      // },
      loading: false,
      dialogTableVisible: false,
      dialogEntrustVisible: false,
      historyShowFlag: false,
      Params: {},
      isShowSuppName: false,
      isShowNetNum: false,
      isShowMarkNo: false,
      isShowEncryNo: false,
      isShowLotsNo: false,
      sampleTypeNameType: [],
      saveAnalyAudit: [],
      deptNo: "", // 登录人的部门(车间)
      sectionNo: "", // 登录人的班组
      classNo: "", // 登录人的岗位
      disSearch: false,
      saveAnlyData: [],
      click_main: {}, // 选中物料行（未审核）
      click_main2: {}, // 选中物料行（已审核）
      theight1: 0,
      theight2: 0,
      isFixed: "left",
      oldTableData: [],
      oldTableLoading: false,
      calculateLoading: false,
      analyAuditLoading: false,
      tableLoading11: false,
      tableLoading1: false,
      tableLoading2: false,
      tableLoading21: false,
      tableLoading3: false,
      buttonLoading1: false,
      buttonLoading2: false,
      buttonLoading3: false,
      buttonLoadingBack: false,
      cols: [], // 未审核动态列
      cols2: [], // 已审核动态列
      tableData11: [], // 待审核物料
      tableData21: [], // 已审核物料
      tableData1: [],
      tableData2: [],
      tableData3: [],
      tableData13: [], // 原始记录1
      theight13: "",
      pageIndex: 1,
      pageSize: 500,
      total_main: 0,
      pageIndex2: 1,
      pageSize2: 500,
      total_main2: 0,
      multipleSelection1: [], // 1表多选
      multipleSelection2: [], // 2表多选
      multipleSelection13: [], // 原始数据多选-审核
      activeName: "first",
      backManLoading: false,
      backPlanLoading: false,
      icoreFilterFlag: true,
      sectionNameType: [], // 检验车间
      sectionClassType: [], // 检验班组
      companyNameType: [], // 公司
      matNameType: [], // 物料名称-查询
      matClassNameType: [], // 物料类型-查询
      activeMenu: "",
      batchShow: false, // 原始记录显示
      backLoading: false, // 审核不通过
      valSource: "", // 原始数据来源
      curSrId: "", // 原始数据srid
      entrTypeNameType: [],
    };
  },
  created() {
    this.theight1 = window.innerHeight - 240;
    this.theight2 = window.innerHeight - 240;
    this.theight13 = window.innerHeight - 240;
    this.activeMenu = window.top.localStorage.getItem("activeMenu");
    let timestamp = new Date().getTime() - 7 * 24 * 60 * 60 * 1000; // 默认前一周
    this.fromDaiban = JSON.parse(sessionStorage.getItem("fromDaiban"));
    sessionStorage.removeItem("fromDaiban");

    if (this.fromDaiban) {
      this.search.times = [this.fromDaiban.startTime, this.fromDaiban.endTime];
      this.activeName = this.fromDaiban.status == 1 ? "second" : "first";
    } else {
      this.search.times = [
        this.getYNM(new Date(timestamp)),
        this.getYNM(new Date()),
      ];
    }

    // 获取所有机构
    this.axios
      .post(
        "pass/baseManagement/v1/sysorgs/querySysOrgCompanyAll",
        {},
        { individualType: "json" }
      )
      .then((response) => {
        this.companyNameType = response.data;
        console.log(this.companyNameType);
        // 获取检测中心下的机构
        this.selectDepartment("JCZX");
        console.log(this.sectionNameType);
        // this.getCompany()
      });
    this.search.type = this.$route.query.type || '';
    this.searchData();
  },
  watch: {
    "$route.query.type"(newType) {
      this.search.type = newType || '';
    }
  },
  mounted() {

    this.axios
      .post(
        "pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",
        { validFlag: 1, baseCode: 4801 },
        { individualType: "json" }
      )
      .then((res) => {
        this.sampleTypeNameType = res.data;
      });
    //物料类型
    this.axios
      .get("pass/baseManagement/v1/limsbasematerialsclasss/?validFlag=1")
      .then((res) => {
        this.matClassNameType = res.data.list;
      });
  },
  methods: {
    closeDialog() {
      this.dialogEntrustVisible = false;
    },
    editEntrustType() {
      if (this.multipleSelection1.length === 0) {
        this.$message.warning('请选择一条数据')
        return
      }
      this.getEntrustType()
      this.dialogEntrustVisible = true;
    },
    modifyEntrustData() {
      this.$confirm("确定修改以上单据的委托类型吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let map = {}
        map.userName = userName
        map.list = this.multipleSelection1
        this.axios
          .post(
            "pass/testManagement/v1/limssampleresults/updateEntrustType",
            map,
            { individualType: "json" }
          ).then((res) => {
            if (res.status === "succeed") {
              this.$message.success("修改成功");
              this.dataMain();
              this.dialogEntrustVisible = false
            } else {
              this.$message.error(res.message);
            }
          });
      }).catch((err) => {
        this.$message.error(err.message);
      });
    },
    getEntrustType() {
      this.axios
        .post(
          "pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",
          { validFlag: 1, baseCode: 4802 },
          { individualType: "json" }
        )
        .then((res) => {
          this.entrTypeNameType = res.data;
          // this.baseData.entrTypeCode = this.getCode(
          //   "内部",
          //   this.entrTypeNameType,
          //   "baseName",
          //   "baseCode"
          // );
        });
    },
    getCode(code, arr, codeKey, nameKey) {
      if (!code || !arr) {
        return "";
      }
      let targetRow = arr.find((item) => {
        return item[codeKey] === code;
      });
      // console.log(targetRow, 'targetRow');
      return targetRow ? targetRow[nameKey] : "";
    },
    getYNM(date) {
      let year = date.getFullYear().toString();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      return `${year}-${month}-${day}`;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
        }
        if (index === 1) {
          sums[index] = data.length;
        }
      });
      return sums;
    },
    getSummaries11(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计：" + data.length;
        }
      });
      return sums;
    },
    //获取个人所属哪个公司
    getCompany() {
      this.axios
        .get("pass/baseManagement/v1/limslrcemps/" + userId)
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.search.deptNo = res.data ? res.data.deptNo : "";
            this.selectClass(this.search.deptNo);
            this.search.sectionNo = res.data ? res.data.sectionNo : "";
            this.searchData();
          } else {
            this.disSearch = true;
            this.$message.error(e.message);
          }
        })
        .catch((e) => {
          this.disSearch = true;
          this.$message.error(e.message);
        });
    },
    resetData() {
      this.search.deptNo = "";
      this.search.sectionNo = "";
      this.search.matClassNo = "";
      this.search.matNo = "";
      this.search.sampleNo = "";
      this.search.carNo = "";

      let timestamp = new Date().getTime() - 7 * 24 * 60 * 60 * 1000; // 默认前一周

      this.search.times = [
        this.getYNM(new Date(timestamp)),
        this.getYNM(new Date()),
      ];
      // this.search.times = [
      //   this.getYNM(new Date(timestamp)) + " 00:00:00",
      //   this.getYNM(new Date()) + " 23:59:59",
      // ];
      this.searchData();
    },
    refresh() { },
    auditEnd() {
    // 原有逻辑：勾选数据判断，无数据直接返回
    if (this.multipleSelection1.length < 1) {
      this.$message.warning("请先勾选要审批的数据");
      return;
    }
    let totalCount = this.multipleSelection1.length;
    // 原有逻辑：开启按钮加载状态
    this.buttonLoading1 = true;

    this.axios.post(
      "pass/testManagement/v1/fullProcess/sampleBatchFullProcess",
      this.multipleSelection1,
      { individualType: "json" }
    ).then((res) => {
      console.log(res, 'res');
      // 关键改造1：获取后端返回的核心业务数据（res.data，兼容为空的情况）
      const result = res

      // 关键改造2：严谨判断操作成功（适配后端status: "succeed"，补充非空判断）
      if (result.status === 'succeed' && result.succeed) {
        // 关键改造3：替换可选链?. 为 && 层层判断（Vue2兼容写法，避免报错）
        const successCount = (result.data && result.data.successCount) || 0;
        const failCount = (result.data && result.data.failCount) || 0;
        const processDetailList = (result.data && result.data.processDetailList) || [];
        const failMsgList = processDetailList
        .filter(item => item.processStatus !== 'SUCCESS' && item.errorMsg) // 仅保留失败且有错误信息的
        .map(item => item.errorMsg || "无具体原因")
        .filter((msg, index, arr) => arr.indexOf(msg) === index); // 去重
        const failMsg = failMsgList.length > 0 ? failMsgList.join("；") : "无";
        let msg = `总共提交了${totalCount}条数据，成功${successCount}条，失败${failCount}条`
        if(failCount != 0) {
            msg = msg + "，失败原因：" + failMsg;
            this.$message.warning(msg);
        }else{
            this.$message.success(msg);
        }
        // 拼接失败详情（无失败时显示“无”）

      } else {
        // 关键改造4：优化失败信息提取，补充默认值
        const errorMsg = result.message || result.resultMessage || "审批失败，请重试";
        this.$message.error(errorMsg);
      }
    }).catch((err) => {
      // 关键改造5：完善异常捕获，避免空错误信息
      console.error("审批请求异常：", err);
      const errMsg = err.message || "网络异常或服务器内部错误，请联系管理员";
      this.$message.error(errMsg);
    }).finally(() => {
      // 原有逻辑：关闭加载状态，刷新列表
      this.buttonLoading1 = false;
      this.searchData();
    });
  },
    restartSendMsgSourceByResult() {
  // 原有逻辑：勾选数据判断，无数据直接返回
  if (this.multipleSelection2.length < 1) {
    this.$message.warning("请先勾选要发送的数据");
    return;
  }

  // 原有逻辑：开启按钮加载状态
  this.buttonLoading1 = true;
    let totalCount = this.multipleSelection1.length;

  this.axios.post(
    "pass/testManagement/v1/fullProcess/restartSendMsgSourceByResult",
    this.multipleSelection2,
    { individualType: "json" }
  ).then((res) => {
    console.log(res, 'res');
    // ========== 关键改造1：获取后端返回的核心业务数据（res.data，兼容为空） ==========
    const result = res

    // ========== 关键改造2：严谨判断操作成功（适配后端status: "succeed"，补充双字段校验） ==========
    if (result.status === 'succeed' && result.succeed) {
      // ========== 关键改造3：处理部分成功场景（Vue2兼容写法，无可选链） ==========
      const successCount = (result.data && result.data.successCount) || 0;
        const failCount = (result.data && result.data.failCount) || 0;
        const processDetailList = (result.data && result.data.processDetailList) || [];
        const failMsgList = processDetailList
        .filter(item => item.processStatus !== 'SUCCESS' && item.errorMsg) // 仅保留失败且有错误信息的
        .map(item => item.errorMsg || "无具体原因")
        .filter((msg, index, arr) => arr.indexOf(msg) === index); // 去重
        const failMsg = failMsgList.length > 0 ? failMsgList.join("；") : "无";
        let msg = `总共提交了${totalCount}条数据，成功${successCount}条，失败${failCount}条`
        if(failCount != 0) {
            msg = msg + "，失败原因：" + failMsg;
            this.$message.warning(msg);
        }else{
            this.$message.success(msg);
        }
    } else {
      // ========== 关键改造5：优化失败信息提取，补充默认值，贴合发送场景 ==========
      const errorMsg = result.message || result.resultMessage || "电文发送失败，请重试";
      this.$message.error(errorMsg);
    }
  }).catch((err) => {
    // ========== 关键改造6：完善异常捕获，避免空错误信息 ==========
    console.error("电文发送请求异常：", err);
    const errMsg = err.message || "网络异常或服务器内部错误，请联系管理员";
    this.$message.error(errMsg);
  }).finally(() => {
    // 原有逻辑：关闭加载状态，刷新列表
    this.buttonLoading1 = false;
    this.searchData();
  });
},
    // 审批通过
    audit() {
      if (this.multipleSelection1.length < 1) {
        this.$message.warning("请先勾选要审批的数据");
        return;
      }
      console.log("未处理参数是：", this.multipleSelection1);
      this.buttonLoading1 = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampleresults/checkLimsSampleResultsBf",
          this.multipleSelection1,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            if (res.data) {
              if (res.data == "1") {
                this.$message.error("您在这些样品的提交人中，不可审核！");
              } else {
                this.$message.error("中心编号" + res.data + "有未提交的任务！");
              }
              this.searchData();
              this.buttonLoading1 = false;
              // this.$confirm('中心编号' + res.data +'有未提交的任务，是否继续审核？', '提示', {
              //     confirmButtonText: '确定',
              //     cancelButtonText: '取消',
              //     type: 'warning'
              // }).then(()=>{
              //   this.axios.post('pass/testManagement/v1/limssampleresults/checkLimsSampleResults', this.multipleSelection1, {individualType: 'json'}).then(res =>{
              //     if (res.code == 0 || res.code == 200) {
              //       if(res.data && res.data != 'true'){
              //         this.$message.warning(res.data)
              //       }else{
              //         this.$message.success(res.message)
              //       }
              //       this.searchData()
              //     } else {
              //       this.$message.error(res.message)
              //     }
              //     this.buttonLoading1 = false
              //   }).catch(e =>{
              //     this.buttonLoading1 = false
              //     this.$message.error(e.message)
              //   })
              // }).catch(e => {
              //   this.buttonLoading1 = false
              // });
            } else {
              // 审核
              this.axios
                .post(
                  "pass/testManagement/v1/limssampleresults/checkLimsSampleResults",
                  this.multipleSelection1,
                  { individualType: "json" }
                )
                .then((res) => {
                  if (res.code == 0 || res.code == 200) {
                    this.$message.success(res.message);
                  } else {
                    this.$message.error(res.message);
                  }

                  this.audit2();
                  this.buttonLoading1 = false;
                })
                .catch((e) => {
                  this.buttonLoading1 = false;
                  this.$message.error(e.message);
                });
              // this.axios.post('pass/testManagement/v1/limssampleresults/checkLimsSampleResults', this.multipleSelection1, {individualType: 'json'}).then(res =>{
              //     if (res.code == 0 || res.code == 200) {
              //       if(res.data && res.data != 'true'){
              //         this.$message.warning(res.data)
              //       }else{
              //         this.$message.success(res.message)
              //       }
              //       this.searchData()
              //     } else {
              //       this.$message.error(res.message)
              //     }
              //     this.buttonLoading1 = false
              //   }).catch(e =>{
              //     this.buttonLoading1 = false
              //     this.$message.error(e.message)
              //   })
            }
          } else {
            // this.audit2()
            // this.searchData()
            this.buttonLoading1 = false;
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          this.buttonLoading1 = false;
          this.$message.error(err.message);
        });
    },
    async audit2() {
      if (this.multipleSelection1.length < 1) {
        this.$message.warning("请先勾选要发送的数据");
        return;
      }
      this.buttonLoading1 = true;
      let aa = 0; //成功
      let bb = 0; //失败
      let cc = 0; //取消
      // 遍历选中的数据,只留下isSomeOutOfRange值不存在或为false的
      let newArr = this.multipleSelection1.filter(function (item) {
        const val = item.isSomeOutOfRange;
        return val === false || val === "false" || val === undefined || val === null;
      });
      if(newArr.length < 1) {
        this.searchData();
        return
      }
      let length = newArr.length;
      for (var i = 0; i < length; i++) {
        var arr = [];
        var item = newArr[i];
        arr.push(item);
        console.log("发送电文参数是：", i, item, arr, length);
        const cfs = await this.axios.post(
          "pass/testManagement/v1/limssamplereleases/checkLimsSampleReleases",
          newArr,
          { individualType: "json" }
        );
        if(!cfs.code) {
            this.$message.warning("电文数据异常,请联系管理员!");
            return;
        }
        if (cfs.code == 0 || cfs.code == 200) {
          if (!cfs.data) {
            this.$message.warning("电文数据异常,请联系管理员");
            return;
          }
          if (cfs.data.info) {
            this.$message.warning(cfs.data);
          } else {
            let info = "";
            let map = {
              msgTopic: "lims/xcom/LS/CX/99",
              msgSource: cfs.data.byteData,
              msgFrom: "LS",
            };
            const cfs1 = await this.axios.post(
              "pass/mqtt/v1/sends/sendMessage",
              map,
              { individualType: "json" }
            );
            if (cfs1 == 0) {
              aa++;
            } else {
              bb++;
              this.$message.error(
                "样号是：" +
                newArr[i].sampleNo +
                "发送电文错误!"
              );
            }
          }
        } else {
          bb++;
          this.$message.error(cfs.message);
        }
      }
      this.buttonLoading1 = false;
      this.searchData();
      if (bb == 0 && cc == 0) {
        this.$message.success("执行完毕，成功提交 " + aa + " 条数据");
      } else {
        this.$message.warning(
          "执行完毕，成功提交 " +
          aa +
          " 条数据，失败 " +
          bb +
          " 条, 取消" +
          cc +
          " 条"
        );
      }
    },
    async audit1() {
      if (this.multipleSelection2.length < 1) {
        this.$message.warning("请先勾选要发送的数据");
        return;
      }
      this.buttonLoading1 = true;
      let aa = 0; //成功
      let bb = 0; //失败
      let cc = 0; //取消
      for (let i = 0; i < this.multipleSelection2.length; i++) {
        let arr = [];
        arr.push(this.multipleSelection2[i]);
        const cfs = await this.axios.post(
          "pass/testManagement/v1/limssamplereleases/checkLimsSampleReleases",
          arr,
          { individualType: "json" }
        );
        if (cfs.code == 0 || cfs.code == 200) {
          if (cfs.data.info) {
            this.$message.warning(cfs.data);
          } else {
            let info = "";
            let map = {
              msgTopic: "lims/xcom/LS/CX/99",
              msgSource: cfs.data.byteData,
              msgFrom: "LS",
            };
            const cfs1 = await this.axios.post(
              "pass/mqtt/v1/sends/sendMessage",
              map,
              { individualType: "json" }
            );
            if (cfs1 == 0) {
              aa++;
            } else {
              bb++;
              this.$message.error(
                "样号是：" +
                this.multipleSelection2[i].sampleNo +
                "发送电文错误!"
              );
            }
          }
        } else {
          bb++;
          this.$message.error(cfs.message);
        }
      }
      this.buttonLoading1 = false;
      this.searchData();
      if (bb == 0 && cc == 0) {
        this.$message.success("执行完毕，成功提交 " + aa + " 条数据");
      } else {
        this.$message.warning(
          "执行完毕，成功提交 " +
          aa +
          " 条数据，失败 " +
          bb +
          " 条, 取消" +
          cc +
          " 条"
        );
      }
    },
    //取消-
    cancel() {
      if (JSON.stringify(this.click_main) === "{}") {
        this.$message.warning("请先点击选中一条审核内容数据");
        return;
      }
      if (this.click_main.stateFlag == 5) {
        this.$message.warning("数据已审核,不可进行取消操作");
        return;
      }
      this.buttonLoading2 = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampleresults/cancelLimsSampleResult?id=" +
          this.click_main.srId,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.$message.success(res.message);
            this.searchData();
          } else {
            this.$message.error(res.message);
          }
          this.buttonLoading2 = false;
        })
        .catch((err) => {
          this.buttonLoading2 = false;
          this.$message.error(err.message);
        });
    },
    // 退回到个人
    backMan() {
      if (this.saveAnlyData.length < 1) {
        this.$message.warning("请选勾选需要退回的数据");
        return;
      }
      for (let i = 0; i < this.saveAnlyData.length; i++) {
        if (this.saveAnlyData[i].stateFlag == "2") {
          this.$message.warning("已审核的数据不能进行计算");
          return;
        }
      }
      let tempArr = [];
      this.saveAnlyData.map((item) => {
        tempArr.push(item.id);
      });
      this.backmanLoading = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampleresultds/sendBackSampleTest",
          tempArr,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
          this.backmanLoading = false;
        })
        .catch((err) => {
          this.backmanLoading = false;
          this.$message.error(err.message);
        });
    },
    // 退回到任务池
    backPlan() {
      if (this.saveAnlyData.length < 1) {
        this.$message.warning("请选勾选需要退回的数据");
        return;
      }
      for (let i = 0; i < this.saveAnlyData.length; i++) {
        if (this.saveAnlyData[i].stateFlag == "2") {
          this.$message.warning("已审核的数据不能进行计算");
          return;
        }
      }
      let tempArr = [];
      this.saveAnlyData.map((item) => {
        tempArr.push(item.id);
      });
      this.backPlanLoading = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampleresultds/sendBackTaskTest",
          tempArr,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
          this.backPlanLoading = false;
        })
        .catch((err) => {
          this.backPlanLoading = false;
          this.$message.error(err.message);
        });
    },
    //查询
    // searchData() {
    //   if (this.loading) return;
    //   this.loading = true;
    //   this.pageIndex = 1;
    //   this.pageSize = 500;
    //   this.pageIndex2 = 1;
    //   this.pageSize2 = 500;
    //   try {
    //     this.dataMainWl11().catch(err => console.error('dataMainWl11失败:', err))
    //       .then(() => this.dataMainWl21().catch(err => console.error('dataMainWl21失败:', err)))
    //       .finally(() => this.loading = false);
    //   } catch (error) {
    //     console.error('数据加载失败:', error);
    //     this.loading = false;
    //   }
    // },
    searchData() {
      if (this.loading) return;
      try {
        this.loading = true;
        this.pageIndex = 1;
        this.pageSize = 500;
        this.pageIndex2 = 1;
        this.pageSize2 = 500;
        this.dataMainWl11(),
          this.dataMainWl21()
      } catch (error) {
        console.error('数据加载失败:', error);
        this.loading = false;
      } finally {
        this.loading = false;
      }
    },
    // 车间列表（检测中心下）
    selectDepartment(val) {
      this.sectionNameType = [];
      this.companyNameType.find((item) => {
        if (val === item.orgCode) {
          this.sectionNameType = item.sysOrgList;
        }
      });
    },
    // 根据选中的车间名称，查询班组名称
    selectClass(val) {
      this.sectionClassType = [];
      this.sectionNameType.find((item) => {
        if (val === item.orgCode) {
          this.sectionClassType = item.sysOrgList;
          this.search.sectionNo = "";
        }
      });
    },
    // 未审核物料
    dataMainWl11() {
      this.click_main = {};
      this.tableData1 = [];
      this.total_main = 0;
      let startTime = null;
      let endTime = null;
      startTime = this.search.times[0] === null ? null : (this.search.times[0] + ' 00:00:00')
      endTime = this.search.times[1] === null ? null : (this.search.times[1] + ' 23:59:59')
      let obj = {
        object: {
          validFlag: "1",
          deptNo: this.search.deptNo,
          sectionNo: this.search.sectionNo,
          sampleNo: this.search.sampleNo,
          carNo:this.search.carNo
        },
        carNo: this.search.carNo,
        list: [4],
        mode: this.search.matClassNo,
        startTime: startTime,
        endTime: endTime,
        deptName: this.search.type
      };
      this.tableLoading11 = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampleresults/queryLimsSampleResultWl",
          obj,
          { individualType: "json" }
        )
        .then((res) => {
          console.log('search1    res', res)
          if (res.code == 0 || res.code == 200) {
            console.log('search1......', res.data);
            this.tableData11 = res.data;
            this.loading = false;
          } else {
            this.loading = false;
            // this.$message.error(res.message);
          }
          this.tableLoading11 = false;
        })
        .catch((err) => {
          this.loading = false;
          this.tableLoading11 = false;
          // this.$message.error(err.message);
        });
    },
    // 已审核物料
    dataMainWl21() {
      this.click_main2 = {};
      this.tableData2 = [];
      this.total_main2 = 0;
      let startTime = null;
      let endTime = null;
      startTime = this.search.times[0] === null ? null : (this.search.times[0] + ' 00:00:00')
      endTime = this.search.times[1] === null ? null : (this.search.times[1] + ' 23:59:59')
      let obj = {
        object: {
          validFlag: "1",
          deptNo: this.search.deptNo,
          sectionNo: this.search.sectionNo,
          sampleNo: this.search.sampleNo,
          carNo:this.search.carNo
        },
        carNo: this.search.carNo,
        list: [5],
        mode: this.search.matClassNo,
        startTime: startTime,
        endTime: endTime,
        deptName: this.search.type
      };
      this.tableLoading21 = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampleresults/queryLimsSampleResultWl",
          obj,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            console.log('search2......', res.data);
            this.tableData21 = res.data;
            this.loading = false;
          } else {
            this.$message.error(res.message);
            this.loading = false;
          }
          this.tableLoading21 = false;
        })
        .catch((err) => {
          this.tableLoading21 = false;
          this.$message.error(err.message);
          this.loading = false;
        });
    },
    // 未审核数据
    dataMain() {
      if (!this.click_main || !this.click_main.MAT_NO) {
        return false;
      }
      let startTime = null;
      let endTime = null;
      startTime = this.search.times[0] === null ? null : (this.search.times[0] + ' 00:00:00')
      endTime = this.search.times[1] === null ? null : (this.search.times[1] + ' 23:59:59')
      let obj = {
        object: {
          matNo: this.click_main.MAT_NO,
          validFlag: "1",
          deptNo: this.search.deptNo,
          sectionNo: this.search.sectionNo,
          sampleNo: this.search.sampleNo,
          carNo:this.search.carNo
        },
        carNo:this.search.carNo,
        list: [4],
        startTime: startTime,
        endTime: endTime,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
      };
      this.tableLoading1 = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampleresults/queryLimsSampleResultPage2",
          obj,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.tableData1 = res.data.data.list;
            this.cols = res.data.head;
            this.total_main = res.data.data.total;
            if (this.tableData1.length > 0) {
              this.isShowSuppName = res.data.data.list[0].SUPP_NAME
                ? true
                : false;
              this.isShowNetNum = res.data.data.list[0].NET_NUM ? true : false;
              this.isShowMarkNo = res.data.data.list[0].MARK_NO ? true : false;
              this.isShowEncryNo = res.data.data.list[0].ENCRY_NO
                ? true
                : false;
              this.isShowLotsNo = res.data.data.list[0].LOTS_NO ? true : false;
            }
          } else {
            this.$message.error(res.message);
          }
          this.tableLoading1 = false;
        })
        .catch((err) => {
          this.tableLoading1 = false;
          this.$message.error(err.message);
        });
    },
    parseFieldWithBracket(val) {
      // 初始化返回结果
      const result = {
        isValid: false, // 是否整体有效
        restValue: '',  // 括号后的剩余内容
        matchedValue: null // 匹配成功的拼接值
      };
      if (!val || typeof val !== 'string') {
        return result;
      }
      const reg = /([\d,.]+)\(([\d,.]+)\)/;
      const match = val.match(reg);
      if (!match) {
        return result;
      }
      const before = match[1].trim();
      const inside = match[2].trim();

      const bracketStartIndex = val.indexOf(')') + 1;
      if (bracketStartIndex > 0) {
        result.restValue = val.substring(bracketStartIndex);
      }
      console.log('val.....', val, 'bracketStartIndex.....', bracketStartIndex, 'restValue.....', result.restValue);
      const numCheckReg = /^[\d,.]+$/;
      if (!numCheckReg.test(before) || !numCheckReg.test(inside)) {
        console.log('包含非数字内容，跳过：', before, inside);
        return result;
      }
    },
    // 已审核数据
    dataMain2() {
      if (!this.click_main2 || !this.click_main2.MAT_NO) {
        return;
      }
      let startTime = null;
      let endTime = null;
      startTime = this.search.times[0] === null ? null : (this.search.times[0] + ' 00:00:00')
      endTime = this.search.times[1] === null ? null : (this.search.times[1] + ' 23:59:59')
      let obj = {
        object: {
          matNo: this.click_main2.MAT_NO,
          validFlag: "1",
          deptNo: this.search.deptNo,
          sectionNo: this.search.sectionNo,
          sampleNo: this.search.sampleNo,
          carNo:this.search.carNo
        },
        carNo:this.search.carNo,
        list: [5],
        startTime: startTime,
        endTime: endTime,
        pageIndex: this.pageIndex2,
        pageSize: this.pageSize2,
      };
      this.tableLoading2 = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampleresults/queryLimsSampleResultPage2",
          obj,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.tableData2 = res.data.data.list;
            console.log('tableData2....', this.tableData2)
            this.cols2 = res.data.head;
            this.total_main2 = res.data.data.total;
            if (this.tableData2.length > 0) {
              this.isShowSuppName = res.data.data.list[0].SUPP_NAME
                ? true
                : false;
              this.isShowNetNum = res.data.data.list[0].NET_NUM ? true : false;
              this.isShowMarkNo = res.data.data.list[0].MARK_NO ? true : false;
              this.isShowEncryNo = res.data.data.list[0].ENCRY_NO
                ? true
                : false;
              this.isShowLotsNo = res.data.data.list[0].LOTS_NO ? true : false;
            }
          } else {
            this.$message.error(res.message);
          }
          this.tableLoading2 = false;
        })
        .catch((err) => {
          this.tableLoading2 = false;
          this.$message.error(err.message);
        });
    },
    handleSizeChangeMain(pageSize) {
      this.pageIndex = 1;
      this.pageSize = pageSize;
      this.dataMain();
    },
    handleCurrentChangeMain(pageIndex) {
      this.pageIndex = pageIndex;
      this.dataMain();
    },
    handleSizeChangeMain2(pageSize) {
      this.pageIndex2 = 1;
      this.pageSize2 = pageSize;
      this.dataMain2();
    },
    handleCurrentChangeMain2(pageIndex) {
      this.pageIndex2 = pageIndex;
      this.dataMain2();
    },
    tableHeaderCellStyle() {
      return "color: rgb(255,255,255);border-bottom: 1px solid #DCDFE7;";
    },
    // 根据物料类型查询物料 - 查询
    selctMatName(val) {
      this.matNameType = [];
      this.search.matNo = "";
      if (!val) {
        return;
      }
      //物料名称
      this.axios
        .post(
          "pass/baseManagement/v1/limsbasematerialss/queryLimsBaseMaterialsPage/",
          {
            object: { validFlag: 1, matClassNo: val },
            pageIndex: 1,
            pageSize: 99999,
          },
          { individualType: "json" }
        )
        .then((res) => {
          this.matNameType = res.data.list;
        });
    },
    clearSelect() {
      this.search.sectionNo = "";
    },
    //选中数据1
    searchFollow1(val) {
      this.multipleSelection1 = val;
    },
    //选中数据2
    searchFollow2(val) {
      this.multipleSelection2 = val;
    },
    //选中数据13 (原始数据)
    searchFollow13(val) {
      this.multipleSelection13 = val;
    },
    // 表格1合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      let tableData = this.$refs.tableMain12.tableData;
      let rowsPan = 1;
      let thisColomnData = row[column["property"]];
      // 相同合同列的行合并
      if (column["property"] === "CONTRACT_NO" && thisColomnData) {
        if (
          rowIndex > 0 &&
          thisColomnData === tableData[rowIndex - 1][column["property"]]
        ) {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
        while (
          tableData[rowIndex + rowsPan] &&
          thisColomnData === tableData[rowIndex + rowsPan][column["property"]]
        ) {
          rowsPan += 1;
        }
        return {
          rowspan: rowsPan,
          colspan: 1,
        };
      }
    },
    // 表格2合并单元格
    arraySpanMethod2({ row, column, rowIndex, columnIndex }) {
      let tableData = this.$refs.tableMain22.tableData;
      let rowsPan = 1;
      let thisColomnData = row[column["property"]];
      // 相同合同列的行合并
      if (column["property"] === "CONTRACT_NO" && thisColomnData) {
        if (
          rowIndex > 0 &&
          thisColomnData === tableData[rowIndex - 1][column["property"]]
        ) {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
        while (
          tableData[rowIndex + rowsPan] &&
          thisColomnData === tableData[rowIndex + rowsPan][column["property"]]
        ) {
          rowsPan += 1;
        }
        return {
          rowspan: rowsPan,
          colspan: 1,
        };
      }
    },
    // 表格13(原始数据)合并单元格
    arraySpanMethod13({ row, column, rowIndex, columnIndex }) {
      let tableData = this.$refs.table13.tableData;
      let rowsPan = 1;
      let thisColomnData = row[column["property"]];
      let st = row["ST_ID"];
      // 相同合同列的行合并
      // if (columnIndex > 0 && columnIndex < 5 && thisColomnData) {
      //   if (rowIndex > 0 && thisColomnData === tableData[rowIndex - 1][column['property']]) {
      //     return {
      //       rowspan: 0,
      //       colspan: 0
      //     };
      //   }
      //   while (tableData[rowIndex + rowsPan] && thisColomnData === tableData[rowIndex + rowsPan][column['property']]) {
      //     rowsPan += 1
      //   }
      //   return {
      //     rowspan: rowsPan,
      //     colspan: 1
      //   };
      // }
      if (columnIndex > 0 && columnIndex < 8 && st) {
        if (rowIndex > 0 && st === tableData[rowIndex - 1]["ST_ID"]) {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
        while (
          tableData[rowIndex + rowsPan] &&
          st === tableData[rowIndex + rowsPan]["ST_ID"]
        ) {
          rowsPan += 1;
        }
        return {
          rowspan: rowsPan,
          colspan: 1,
        };
      }
    },
    rollback() {
      if (this.multipleSelection2.length == 0) {
        this.$message.warning("请勾选需要撤回审核的数据");
        return;
      }
      let ids = [];
      this.multipleSelection2.forEach((item) => {
        ids.push(item.SR_ID);
      });
      this.buttonLoadingBack = true;
      this.$confirm("确定退回已审核数据吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .post("pass/testManagement/v1/limssampleresults/rollback", ids, {
              individualType: "json",
            })
            .then((res) => {
              if (res.code == 0 || res.code == 200) {
                this.$message.success(res.message);
                this.buttonLoadingBack = false;
                this.dataMainWl11();
                this.dataMain2();
              } else {
                this.$message.error(res.message);
                this.buttonLoadingBack = false;
              }
            })
            .catch((e) => {
              this.$message.error(e.message);
              this.buttonLoadingBack = false;
            });
        })
        .catch((e) => {
          this.buttonLoadingBack = false;
          this.$message.warning("已取消退回！");
        });
    },
    showHistory(row) {
      if (!row) {
        return this.$message.warning("查询历史记录失败，参数错误!");
      }
      this.axios
        .post(
          "pass/testManagement/v1/limssamplehistorys/queryHistoryTest",
          row,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            //打开窗口
            this.historyShowFlag = !this.historyShowFlag;
            this.Params = Object.assign([{}], res.data);
          } else {
            this.$message.warning("查询历史记录失败!");
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    // 显示数据来源，valSource 格式 数值_stid_errstid_substid
    showDataSource(row, valSource) {
      if (!valSource || valSource.split("_").length < 4) {
        this.$message.error("参数错误");
        return;
      }
      // 记录参数，用于审核后刷新本页数据
      // this.valSource = valSource;
      this.curSrId = row.SR_ID;
      this.tableData13 = [];
      this.axios
        .get(
          "pass/testManagement/v1/limssampleresults/queryDataSource?valSource=" +
          valSource
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.tableData13 = res.data;
            if (this.tableData13) {
              this.tableData13.forEach((item) => {
                item.isReportName =
                  item.IS_REPORT == 0 ? "否" : item.IS_REPORT == 1 ? "是" : "";
                item.isAlarmName =
                  item.IS_ALARM == 0 ? "否" : item.IS_ALARM == 1 ? "是" : "";
              });
            }
            this.batchShow = true;
          } else {
            this.$message.error(res.message);
          }
          this.batchDataLoading = false;
        })
        .catch((e) => {
          this.batchDataLoading = false;
          this.$message.error(e.message);
        });
    },
    // 选中未审核物料
    handleCurrentChange11(val) {
      this.click_main = val;
      this.dataMain();
    },
    // 选中已审核物料
    handleCurrentChange21(val) {
      this.click_main2 = val;
      this.dataMain2();
    },
    // 关闭原始记录页面
    closebatch() {
      this.multipleSelection13 = [];
      this.batchShow = false;
      // this.dataMain();
    },
    // 审批不通过
    checkErr() {
      if (this.multipleSelection13.length < 1) {
        this.$message.warning("请先勾选要审批的原始数据");
        return;
      }
      this.backLoading = true;
      this.$confirm("确定审核不通过？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 审核不通过
          let arr = this.multipleSelection13;
          for (let item of arr) {
            item["SR_ID"] = this.curSrId;
            if (item["logMemo"] == null) {
              this.$message.error("退回原因不能为空！");
              return;
            }
          }
          this.axios
            .post(
              "pass/testManagement/v1/limssampleresults/checkErrLimsSampleResult",
              arr,
              { individualType: "json" }
            )
            .then((res) => {
              if (res.code == 0 || res.code == 200) {
                if (res.data && res.data != "true") {
                  this.$message.warning(res.data);
                } else {
                  this.$message.success(res.message);
                }
                this.dataMain();
                this.closebatch();
              } else {
                this.$message.error(res.message);
              }
              this.backLoading = false;
            })
            .catch((e) => {
              this.backLoading = false;
              this.$message.error(e.message);
            });
        })
        .catch((e) => {
          this.backLoading = false;
        });
    },
    selectStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        if (row.BS === "1") {
          return "error-row";
        }
      }
      if (row.IS_SEND_BACK === "1") {
        return "row-green";
      }
    },
  },
};
</script>
<style scoped></style>
<style lang="less">
.secondApprove {
  .common-title-name {
    margin-right: 40px;
  }
}
</style>
<style>
.row-green {
  background-color: #caf982 !important;
}

.el-table__body tr.current-row.row-green>td {
  background-color: #caf982 !important;
}
</style>
