<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row>
        <el-form-item label="退料单位" prop="backUnit">
          <el-input v-model="queryParams.backUnit" placeholder="退料单位"
            clearable style="width: 240px" disabled />
        </el-form-item>
        <el-form-item label="退料工程" prop="backPro">
          <el-input v-model="queryParams.backPro" placeholder="退料工程"
            clearable style="width: 240px" disabled/>
        </el-form-item>
        <el-form-item label="维修单号" prop="repairCode">
          <el-input v-model="queryParams.repairCode" placeholder="维修单号"
            clearable style="width: 240px" disabled/>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-back" size="mini"
          @click="goBack">维修管理</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini"
          @click="handlePass">合格</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" min-width="55" align="center" :selectable="selectable"/>
      <el-table-column label="序号" type="index" align="center" min-width="80"/>
      <el-table-column label="类型名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
      <el-table-column label="规格型号" align="center" prop="type" :show-overflow-tooltip="true"/>
      <el-table-column label="计量单位" align="center" prop="unitName" />
      <el-table-column label="退料数量" align="center" prop="typeRepairNum" show-overflow-tooltip></el-table-column>
      <el-table-column label="已修数量" align="center" prop="typeRepairedNum" show-overflow-tooltip></el-table-column>
      <el-table-column label="待报废数量" align="center" prop="typeScrapNum" show-overflow-tooltip></el-table-column>
      <el-table-column label="待修数量" align="center" prop="disrepairNum" show-overflow-tooltip></el-table-column>
      <el-table-column label="管理模式" align="center" prop="manageType">
        <template slot-scope="scope">
          <!-- 0编码1数量 -->
          <div v-if="scope.row.manageType == 0">编码管理</div>
          <div v-if="scope.row.manageType == 1">数量管理</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200px">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="handleRepair(scope.row)" v-if="scope.row.disrepairNum!=0">维修</el-button>
          <el-button size="mini" type="success"  @click="handleAddSingle(scope.row)" v-if="scope.row.disrepairNum!=0">合格</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- ****************编码维修****************** -->
    <!-- 编码维修 -->
    <el-dialog title="编码维修" :visible.sync="openCode" width="1200px" append-to-body>
      <el-table :data="repairDeviceList" width="100%" height="450px">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="类型名称" prop="typeName" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="规格型号" prop="type" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="设备编码" prop="code" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="维修状态" prop="status" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.row.status == '1'" style="color: green">{{ "已完成" }}</div>
            <div v-if="scope.row.status == '0'" style="color: red">{{ "未完成" }}</div>
          </template></el-table-column>
        <el-table-column label="配件信息" prop="partInfo" align="center" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="附件" align="center" width="100">
          <template slot-scope="scope">
            <div style="display: flex;align-items: center;justify-content: center;">
              <el-upload
                ref="upload"
                :limit="3"
                :headers="upload.headers"
                :action="upload.url"
                :show-file-list="false"
                accept=".png, .jpg, .jpeg, .pdf, .doc, .docx"
                :on-success="handleFileSuccess2"
                :auto-upload="true"
              >
                <el-button
                  v-if="scope.row.fileUrl != '' && scope.row.fileUrl != null"
                  size="mini"
                  type="text"
                  @click="beforeFileUpload(scope.row)"
                >
                  上传
                </el-button>
              </el-upload>
              <!-- 查看按钮 - 显示图片数量 -->
              <el-button
                size="mini"
                type="text"
                @click="picturePreview(scope.row)"
                v-if="scope.row.bmFileInfos && scope.row.bmFileInfos.length > 0"
              >
                查看图片
                <span v-if="getImageCount(scope.row) > 0" style="margin-left: 2px; color: #409EFF;">
    ({{ getImageCount(scope.row) }})
  </span>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" v-if="scope.row.status=='0'"
              @click="openInnerDialog(scope.row)"
              >内部维修</el-button>
            <el-button size="mini" type="warning" v-if="scope.row.status=='0'"
              @click="openBackDialog(scope.row)"
              >返厂维修</el-button>
            <el-button size="mini" type="danger" v-if="scope.row.status=='0'"
              @click="openScrapDialog(scope.row)"
              >待报废</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;height: 50px;display: flex;justify-content: flex-end;align-items: center;">
        <el-button type="primary" size="mini" @click="saveCodeDialog">保存</el-button>
        <el-button type="normal" size="mini" @click="cancelCodeDialog">取消</el-button>
      </div>
    </el-dialog>
    <!-- 内部维修 -->
    <el-dialog title="内部维修" :visible.sync="openInner" width="900px" append-to-body>
      <el-row :gutter="18" class="mb8">
        <el-col :span="12">
          <div style="width: 100%;height: 100%;display: flex;align-items: center;">
            <span style="width: 80px">配件型号:</span>
            <treeselect
              v-model="partTypeId"
              :options="partTypeTree"
              :normalizer="normalizer"
              :searchable="true"
              :disable-branch-nodes="true"
              :show-count="false"
              :expand-on-click-node="false"
              placeholder="请选择配件型号"
              style="width: 80%;"
              @select="partChange"
            />
          </div>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="resetInner">重置</el-button>
        </el-col>
      </el-row>
      <el-table :data="partTableList" width="100%" height="450px">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="配件名称" prop="typeName" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="规格型号" prop="typeCode" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="是否收费" prop="partType" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-select v-model="scope.row.partType"
              placeholder="是否收费" filterable clearable>
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="配件数量" prop="partNum" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.partNum"
              placeholder="配件数量" type="number" min="1"
              clearable style="width: 100%"
              @input="inputPartNum(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120px">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleDeletePart({ ...scope.row, index: scope.$index })">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;height: 50px;display: flex;justify-content: flex-end;align-items: center;">
        <el-button type="primary" size="mini" @click="saveInnerDialog">保存</el-button>
        <el-button type="normal" size="mini" @click="openInner = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 返厂维修 -->
    <el-dialog title="返厂维修" :visible.sync="openBack" width="900px" append-to-body>
      <el-form :model="backForm" ref="backForm" size="small" :rules="rules" :inline="true" label-width="100px">
        <el-form-item label="物资厂家" prop="supplierId">
          <el-select v-model="backForm.supplierId" placeholder="物资厂家" clearable filterable style="width: 240px">
            <el-option
              v-for="item in supplierList"
              :key="item.supplierId"
              :label="item.supplier"
              :value="item.supplierId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="backForm.remark"
            placeholder="请输入备注"
            clearable maxlength="150" type="textarea"
            style="width: 240px" rows="1"
          />
        </el-form-item>
      </el-form>
      <el-table :data="backTableList" width="100%" height="450px">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="配件名称" prop="partName" align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <el-input v-model="scope.row.partName" style="width: 100%"  maxlength="20"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="是否收费" prop="partType" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-select v-model="scope.row.partType" placeholder="是否收费" filterable clearable>
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="配件数量" prop="partNum" align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <el-input-number v-model="scope.row.partNum" controls-position="right" style="width: 100%" :min="0"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="维修金额" prop="partPrice" align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <el-input-number v-model="scope.row.partPrice" controls-position="right" style="width: 100%" :min="0"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80px">
          <template slot-scope="scope">
            <div style="width: 100%;height: 40px;display: flex;align-items: center;justify-content: space-between;">
              <i class="el-icon-plus" style="font-size: 20px; color: blue" @click="handleAddBack"></i>
              <i class="el-icon-minus" style="font-size: 20px; color: red" @click="handleDeleteBack({ ...scope.row, index: scope.$index })"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;height: 50px;display: flex;justify-content: flex-end;align-items: center;">
        <el-button type="primary" size="mini" @click="saveBackDialog">保存</el-button>
        <el-button type="normal" size="mini" @click="openBack = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 待报废 -->
    <el-dialog
      title="待报废"
      :visible.sync="openScrap"
      width="900px"
      append-to-body
    >
      <el-form
        :model="scrapForm"
        ref="scrapForm"
        size="small"
        :rules="scrapRules"
        :inline="true"
        label-width="100px"
      >
        <!-- <el-form-item label="报废原因" prop="scrapReason">
          <el-select
            v-model="scrapForm.scrapReason"
            placeholder="报废原因"
            clearable
            filterable
            style="width: 250px"
          >
            <el-option
              v-for="item in damageReasonList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="损坏原因" prop="scrapType">
          <el-select
            v-model="scrapForm.scrapType"
            placeholder="损坏原因"
            clearable
            filterable
            style="width: 250px"
          >
            <el-option
              v-for="item in damageReasonList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
        </el-select>
        </el-form-item>
        <el-form-item label="报废原因" prop="scrapReason">
              <el-input
                v-model="scrapForm.scrapReason"
                placeholder="请输入报废原因"
                clearable
                maxlength="150"
                type="textarea"
                style="width: 300px"
                rows="4"
                >
              </el-input>
        </el-form-item>
        <el-row>
          <el-form-item label="照片" required>
            <el-upload
              action="#"
              :file-list="fileList"
              :show-file-list="true"
              :auto-upload="false"
              :key="uploadKey"
              list-type="picture-card"
              accept=".png, .jpg, .jpeg"
              :on-change="handleChange"
              :class="{ disabled: uploadDisabled }"
              :on-preview="picturePreview"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>

      <div
        style="
          width: 100%;
          display: flex;
          justify-content: flex-end;
          align-items: center;
        "
      >
        <el-button type="primary" size="mini" @click="saveSubmit"
          >保存</el-button
        >
        <el-button type="normal" size="mini" @click="saveCancel"
          >取消</el-button
        >
      </div>
    </el-dialog>

    <!-- ****************数量维修****************** -->
    <!-- 数量维修 -->
    <el-dialog title="数量维修" :visible.sync="openNum" width="1250px" append-to-body>
      <el-row :gutter="24" style="padding-bottom: 20px;border-bottom: 2px solid #dcdfe6;">
        <el-col :span="4">
          <div style="font-weight: 600;">
            物资名称： {{ typeNameTemp }}
          </div>
        </el-col>
        <el-col :span="4">
          <div style="font-weight: 600;">
            规格型号： {{   typeTemp }}
        </div>
        </el-col>
        <el-col :span="4">
          <div style="font-weight: 600;">
            待维修数量： {{ disrepairNumTemp }}
        </div>
        </el-col>
      </el-row>

      <div class="dialog-content">
        <div class="left">
          <!-- 左侧内容 -->
          <el-form ref="formLeft" :model="formLeft" :rules="rulesLeft" label-width="80px">
            <el-row :gutter="24">
              <el-col :span="20">
                <el-form-item label="内部维修数量" prop="repairNum" label-width="120px">
                  <el-input v-model.number="formLeft.repairNum" placeholder="请输入内部维修数量"
                    maxlength="20" type="number" min="0"
                    style="width: 220px" @input="waitRepairCount"/>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-for="(item, index) in partItems" :key="index" class="dynamic-item">
              <el-row :gutter="24">
                <el-col :span="20">
                  <el-form-item label="配件型号" prop="partId">
                    <treeselect
                      v-model="item.partId"
                      :options="partTypeTreeTwo"
                      :searchable="true"
                      :disable-branch-nodes="true"
                      :show-count="false"
                      :expand-on-click-node="false"
                      placeholder="请选择配件型号"
                      style="width: 200px;"
                      @select="partTypeSelect"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="20">
                  <el-form-item label="配件数量" prop="partNum">
                    <el-input
                      v-model.number="item.partNum"
                      placeholder="请输入" @input="inputPartNum(item)"
                      maxlength="20" type="number" :min="1"
                      style="width: 200px;"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="16">
                  <el-form-item
                    label="是否收费"
                    prop="partType"
                  >
                    <el-select
                      v-model="item.partType"
                      placeholder="请选择"
                      filterable
                      clearable
                      style="width: 200px;"
                    >
                      <el-option label="是" value="1"></el-option>
                      <el-option label="否" value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6" style="margin-top: 10px;display: flex;justify-content: center;align-items: center;">
                  <i
                    class="el-icon-plus"
                    style="font-size: 20px; color: blue"
                    @click="addPartItem"
                  ></i>
                  <i
                    class="el-icon-minus"
                    style="font-size: 20px; color: red"
                    v-if="index != 0"
                    @click="removePartItem(index)"
                  ></i>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
        <!-- 竖线 -->
        <div class="divider"></div>
        <div class="middle">
          <!-- 中间内容 -->
          <el-form ref="formMiddle" :model="formMiddle" :rules="rulesMiddle" label-width="80px">
            <el-row :gutter="24">
              <el-col :span="20">
                <el-form-item label="返厂维修数量" prop="repairNum" label-width="120px">
                  <el-input v-model.number="formMiddle.repairNum" placeholder="请输入返厂维修数量" maxlength="20" type="number" min="0"  style="width: 220px" @input="waitRepairCount"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="20">
                <el-form-item label="物资厂家" prop="supplierId">
                  <el-select v-model="formMiddle.supplierId"
                    placeholder="物资厂家" clearable filterable style="width: 260px">
                    <el-option v-for="item in supplierList"
                      :key="item.supplierId"
                      :label="item.supplier"
                      :value="item.supplierId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-for="(item, index) in partItemsMiddle" :key="index" class="dynamic-item">
              <el-row :gutter="24">
                <el-col :span="10">
                  <el-form-item label="配件名称" prop="partName"  label-width="80px">
                    <el-input v-model="item.partName" placeholder="请输入" maxlength="20" style="width: 90px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="是否收费" prop="partType" label-width="70px">
                    <el-select v-model="item.partType" placeholder="请选择" filterable clearable style="width: 80px">
                      <el-option label="是" value="1"></el-option>
                      <el-option label="否" value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="9">
                  <el-form-item label="配件数量" prop="partNum" label-width="80px"  >
                    <el-input v-model.number="item.partNum" placeholder="请输入配件数量"
                      maxlength="20" type="number" :min="0" style="width: 90px" @change="partNumChange(item, $event)"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="9">
                  <el-form-item label="金额" prop="partPrice" label-width="70px">
                    <el-input v-model.number="item.partPrice" placeholder="请输入金额"
                      maxlength="20" type="number" :min="0" style="width: 95px" @change="partPriceChange(item, $event)">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6" style="margin-top: 10px;display: flex;justify-content: center;align-items: center;">
                  <i class="el-icon-plus" style="font-size: 20px; color: blue" @click="addPartItemMiddle"></i>
                  <i class="el-icon-minus" style="font-size: 20px; color: red" v-if="index != 0" @click="removePartItemMiddle(index)"></i>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
        <!-- 竖线 -->
        <div class="divider"></div>
        <div class="right">
          <!-- 右侧内容 -->
          <el-form :model="formRight" ref="formRight" size="small" :rules="rulesRight" :inline="true" label-width="80px">
            <el-col :span="20">
              <el-form-item label="待报废数量" prop="scrapNum" label-width="100px">
                <el-input v-model.number="formRight.scrapNum" placeholder="请输入待报废数量" maxlength="20" type="number" style="width: 210px" min="0" @input="waitRepairCount"/>
              </el-form-item>
            </el-col>
            <el-form-item label="损坏原因" prop="scrapType">
              <el-select v-model="formRight.scrapType" placeholder="损坏原因" clearable filterable style="width: 240px">
                <el-option v-for="item in damageReasonList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="报废原因" prop="scrapReason">
              <el-input v-model="formRight.scrapReason" placeholder="请输入报废原因" clearable maxlength="150" type="textarea" style="width: 240px" rows="4"></el-input>
            </el-form-item>
          <el-form-item label="照片" required>
            <el-upload
              action="#"
              :file-list="fileList"
              :show-file-list="true"
              :auto-upload="false"
              :key="uploadKey"
              list-type="picture-card"
              accept=".png, .jpg, .jpeg"
              :on-change="handleChange"
              :class="{ disabled: uploadDisabled }"
              :on-preview="picturePreview"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          </el-form>
        </div>
      </div>

      <div style=" width: 100%; height: 50px; display: flex; justify-content: flex-end; align-items: center;">
        <el-button type="primary" size="mini" :disabled="flagSave" @click="saveNumAll">保存</el-button>
        <el-button type="normal" size="mini" @click="saveCancelAll">取消</el-button>
      </div>
    </el-dialog>

    <!-- 图片查看弹窗 -->
<!--    <el-dialog :visible.sync="dialogVisible" width="500px" height="500px">-->
<!--      <img width="100%" height="500px" :src="dialogImageUrl" />-->
<!--    </el-dialog>-->

    <!-- 图片查看弹窗 - 支持多张图片切换 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="600px"
      height="600px"
      :close-on-click-modal="false"
      @closed="handlePreviewClose"
    >
      <div style="position: relative; height: 500px; background-color: #f5f5f5;">
        <!-- 图片显示区域 -->
        <img
          v-if="dialogImageUrl"
          width="100%"
          height="100%"
          :src="dialogImageUrl"
          style="object-fit: contain;"
        />

        <!-- 多图导航 - 当有多张图片时显示 -->
        <div
          v-if="previewImageFiles && previewImageFiles.length > 1"
          style="position: absolute; top: 50%; width: 100%; transform: translateY(-50%);"
        >
          <!-- 上一张按钮 -->
          <el-button
            circle
            size="mini"
            style="position: absolute; left: 10px; background: rgba(0,0,0,0.3); color: white;"
            @click="prevImage"
          >
            <i class="el-icon-arrow-left"></i>
          </el-button>

          <!-- 下一张按钮 -->
          <el-button
            circle
            size="mini"
            style="position: absolute; right: 10px; background: rgba(0,0,0,0.3); color: white;"
            @click="nextImage"
          >
            <i class="el-icon-arrow-right"></i>
          </el-button>
        </div>

        <!-- 图片计数器 -->
        <div
          v-if="previewImageFiles && previewImageFiles.length > 1"
          style="position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); background: rgba(0,0,0,0.7); color: white; padding: 5px 15px; border-radius: 15px; font-size: 14px;"
        >
          {{ previewFileIndex + 1 }} / {{ previewImageFiles.length }}
        </div>

        <!-- 图片名称 -->
<!--        <div-->
<!--          v-if="previewImageFiles && previewImageFiles.length > 0 && previewImageFiles[previewFileIndex]"-->
<!--          style="position: absolute; bottom: 40px; left: 0; width: 100%; text-align: center; background: rgba(0,0,0,0.5); color: white; padding: 5px; font-size: 12px;"-->
<!--        >-->
<!--          {{ previewImageFiles[previewFileIndex].name }}-->
<!--        </div>-->
      </div>

      <!-- 缩略图列表 -->
      <div
        v-if="previewImageFiles && previewImageFiles.length > 1"
        style="margin-top: 10px; padding: 10px; background-color: #f8f8f8; border-radius: 5px; max-height: 80px; overflow-x: auto; white-space: nowrap;"
      >
        <div
          v-for="(file, index) in previewImageFiles"
          :key="index"
          :style="{
        display: 'inline-block',
        margin: '0 5px',
        border: '2px solid',
        borderColor: previewFileIndex === index ? '#409EFF' : '#ddd',
        borderRadius: '4px',
        cursor: 'pointer',
        opacity: previewFileIndex === index ? 1 : 0.8,
        transition: 'all 0.3s'
      }"
          @click="previewFileIndex = index; dialogImageUrl = file.url;"
        >
          <img
            :src="file.url"
            :alt="file.name"
            style="width: 50px; height: 50px; object-fit: cover;"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getListFacturer } from "@/api/ma/supplier";

import {
  getAppRepairMaTypeList,
  partTypeTreeList,
  saveCodeList,
  auditPass, partTypeTreeListNew,
} from "@/api/repair/repair.js";

import { mapState } from "vuex";
import { getInfo, h } from "@/api/login";
import { getToken } from "@/utils/auth";
import { imgUpLoadThree, fileUpLoad } from "@/api/system/upload";
import { downloadFile, downloadFileData } from "@/utils/download";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "",
  dicts: ["ma_machine_status"],
  components: { Treeselect },
  props: {
    repairRow: {
      type: [Object],
    },
  },
  data() {
    return {
      uploadKey: Date.now(),
      partItems: [{ partNum: "", partType: "0", partId:null, storageNum:"" }],
      partItemsMiddle: [{ partName: "", partNum: "", partPrice: "0", partType: "0" }],
      // 遮罩层
      loading: false,
      // 选中数组
      idsTemp: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        backUnit: "",
        backPro: "",
        repairCode: "",
        equipmentList: [],
      },
      equipmentList: [],

      //编码维修
      openCode: false,
      repairRowData: {},
      repairDeviceList: [], //编码表格
      //图片查看弹窗
      dialogImageUrl: "",
      dialogVisible: false,
      fileData: {},
      //上传
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/upload",
      },
      //内部维修
      openInner: false,
      innerRowData: {},
      //配件表格数据
      partTableList: [],
      //选中的配件
      partTypeId: null,
      // 配件树结构数据
      partTypeTree: [],

      // 配件树配置
      partTypeTreeProps: {
        children: "children",
        label: "label",
        // multiple: false,
        value: "id",
        multiple: true,
      },
      propsKey: 1000,

      //返厂维修
      openBack: false,
      backRowData: {},
      //表格数据
      backTableList: [],
      backForm: {
        //返厂厂家
        supplierId: null,
        //备注
        remark: "",
      },
      rules: {
        supplierId: [
          {
            required: true,
            message: "请选择厂家",
            trigger: "change",
          },
        ],
      },
      //厂商下拉选
      supplierList: [],

      //待报废
      openScrap: false,
      scrapRowData: {},
      scrapForm: {
        scrapReason: "",
        damageReason: "",
        otherReason: "",
        fileName: "",
        fileUrl: "",
      },
      damageReasonList: [
        { label: "自然损坏", id: 0 },
        { label: "人为损坏", id: 1 },
      ], //自然损坏、人为损坏
      scrapRules: {
        scrapType: [
          {
            required: true,
            message: "请选择损坏原因",
            trigger: "change",
          },
        ],
        scrapReason: [
          {
            required: true,
            message: "请输入报废原因",
            trigger: "blur",
          },
        ],

      },
      //树状勾选
      deviceTypeTree: [], // 设备 树结构数据
      // 设备 树显示 配置
      deviceTypeTreeProps: {
        children: "children",
        label: "label",
        // multiple: false,
        value: "id",
        multiple: true,
      },
      // 选中的设备类型
      deviceType: null,
      companyId: "",
      createBy: "",

      //数量维修
      openNum: false,
      partTypeTreeTwo: [],

      //数量维修三部分
      formLeft: {
        repairNum:0
      },
      formMiddle: {
        supplierId:undefined,
        repairNum:0
      },
      formRight:{
        scrapType:1,
        scrapReason:undefined,
        scrapNum:0
      },

      rulesLeft: {
        repairNum: [
          {
            required: true,
            message: "请输入内部维修数量",
            trigger: "blur",
          },
        ],

      },
      rulesMiddle: {
        repairNum: [
          {
            required: true,
            message: "请输入返厂维修数量",
            trigger: "blur",
          },
        ],

        supplierId: [
          {
            required: true,
            message: "请选择厂家",
            trigger: "change",
          },
        ],

        partPrice: [
          {
            required: false,
            message: "请输入金额",
            trigger: "blur",
          },
          // {
          //   validator: (rule, value, callback) => {
          //     const regex = /^[+-]?(0|[1-9]\d*)(\.\d+)?$/;
          //     if(!regex.test(value)){
          //       return callback(new Error('请勿输入非数字'));
          //     }
          //     const pat = parseFloat(value);
          //     console.log('pat',pat)
          //     if(pat.toString().includes('.')==true){
          //       if (pat <0 ||pat.toString().split(".")[1].length>6) {
          //       callback(new Error('请必须输入大于0的数据且小数点后最多保留六位'));
          //     } else {
          //       callback();
          //     }
          //     }else{
          //       if (pat<0) {
          //       callback(new Error('请必须输入大于0的数据且小数点后最多保留六位'));
          //     }else{
          //       callback();
          //     }
          //   }
          //   },
          //   trigger: 'blur'
          // }
        ]
      },
      rulesRight: {
        scrapNum: [
          {
            required: true,
            message: "请输入返厂维修数量",
            trigger: "blur",
          },
        ],

        scrapType: [
          {
            required: true,
            message: "请选择损坏原因",
            trigger: "change",
          },
        ],
        scrapReason: [
          {
            required: true,
            message: "请输入报废原因",
            trigger: "blur",
          },
        ],
      },

      //文件数组
      fileList: [],
      //暂存的文件数组
      fileListTemp:[],

      typeTemp: "",
      typeNameTemp: "",
      //待维修数量
      disrepairNumTemp: undefined,
      //数量维修是否能保存
      flagSave: true,
      //合格勾选对象数组
      idsList:[],
      //一级页面传来的id
      taskIdTemp:undefined,
      previewRow: null,              // 当前预览的行数据
      previewImageFiles: [],         // 当前行的图片文件列表
      previewFileIndex: 0,           // 当前预览的图片索引
    };
  },
  mounted() {
    console.log(this.repairRow);
    this.GetViewByApply();
    this.supplierInfoList();
  },
  computed: {
    //图片上传1张后，隐藏上传框
    uploadDisabled() {
      return this.fileList.length > 4;
    },
    ...mapState(["user"]),
  },
  methods: {
    // 重置表单方法
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    goBack() {
      this.$emit("goBackPage");
    },
    // 计算行数据中的图片数量
    getImageCount(row) {
      if (!row.bmFileInfos || row.bmFileInfos.length === 0) return 0;

      const imageFiles = row.bmFileInfos.filter(file => {
        const parts = file.name.split(".");
        const extension = parts.pop().toLowerCase();
        return ["jpg", "jpeg", "png", "gif", "bmp", "webp"].includes(extension);
      });

      return imageFiles.length;
    },
    // 获取 任务详情数据
    async GetViewByApply() {
      console.log(this.repairRow);
      this.queryParams.backUnit = this.repairRow.backUnit;
      this.queryParams.backPro = this.repairRow.backPro;
      this.queryParams.repairCode = this.repairRow.repairCode;
      let param = {
        taskId: this.repairRow.taskId,
        keyword: "",
      };
      this.taskIdTemp = this.repairRow.taskId;
      const res = await getAppRepairMaTypeList(param);
      this.equipmentList = res.data;
      this.equipmentList.forEach((e) => {
        e.disrepairNum = Number(e.typeRepairNum) - Number(e.typeRepairedNum) - Number(e.typeScrapNum);
      });
      // this.GetDeviceTypeTreeFn(data.backApplyInfo.agreementId)
    },
    //是否可用勾选框
    selectable(row) {
      if (row.disrepairNum != 0) {
      return true;
      } else {
          return false
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.queryParams.equipmentList = selection;
      // this.idsList = [];
      selection.map((item) => {
        if(item.ids.length>0){
          item.ids.forEach((itemTwo =>{
            this.idsTemp.push(itemTwo)
          }))
        }
      })
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 批量合格按钮操作 */
    handlePass() {
      if (this.idsTemp.length == 0) {
        this.$alert("请至少勾选一条数据", "提示", {
          type: "warning",
          confirmButtonText: "确定",
        });
      }else{
        console.log(this.idsTemp)
        auditPass(this.idsTemp).then(async(response) => {
          if (response.code == 200) {
          let param = {
            taskId: this.repairRow.taskId,
          };
          this.taskIdTemp = this.repairRow.taskId;
          const res = await getAppRepairMaTypeList(param);
          this.equipmentList = res.data;
          this.equipmentList.forEach((e) => {
            e.disrepairNum = Number(e.typeRepairNum) - Number(e.typeRepairedNum)-Number(e.typeScrapNum);
          });
            this.$modal.msgSuccess("通过成功");
          }
        });
      }
    },
    //单个合格按钮操作
    handleAddSingle(row){
      let ids = [];
      ids = row.ids;
      this.$modal
        .confirm("是否确认合格所选择的数据项？")
        .then(function () {
          return auditPass(ids);
        })
        .then(async() => {
          let param = {
            taskId: this.repairRow.taskId,
          };
          this.taskIdTemp = this.repairRow.taskId;
          const res = await getAppRepairMaTypeList(param);
          this.equipmentList = res.data;
          this.equipmentList.forEach((e) => {
            e.disrepairNum = Number(e.typeRepairNum) - Number(e.typeRepairedNum)-Number(e.typeScrapNum);
          });
          this.$modal.msgSuccess("合格成功");
        })
        .catch(() => {});
    },
    /** 维修按钮操作 */
    handleRepair(row) {
      ////编码
      if (row.manageType == 0) {
        this.repairRowData = row;
        this.repairDeviceList = [];
        this.openCode = true;
      } else {
      ////数量
        this.innerRowData = row;
        this.partTableList = [];
        this.typeTemp = row.type;
        this.typeNameTemp = row.typeName;
        this.disrepairNumTemp = row.typeRepairNum - row.typeRepairedNum - row.typeScrapNum;
        this.repairRowData = row;
        this.repairDeviceList = [];
        const params = {};
        partTypeTreeListNew(params).then((res) => {
          this.partTypeTreeTwo = this.filterTree(res.data);
          this.resetForm("formLeft");
          this.resetForm("formMiddle")
          this.resetForm("formRight")
          this.partItems =  [{ partNum: "", partType: "0", partId:null, storageNum:"" }],
          this.partItemsMiddle= [
            { partName: "", partNum: "", partPrice: "0", partType: "0" },
          ],
          this.openNum = true;
        });
      }
      if (this.repairRowData.repairDeviceList&&this.repairRowData.repairDeviceList.length > 0) {
        this.repairDeviceList = this.repairRowData.repairDeviceList;
      }
    },
    //遍历树状数据
    filterTree(nodes) {
      return nodes.map((node) => {
        if(node.level==3){
          node.label=node.label+`（${node.storageNum}）`
        }
        if (node.children) {
          node.children = this.filterTree(node.children);
        }
        return node;
      });
    },



    // ********编码维修********
    // 编码维修弹窗保存
    async saveCodeDialog() {
      if (this.repairDeviceList.length > 0) {
        this.repairDeviceList.forEach((item) => {
          item.inRepairList = []
          item.outRepairList = []
        })
      }
      this.repairRowData.repairDeviceList = this.repairDeviceList;
      await  saveCodeList(this.repairRowData.repairDeviceList).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("保存成功");
          this.fileList = [];
          this.fileListTemp = [];
        }
      });
      let param = {
        taskId: this.repairRow.taskId,
        keyword: "",
      };
      this.taskIdTemp = this.repairRow.taskId;
      const res = await getAppRepairMaTypeList(param);
      this.equipmentList = res.data;
      this.equipmentList.forEach((e) => {
        e.disrepairNum = Number(e.typeRepairNum) - Number(e.typeRepairedNum)-Number(e.typeScrapNum);
      });
      this.openCode = false;
      // console.log(this.equipmentList)
    },
    // 编码维修弹窗取消
    async cancelCodeDialog(){
      let param = {
        taskId: this.repairRow.taskId,
        keyword: "",
      };
      this.taskIdTemp = this.repairRow.taskId;
      const res = await getAppRepairMaTypeList(param);
      this.equipmentList = res.data;
      this.equipmentList.forEach((e) => {
        e.disrepairNum = Number(e.typeRepairNum) - Number(e.typeRepairedNum)-Number(e.typeScrapNum);
      });
      this.openCode = false;
    },



    // ********编码--内部维修********
    //编码-内部维修
    openInnerDialog(row) {
      console.log('111111111',row)
      this.innerRowData = row;
      this.partTableList = [];
      if (this.innerRowData.partTableList && this.innerRowData.partTableList.length > 0) {
        this.partTableList = JSON.parse(JSON.stringify(this.innerRowData.partTableList));
      }
      // 重置配件选择器
      this.partTypeId = null;
      this.getPartTypeTreeData();
      this.openInner = true;
    },
    //编码-内部维修-配件树
    async getPartTypeTreeData() {
      const params = {};
      const res = await partTypeTreeList(params);
      console.log("treeData==========", res);
      this.partTypeTree = res.data;
    },
    //编码-内部维修- 反显 树结构数据获取父 -旧组件
    getSelectId(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          //查询到就返回该数组对象的value
          return [list[i].id];
        }
        if (list[i].children) {
          let node = this.getSelectId(list[i].children, id);
          if (node !== undefined) {
            //查询到把父节把父节点加到数组前面
            node.unshift(list[i].id);
            return node;
          }
        }
      }
    },
    //编码-内部维修- 切换 设备类型树-旧组件
    async partTypeChange(val) {
      const partTypeList = this.$refs.partTypeCascader.getCheckedNodes();
      console.log(partTypeList);
      let tempList = [];
      if (val.length > 0) {
        const items = val.map((e) => {
          return e[2];
        });
        for (let i of items) {
          for (let z of partTypeList) {
            if (z.data.id === i) {
              const parent = z.parent;
              console.log(parent);
              const obj = JSON.parse(JSON.stringify(z.data));
              console.log(obj);
              obj.typeCode = obj.label;
              obj.typeName = parent.label;
              obj.partType = "0";
              obj.partNum = 1;
              console.log(obj);
              tempList.push(obj);
              break;
            }
          }
        }
        const newDataListNew = [...this.partTableList, ...tempList];
        const map = new Map();
        for (let item of newDataListNew) {
          if (!map.has(item.id)) {
            map.set(item.id, item);
          }
        }
        const newArray = [...map.values()];
        let newArray_array = [];
        items.forEach((e) => {
          newArray.forEach((j) => {
            if (e == j.id) {
              newArray_array.push(j);
            }
          });
        });
        this.partTableList = newArray_array;
      } else {
        this.partTableList = [];
      }
    },
    //编码-内部维修- 切换 设备类型树-旧组件
    partChange(e){
      console.log(e)
      let isHas = this.partTableList.findIndex(v=>v.partId==e.id)
      let obj = {}
      if(isHas>-1){
        this.$message.error("已存在所选配件");
      }else{
        let parentNode = this.findParentNode(this.partTypeTree, e);
        // console.log(parentNode)
        obj.typeName = parentNode.label;
        obj.partId = e.id;
        obj.typeCode = e.label;
        obj.storageNum = e.storageNum;
        obj.partType = "0";
        obj.partNum = 1;
        this.partTableList.push(obj)
      }
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
        if (node.children && !node.children.length) {
            delete node.children
        }
        return {
          id: node.id,
          label: node.storageNum>0?node.label+"("+ node.storageNum +")":node.label,
          children: node.children
        }
    },
    //treeselect获取父节点
    findParentNode(nodes, targetNode) {
      for (let node of nodes) {
        if (node.children && node.children.includes(targetNode)) {
          return node; // 返回父节点信息
        } else if (node.children) {
          const parent = this.findParentNode(node.children, targetNode); // 递归查找子树中的父节点
          if (parent) return parent; // 如果找到，返回父节点信息并停止递归
        }
      }
      return null; // 未找到父节点时返回null
    },
    //编码-内部维修- 重置按钮操作
    resetInner() {
      this.partTypeId=null;
      this.partTableList = [];
    },
    //编码-内部维修- 删除
    handleDeletePart(row) {
      this.partTableList.forEach((item, index) => {
        if (item.id == row.id) {
          this.partTableList.splice(index, 1);
        }
      });
    },
    //编码-内部维修- 弹窗保存
    saveInnerDialog() {
      // const isNum = this.partTableList.some(
      //   (item) => item.partNum == 0 || item.partNum == undefined
      // );
      // if (isNum) {
      //   this.$message.error("配件数量不能为0！");
      //   return;
      // }
      this.innerRowData.partTableList = this.partTableList;
      this.innerRowData.repairType = 1;
      this.innerRowData.partTableList.forEach((item) => {
        this.innerRowData.codeInRepairPartList.push(item);
      });
      // if(this.partTableList.length==0) {
      //   this.$message.error("请添加配件！");
      //   return;
      // }else{
        this.innerRowData.status = 1;
        this.openInner = false;
      // }
      // console.log(this.equipmentList)
    },



    // ********编码--返厂维修********
    // 返厂维修-打开
    openBackDialog(row) {
      console.log('row',row)
      this.backRowData = row;
      this.backTableList = [];
      this.resetForm("backForm")
      if(row.backTableList){
      this.backForm = {
        //返厂厂家
        supplierId: row.backTableList[0].supplierId,
        //备注
        remark: row.backTableList[0].remark,
      };
       }
      if (
        this.backRowData.backTableList &&
        this.backRowData.backTableList.length > 0
      ) {
        this.backTableList = this.backRowData.backTableList;
      } else {
        let obj = {
          partName: "",
          partType: "0",
          partNum: 1,
          partPrice: 0,
          supplier:this.backForm.supplierId,
          remark:this.backForm.remark,
        };
        this.backTableList.push(obj);
      }
      this.openBack = true;
    },
    //返厂维修- 添加
    handleAddBack() {
      let obj = {
        partName: "",
        partType: "0",
        partNum: 1,
        partPrice: 0,
      };
      this.backTableList.push(obj);
    },
    //返厂维修- 删除
    handleDeleteBack(row) {
      this.backTableList.splice(row.index, 1);
    },
    //返厂维修- 弹窗保存
    saveBackDialog() {
      if (this.backTableList.length > 0) {
        this.$refs["backForm"].validate((valid) => {
          if (valid) {
            const isName = this.backTableList.some(
              (item) => item.partName == "" || item.partName == undefined
            );
            if (isName) {
              this.$message.error("配件名称不能为空！");
              return;
            }
            const isNum = this.backTableList.some(
              (item) => item.partNum == 0 || item.partNum == undefined
            );
            if (isNum) {
              this.$message.error("配件数量不能为0！");
              return;
            }
            // const isCost = this.backTableList.some(
            //   (item) => item.partPrice == 0 || item.partPrice == undefined
            // );
            // if (isCost) {
            //   this.$message.error("维修金额不能为0！");
            //   return;
            // }
            this.backTableList.forEach(item=>{
              item.supplierId = this.backForm.supplierId
              item.remark = this.backForm.remark
            })
            this.backRowData.backTableList = this.backTableList;
            this.backRowData.repairType = 2;
            this.backRowData.backTableList.forEach((item) => {
              this.backRowData.codeOutRepairPartList.push(item);
            });
            this.backRowData.status = 1;
            this.openBack = false;
          }
        });
      } else {
        this.$modal.msgError("请添加配件！");
      }
    },
    /** 返厂维修-物资厂家-下拉选 */
    supplierInfoList() {
      let param = {
        pageNum: 1,
        pageSize: 1000,
        keyWord: undefined,
      };
      getListFacturer(param).then((response) => {
        this.supplierList = response.rows;
      });
    },



    // ********编码--待报废********
    // 待报废-打开
    openScrapDialog(row) {
      this.scrapRowData = row;
      this.scrapForm = {};
      this.fileList = [];
      this.openScrap = true;
    },
    //编码-待报废保存按钮
    saveSubmit() {
      this.uploadKey = Date.now();
      this.$refs["scrapForm"].validate(async(valid) => {
          if(valid){
            // 添加文件必传验证
            if(this.fileList.length === 0){
              this.$message.error('请上传照片');
              return;
            }
            if(this.fileList.length!=0){
            await  this.getImaUpload(),
            await this.addWaitRepairPic(this.scrapForm);
          }else{
              await this.addWaitRepairPic(this.scrapForm);
          }
          this.scrapRowData.repairType = 3
          this.scrapRowData.codeScrapRepairPartList.push(this.scrapForm)
          this.scrapRowData.status = 1
          this.openScrap = false;
            }
      })
    },
    //编码-待报废
    async addWaitRepairPic(scrapForm){
              this.scrapForm.fileList=this.fileListTemp
              this.openScrap = false;

    },
    // 编码-待报废取消按钮
    saveCancel() {
      this.uploadKey = Date.now();
      this.openScrap = false;
      this.fileList = [];
      this.fileListTemp = [];
      this.resetForm("scrapForm");
    },
    //编码-待报废-上传文件库
    async getImaUpload(){
        this.fileListTemp = [];
        const reqData = new FormData()
        const {fileTwo} = await this.getFileData()
        let res = await imgUpLoadThree(fileTwo);
        console.log('res',res)
        if (res.code === 200) {
            res.data.forEach(item=>{
            let objTwo = { 'name': item.name, 'url': item.url,};
            this.fileListTemp.push(objTwo);
            })
        } else {
            this.$modal.msgError(res.msg);
        }
    },
    //编码-待报废-提交时循环fileList 获取raw文件
    async getFileData() {
        const fileTwo = []
        this.fileList.forEach(item => {
          if (item?.hasOwnProperty('raw')) {
            fileTwo.push(item.raw)
          }
        })
        return { fileTwo }
    },
    //编码维修弹窗文件上传前
    beforeFileUpload(row) {
      this.fileData = row;
    },
    // 编码维修弹窗文件上传成功处理-编码弹窗上传
    handleFileSuccess2(response, file, fileList) {
      if (response.code == 200) {
        let obj = {
          name: response.data.name,
          url: response.data.url,
        };
        let index = this.repairDeviceList.findIndex(
          (v) => v.maCode == this.fileData.maCode
        );
        this.repairDeviceList[index].bmFileInfos = [obj];
      }
      this.repairRowData.repairDeviceList[index].bmFileInfos =
        this.repairDeviceList[index].bmFileInfos;
    },
    //维修弹窗图片查看
// 图片查看 - 支持多张图片预览（只处理图片）
    picturePreview(row) {
      if (row.bmFileInfos && row.bmFileInfos.length > 0) {
        // 筛选出图片文件（只显示图片）
        const imageFiles = row.bmFileInfos.filter(file => {
          const parts = file.name.split(".");
          const extension = parts.pop().toLowerCase();
          return ["jpg", "jpeg", "png", "gif", "bmp", "webp"].includes(extension);
        });

        // 如果没有图片，显示提示
        if (imageFiles.length === 0) {
          this.$message.info("没有可预览的图片文件");
          return;
        }

        // 存储当前行和图片列表
        this.previewRow = row;
        this.previewImageFiles = imageFiles;
        this.previewFileIndex = 0;

        // 显示第一张图片
        this.dialogImageUrl = imageFiles[0].url;
        this.dialogVisible = true;
      } else {
        this.$message.info("没有可预览的附件");
      }
    },

// 切换到上一张图片
    prevImage() {
      if (this.previewImageFiles && this.previewImageFiles.length > 0) {
        this.previewFileIndex--;
        if (this.previewFileIndex < 0) {
          this.previewFileIndex = this.previewImageFiles.length - 1;
        }
        this.dialogImageUrl = this.previewImageFiles[this.previewFileIndex].url;
      }
    },

// 切换到下一张图片
    nextImage() {
      if (this.previewImageFiles && this.previewImageFiles.length > 0) {
        this.previewFileIndex++;
        if (this.previewFileIndex >= this.previewImageFiles.length) {
          this.previewFileIndex = 0;
        }
        this.dialogImageUrl = this.previewImageFiles[this.previewFileIndex].url;
      }
    },
    // 预览弹窗关闭时的清理
    handlePreviewClose() {
      this.previewRow = null;
      this.previewImageFiles = [];
      this.previewFileIndex = 0;
    },
    // 图片上传
    handleChange(file, fileList) {
      if (this.beforeUpload(file) == false) {
        fileList.splice(fileList.length - 1, 1);
      }
      // this.$refs["form"].clearValidate()
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG =
        file.raw.type === "image/jpeg" ||
        file.raw.type === "image/png" ||
        file.raw.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      // console.log(isJPG)
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG ,JPEG或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleRemove(file, fileList) {
      let sum = 0;
      this.fileList.forEach((item, index) => {
        if (item.uid == file.uid) {
          sum = index;
        }
      });
      this.fileList.splice(sum, 1);
    },
    // 待报废弹窗文件上传成功处理-编码弹窗上传
    handleFileSuccess3(response, file, fileList) {
      if (response.code == 200) {
        let obj = {
          name: response.data.name,
          url: response.data.url,
        };
        // this.scrapForm={}
      }
    },






    // ********数量维修********
    //数量-内部-选中配件类型
    partTypeSelect(e){
      // console.log(e)
      // console.log(this.partItems)
      let index=-1;
      let len = this.partItems.length;
      if(this.partItems.length>0){
        index = this.partItems.findIndex(v=>v.partId==e.id)
        // console.log(index)
        if(index>-1){
          this.$message.error("已存在所选配件！");
          setTimeout(()=>{
            this.partItems[len-1].partId=null;
          },500)
        }else{
          this.partItems[len-1].storageNum=e.storageNum
        }
      }else{
          this.partItems[0].storageNum=e.storageNum
      }
    },
    //配件数量
    inputPartNum(item){
      // console.log(item)
      if(item.partNum>item.storageNum){
        this.$message.error("配件数量不可大于配件领用库存！");
        item.partNum=item.storageNum
      }
    },

    partNumChange(item,value) {
      console.log("xxxxxxxxxx",item,value)
    if (value < 0) {
      this.$message.error('配件数量不能小于 0，请重新输入。');
      // 把输入值重置为 0
      this.$set(item, 'partNum', 0);
      }
    },
    partPriceChange(item,value) {
      console.log("xxxxxxxxxx",item,value)
    if (value < 0) {
      this.$message.error('配件金额不能小于 0，请重新输入。');
      // 把输入值重置为 0
      this.$set(item, 'partPrice', 0);
      }
    },
    //数量-左侧-内部维修-添加
    addPartItem() {
      this.partItems.push({ partNum: "", partType: "0", partId:null, storageNum:"" });
      this.dividerHeight += 200; // 每次增加配件时，竖线高度增加
    },
    //数量-左侧-内部维修-删除
    removePartItem(index) {
      if (this.partItems.length > 1) {
        this.partItems.splice(index, 1);
        this.dividerHeight -= 200; // 每次删除配件时，竖线高度减少
      }
    },
    //数量管理中间-返厂维修-添加
    addPartItemMiddle() {
      this.partItemsMiddle.push({ partTypeName: "", partNum: "", partType: "0" });
      this.dividerHeight += 200; // 每次增加配件时，竖线高度增加
    },
    //数量管理中间-返厂维修-删除
    removePartItemMiddle(index) {
      if (this.partItemsMiddle.length > 1) {
        this.partItemsMiddle.splice(index, 1);
        this.dividerHeight -= 200; // 每次删除配件时，竖线高度减少
      }
    },
    //表单校验
    async validateForms(refs){
      const validationResults = await Promise.all(refs.map(ref =>ref.validate()))
      return validationResults.every(result=> result===true)
    },
    //数量管理保存
    async saveNumAll() {
      if((Number(this.formLeft.repairNum) + Number(this.formMiddle.repairNum)+ Number(this.formRight.scrapNum)) >this.disrepairNumTemp) {
        this.$message({
          message: '维修总数不能大于待维修数量',
          type: 'warning'
        })
        return
      }
      if((Number(this.formLeft.repairNum) + Number(this.formMiddle.repairNum)+ Number(this.formRight.scrapNum)) ==0) {
        this.$message({
          message: '请输入维修数量 ',
          type: 'warning'
        })
        return
      }
      let refTemp = [];
      if(this.formLeft.repairNum!=0){
          refTemp.push(this.$refs.formLeft)
      }
      if(this.formMiddle.repairNum!=0){
        refTemp.push(this.$refs.formMiddle)
      }
      if(this.formRight.scrapNum!=0){
        refTemp.push(this.$refs.formRight)
        // 添加文件必传验证
        if(this.fileList.length === 0){
          this.$message.error('请上传照片');
          return;
        }
      }
      const valid = await this.validateForms(refTemp)
      if(valid){
        for (let i = 0; i < this.partItems.length; i++) {
          this.innerRowData.repairDeviceList[0].numberInRepairPartList.push({
            partType: this.partItems[i].partType,
            partId: this.partItems[i].partId,
            partNum: this.partItems[i].partNum,
            storageNum: this.partItems[i].storageNum,
            repairNum: this.formLeft.repairNum,
          });
        }
        for (let i = 0; i < this.partItemsMiddle.length; i++) {
          this.innerRowData.repairDeviceList[0].numberOutRepairPartList.push({
            partType: this.partItemsMiddle[i].partType,
            partPrice: this.partItemsMiddle[i].partPrice,
            partNum: this.partItemsMiddle[i].partNum,
            partName: this.partItemsMiddle[i].partName,
            supplierId: this.formMiddle.supplierId,
            repairNum: this.formMiddle.repairNum,
          });
        }
        this.uploadKey = Date.now();
        if(this.fileList.length!=0){
          await  this.getImaUpload(),
          this.formRight.fileList = this.fileListTemp;
        }else{
          this.formRight.fileList = this.fileListTemp;
        }
        console.log('this.formRight',this.formRight)
        this.innerRowData.repairDeviceList[0].numberScrapRepairPartList.push(this.formRight)
        this.innerRowData.repairDeviceList[0].repairType = 1;
        this.innerRowData.repairDeviceList[0].inRepairList = []
        this.innerRowData.repairDeviceList[0].outRepairList = []
        saveCodeList(this.innerRowData.repairDeviceList).then(async (response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("保存成功");
            this.fileList=[];
            this.fileListTemp=[];
            let param = {
            taskId: this.repairRow.taskId,
            keyword: "",
            };
            this.taskIdTemp = this.repairRow.taskId;
            const res =  await getAppRepairMaTypeList(param);
            this.equipmentList = res.data;
            this.equipmentList.forEach((e) => {
              e.disrepairNum = Number(e.typeRepairNum) - Number(e.typeRepairedNum)-Number(e.typeScrapNum);
            });
            this.openNum=false;
          }
        });
      }
  //   this.$refs.refTemp.validate(async(valid)=>{
  //     if(valid){
  //     for (let i = 0; i < this.partItems.length; i++) {
  //       this.innerRowData.repairDeviceList[0].numberInRepairPartList.push({
  //         partType: this.partItems[i].partType,
  //         partId: this.partItems[i].partId,
  //         partNum: this.partItems[i].partNum,
  //         repairNum: this.formLeft.repairNum,
  //       });
  //     }
  //     }
  //   })
  // }
    // if(this.formRight.scrapNum!=0){
    //   this.$refs["formLeft","formMiddle","formRight"].validate(async(valid)=>{
    //   if(valid){
    //   for (let i = 0; i < this.partItems.length; i++) {
    //     this.innerRowData.repairDeviceList[0].numberInRepairPartList.push({
    //       partType: this.partItems[i].partType,
    //       partId: this.partItems[i].partId,
    //       partNum: this.partItems[i].partNum,
    //       repairNum: this.formLeft.repairNum,
    //     });
    //   }
    //   for (let i = 0; i < this.partItemsMiddle.length; i++) {
    //     this.innerRowData.repairDeviceList[0].numberOutRepairPartList.push({
    //       partType: this.partItemsMiddle[i].partType,
    //       partPrice: this.partItemsMiddle[i].partPrice,
    //       partNum: this.partItemsMiddle[i].partNum,
    //       partName: this.partItemsMiddle[i].partName,
    //       supplierId: this.formMiddle.supplierId,
    //       repairNum: this.formMiddle.repairNum,
    //     });
    //   }
    //   this.uploadKey = Date.now();
    //   if(this.fileList.length!=0){
    //     await  this.getImaUpload(),
    //     this.formRight.fileList = this.fileListTemp;
    //   }else{
    //     this.formRight.fileList = this.fileListTemp;
    //   }
    //   console.log('this.formRight',this.formRight)
    //   this.innerRowData.repairDeviceList[0].numberScrapRepairPartList.push(this.formRight)
    //   this.innerRowData.repairDeviceList[0].repairType = 1;
    //   saveCodeList(this.innerRowData.repairDeviceList).then(async (response) => {
    //     if (response.code == 200) {
    //       this.$modal.msgSuccess("保存成功");
    //       this.fileList=[];
    //       this.fileListTemp=[];
    //       let param = {
    //       taskId: this.repairRow.taskId,
    //       keyword: "",
    //       };
    //       this.taskIdTemp = this.repairRow.taskId;
    //       const res =  await getAppRepairMaTypeList(param);
    //       this.equipmentList = res.data;
    //       this.equipmentList.forEach((e) => {
    //          e.disrepairNum = Number(e.typeRepairNum) - Number(e.typeRepairedNum)-Number(e.typeScrapNum);
    //       });
    //       this.openNum=false;
    //     }
    //   });
    //   }
    // })
    // }else{
    //   this.$refs["formLeft","formMiddle"].validate(async(valid)=>{
    //   if(valid){
    //   for (let i = 0; i < this.partItems.length; i++) {
    //     this.innerRowData.repairDeviceList[0].numberInRepairPartList.push({
    //       partType: this.partItems[i].partType,
    //       partId: this.partItems[i].partId,
    //       partNum: this.partItems[i].partNum,
    //       repairNum: this.formLeft.repairNum,
    //     });
    //   }
    //   for (let i = 0; i < this.partItemsMiddle.length; i++) {
    //     this.innerRowData.repairDeviceList[0].numberOutRepairPartList.push({
    //       partType: this.partItemsMiddle[i].partType,
    //       partPrice: this.partItemsMiddle[i].partPrice,
    //       partNum: this.partItemsMiddle[i].partNum,
    //       partName: this.partItemsMiddle[i].partName,
    //       supplierId: this.formMiddle.supplierId,
    //       repairNum: this.formMiddle.repairNum,
    //     });
    //   }
    //   this.uploadKey = Date.now();
    //   if(this.fileList.length!=0){
    //     await  this.getImaUpload(),
    //     this.formRight.fileList = this.fileListTemp;
    //   }else{
    //     this.formRight.fileList = this.fileListTemp;
    //   }
    //   console.log('this.formRight',this.formRight)
    //   this.innerRowData.repairDeviceList[0].numberScrapRepairPartList.push(this.formRight)
    //   this.innerRowData.repairDeviceList[0].repairType = 1;
    //   saveCodeList(this.innerRowData.repairDeviceList).then(async (response) => {
    //     if (response.code == 200) {
    //       this.$modal.msgSuccess("保存成功");
    //       this.openNum=false;
    //     }
    //   });
    //       this.fileList=[];
    //       this.fileListTemp=[];
    //       let param = {
    //       taskId: this.repairRow.taskId,
    //       keyword: "",
    //       };
    //       this.taskIdTemp = this.repairRow.taskId;
    //       const res =  await getAppRepairMaTypeList(param);
    //       this.equipmentList = res.data;
    //       this.equipmentList.forEach((e) => {
    //         e.disrepairNum = Number(e.typeRepairNum) - Number(e.typeRepairedNum)-Number(e.typeScrapNum);
    //       });

    //   }
    // })
    // }

    },
    //数量维修取消
    saveCancelAll(){
      this.fileList=[];
      this.fileListTemp=[];
      this.resetForm("formLeft");
      this.resetForm("formMiddle")
      this.resetForm("formRight")
      this.partItems =  [{ partNum: "", partType: "0", partId:null, storageNum:"" }],
      this.partItemsMiddle = [{ partName: "", partNum: "", partPrice: "0", partType: "0" }],
      this.openNum=false;
    },
    //待维修数量限制统计
    waitRepairCount(){
      if((Number(this.formLeft.repairNum) + Number(this.formMiddle.repairNum)+ Number(this.formRight.scrapNum)) >this.disrepairNumTemp){
        this.flagSave = true;
        this.$message.error("输入的数字之和大于"+this.disrepairNumTemp);
      }else if((Number(this.formLeft.repairNum) + Number(this.formMiddle.repairNum)+ Number(this.formRight.scrapNum))==0){
        this.flagSave = true;
        this.$message.error("输入的数字之和不能为0");
      }else{
         this.flagSave = false;
      }
      if(Number(this.formMiddle.repairNum)==0){
        this.resetForm("formMiddle")
      }
      if(Number(this.formRight.scrapNum)==0){
        this.resetForm("formRight")
      }
    },
  },
};
</script>
<style lang="scss" scoped>
  ::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
  }
  //隐藏图片上传框的css
  ::v-deep.disabled {
    .el-upload--picture-card {
      display: none;
    }
  }
  .part-select {
    .el-cascader-panel .el-scrollbar .el-checkbox {
      display: none;
    }

    .el-cascader-panel .el-scrollbar:nth-child(3) .el-checkbox {
      display: block !important;
    }
  }
  .dialog-content {
    height: 600px;
    overflow-y: auto;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }

  .left,
  .middle,
  .right {
    flex: 1;
    padding: 10px 0;
  }

  .divider {
    width: 2px;
    background-color: #dcdfe6;
    height: 100%;
    margin: 0 10px;
    flex-shrink: 0; /* 防止竖线在内容较少时缩小 */
  }
</style>
