<template>
  <div class="app-container">
    <el-splitter>
      <el-splitter-panel size="40%" style="margin-right:24px">
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="90">
          <el-row>
            <el-col :span="12">
              <el-form-item label="入库时间" prop="operationTime">
                <el-date-picker v-model="operationTime" type="datetimerange" start-placeholder="开始时间"
                  end-placeholder="结束时间" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单据号" prop="billNo">
                <el-input v-model="queryParams.billNo" placeholder="请输入单据号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="入库类型" prop="operationType">
                <el-select v-model="queryParams.operationType" placeholder="请选择入库类型" clearable
                  @keyup.enter="handleQuery">
                  <el-option v-for="dict in storeTypeList" :key="dict.id" :label="dict.typeName"
                    :value="dict.typeCode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存状态" prop="execStatus">
                <el-select v-model="queryParams.execStatus" placeholder="请选择库存状态" clearable @keyup.enter="handleQuery">
                  <el-option v-for="dict in execStatusMenu" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row class="mb8">
          <el-col :span="14">
            <el-button type="primary" plain @click="handleAdd(false)" v-hasPermi="['wisdom:bill:add']">新增入库</el-button>
            <el-button type="warning" plain @click="handleExport" v-hasPermi="['wisdom:bill:export']">导出</el-button>
            <!-- <el-button type="primary" plain @click="rkUpload">图片上传</el-button> -->
          </el-col>

          <el-col :span="9" class="searchBtn">
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table v-loading="loading" ref="billTableRef" :data="billList" highlight-current-row
          @row-click="(row) => tableInfoRowClick(row, billTableRef)" :row-class-name="tableBillRowClassName"
          @row-dblclick="billClick" @selection-change="billSelectionChange">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column label="单据号" align="center" prop="billNo" width="180" />
          <el-table-column label="库存状态" align="center">
            <template #default="scope">
              <span>{{ getExecStatusName(scope.row.execStatus) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作类型" align="center">
            <template #default="scope">
              <dict-tag :options="dictTagData()" :value="scope.row.bizType" />
            </template>
          </el-table-column>

          <el-table-column label="入库类型" align="center" prop="operationTypeName" width="120" />
          <el-table-column label="物资类型" align="center" prop="wlTypeName" width="100" />
          <el-table-column label="入库时间" align="center" prop="operationTime" width="170">
            <template #default="scope">
              <span>{{
                parseTime(scope.row.operationTime, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="理货员" align="center" prop="operatorName" width="100" />
          <el-table-column label="操作" align="center" fixed="right" width="260">
            <template #default="scope">
              <el-button link type="primary" @click="picDetailFun(scope.row.billNo, 0, 1)">入库图片</el-button>
              <el-button link type="primary" @click="billClick(scope.row, 'bill', 'rk')">入库单</el-button>
              <el-button link type="primary" @click="editData(scope.row)">修改</el-button>
              <el-button link type="primary" @click="delData(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
        <!-- <el-pagination background layout="prev, pager, next" :total="total" v-model:page="queryParams.pageNum" @pagination="getList"/> -->
      </el-splitter-panel>
      <el-splitter-panel :min="200">
        <el-row :gutter="10" class="mb8" v-show="stockList.length > 0">
          <el-col :span="1.5">
            <el-button type="success" plain icon="Printer" @click="handlePrint" v-print="printViewInfo"
              v-hasPermi="['wisdom:bill:print']">打印单据</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Printer" @click="handlePrintTag">打印标签</el-button>
          </el-col>
          <el-col :span="4">
            <el-form-item label="打印机编号" prop="printNum">
              <el-select v-model="printNum" clearable>
                <el-option v-for="dict in printNumList" :key="dict.id" :label="dict.statusName" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Switch"
                @click="handleMove"
                v-hasPermi="['wisdom:bill:move']"
              >移库</el-button>
            </el-col> -->
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="addOne()">添加单条物料</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleDispatch">生成调度任务</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleOneClickWarehousing">一键入库</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleOneClickStockDelete">一键撤销</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Delete" @click="handleOneClickStockDel">一键删除</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="detailLoading" ref="infoTableRef" highlight-current-row
          @row-click="(row) => tableInfoRowClick(row, infoTableRef)" show-overflow-tooltip border :data="stockList"
          @selection-change="printSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" width="70" />
          <el-table-column label="库存状态" align="center">
            <template #default="scope">
              <span>{{ getExecStatusName(scope.row.execStatus) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="sapNo" width="150" />
          <el-table-column label="项目号" align="center" prop="xmNo" width="150" />
          <el-table-column label="项目描述" align="center" prop="xmMs" width="250" />
          <el-table-column label="物料号" align="center" prop="wlNo" width="100" />
          <el-table-column label="物料描述" align="center" prop="wlMs" width="250" />
          <el-table-column label="供应商名称" align="center" prop="gysMc" width="200" />
          <el-table-column label="合同单价" align="center" prop="htDj" />
          <el-table-column label="总计" align="center" prop="totalAmount" />
          <el-table-column label="计量单位" align="center" prop="dw" />
          <el-table-column label="实际入库数量" align="center" prop="realQty" width="120" />
          <el-table-column label="库位码" align="center" prop="pcode" width="120" />
          <el-table-column label="备注" align="center" prop="remark" width="200" />
          <el-table-column label="是否移库" align="center" prop="isMove">
            <template #default="scope">
              <span>{{ isMoveFun(scope.row.hasMoved) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="托盘码" align="center" prop="trayCode" />
          <el-table-column label="所属大仓" align="center" prop="parentWarehouseName" width="150" />
          <el-table-column label="所属小仓" align="center" prop="warehouseName" width="150" />
          <!-- <el-table-column label="库龄" align="center" prop="stockAge" /> -->
          <el-table-column label="现场图片" align="center" v-if="isExamine == 1">
            <template #default="scope">
              <el-image :src="scope.row.scenePhotoUrl" style="width: 50px; height: 50px" :zoom-rate="1.2" :max-scale="7"
                :min-scale="0.2" :preview-src-list="srcList" show-progress :initial-index="4" :preview-teleported="true"
                @click="preview(scope.row.scenePhotoUrl)" />
            </template>
          </el-table-column>

          <el-table-column label="一次封样号" align="center" prop="fycde1" width="150" />
          <el-table-column label="二次封样号" align="center" prop="fycde2" width="150" />
          <el-table-column label="身份码" align="center" prop="entityId" width="200" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['wisdom:bill:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" v-show="scope.row.execStatus == 1"
                @click="handleStockDelete(scope.row)" v-hasPermi="['wisdom:bill:delete']">撤销</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-splitter-panel>
    </el-splitter>

    <!-- 打印 -->
    <div id="printMe" class="printMeBox" v-if="showContent">
      <printBill :billAllObj="stockList" />
    </div>
    <!-- 修改主单据，入库时间等字段 -->
    <el-dialog title="修改" v-model="openBill" @close="closeDialog" append-to-body width="40%">
      <el-form :model="billData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库类型" prop="operationType">
              <el-select v-model="billData.operationType" placeholder="请选择入库类型" clearable>
                <el-option v-for="dict in storeTypeList" :key="dict.id" :label="dict.typeName" :value="dict.typeCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物资类型" prop="wlType">
              <el-select v-model="billData.wlType" placeholder="请选择物资类型" clearable>
                <el-option v-for="dict in wzTypeList" :key="dict.id" :label="dict.typeName" :value="dict.typeCode" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="理货员" prop="operator">
              <el-select v-model="billData.operator" placeholder="请选择理货员" clearable>
                <el-option v-for="dict in personList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库时间" prop="operationTime">
              <el-date-picker style="width: 100%" v-model="billData.operationTime" value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss" type="datetime" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存状态" prop="execStatus">
              <el-select v-model="billData.execStatus" placeholder="请选择库存状态" clearable>
                <el-option v-for="dict in execStatusMenu" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="editForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改库存单据主对话框 -->
    <el-dialog :title="title" v-model="open" @close="closeDialog" width="75%" :draggable="true" :z-index="4"
      :close-on-click-modal="false">
      <el-form ref="stockRef" :model="storeData" :rules="rules">
        <el-row :gutter="20" v-if="idEdit == 0">
          <el-col :span="12">
            <el-form-item label="采购订单号">
              <el-input v-model="orderNum" placeholder="请输入订单号" :disabled="idEdit != 0" @keydown.enter="searchPlan" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="searchPlan" :disabled="idEdit != 0">从供应计划中添加</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" v-if="idEdit == 0">
            <el-form-item label="入库类型" prop="operationType">
              <el-select v-model="storeData.operationType" placeholder="请选择入库类型" clearable>
                <el-option v-for="dict in storeTypeList" :key="dict.id" :label="dict.typeName" :value="dict.typeCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="idEdit == 0">
            <el-form-item label="物资类型" prop="wlType">
              <el-select v-model="storeData.wlType" placeholder="请选择物资类型" clearable>
                <el-option v-for="dict in wzTypeList" :key="dict.id" :label="dict.typeName" :value="dict.typeCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属仓库" prop="warehouseCode">
              <el-cascader :options="warehouseList" @change="pcodeList" v-model="storeData.warehouseCode" :props="{
                children: 'children',
                label: 'warehouseName',
                value: 'warehouseCode',
              }" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="idEdit == 0">
            <el-form-item label="理货员" prop="operator">
              <el-select v-model="storeData.operator" placeholder="请选择理货员" clearable>
                <el-option v-for="dict in personList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="idEdit == 0">
          <el-col :span="6">
            <el-form-item label="入库时间" prop="operationTime">
              <!-- type="date" -->
              <el-date-picker v-model="storeData.operationTime" value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择入库时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库存状态" prop="execStatus">
              <el-select v-model="storeData.execStatus" placeholder="请选择" clearable>
                <el-option v-for="dict in execStatusMenu" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="扩展描述">
              <el-input v-model="kzms" placeholder="请输入扩展描述" :disabled="idEdit != 0" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-checkbox v-model="autoFill" label="自动填充" size="large" @change="autoFillFun" :disabled="idEdit != 0" />
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="addLineFun" :disabled="idEdit != 0">添加</el-button>
          </el-col>
        </el-row>
        <div class="addBox">
          <div style="display: flex;align-items: center;">
            <div class="addData" @click="addData">
              <el-icon style="margin-right: 10px;" size="20">
                <FolderAdd />
              </el-icon>
              添加至入库
            </div>
            <div @click="viewData" style="color: #000;text-decoration: underline;margin-left: 5px;">[已添加{{
              outTempData.length }}条库存]</div>
            <!-- <div @click="viewData" style="color: red;text-decoration: underline;font-weight: bold;">[凭证重复入库或项目已关闭，请点击查看！]</div> -->
          </div>
          <div v-show="outTempData.length > 0 && planList.length === outTempData.length" @click="deleteData"
            style="display: flex;align-items: center;color: var(--el-color-primary);">
            <el-icon>
              <delete />
            </el-icon>
            <span>删除</span>
          </div>
        </div>
        <el-table :data="planList" height="400" style="width: 100%" show-overflow-tooltip border
          :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column label="序号" align="center" type="index" width="70" />
          <el-table-column label="状态" align="center" prop="status" width="100" v-if="idEdit == 0">
            <template #default="scoped">
              <el-tag :type="scoped.row.status == 1
                ? 'success'
                : scoped.row.status == 0
                  ? 'danger'
                  : 'warning'
                ">{{
                  statusList.filter(
                    (item) => item.value == scoped.row.status
                  )[0].label
                }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column width="40" align="center">
            <template #default="scope">
              <el-icon :size="22" @click="delLineFun(scope.$index)">
                <RemoveFilled />
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column label="物料号" align="center" prop="wlNo" width="150">
            <template #default="scope">
              <el-input v-if="scope.row.isnew" v-model="scope.row.wlNo" placeholder="请输入物料号"
                @change="searchInfo(scope.row.wlNo, scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="物料描述" align="center" prop="wlMs" width="200">
            <template #default="scope">
              <el-input v-if="scope.row.isnew" v-model="scope.row.wlMs" placeholder="请输入物料描述"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="htDj" width="80">
            <template #default="scope">
              <el-input v-if="scope.row.isnew" v-model="scope.row.htDj"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" prop="dw" width="80">
            <template #default="scope">
              <el-input v-if="scope.row.isnew" v-model="scope.row.dw"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="入库数量" align="center" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.realQty" placeholder="入库数量">
                <template #append>
                  <el-button :icon="Plus" @click="addNum(scope.row)" />
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="库位" align="center" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.pcode" clearable @change="changePcode" filterable placeholder="请选择库位">
                <el-option v-for="item in kwOptions" :key="item.pcode" :label="item.pcode" :value="item.pcode" />
              </el-select>
            </template>
          </el-table-column>


          <el-table-column label="备注" align="center" width="200">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="采购订单号" align="center" prop="sapNo" width="130">
            <template #default="scope">
              <el-input v-if="scope.row.isnew" v-model="scope.row.sapNo" placeholder="请输入订单号"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="项目定义号" align="center" prop="xmNo" width="150">
            <template #default="scope">
              <el-input v-if="scope.row.isnew" v-model="scope.row.xmNo" placeholder="项目定义号"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="项目名称" align="center" prop="xmMs" width="300">
            <template #default="scope">
              <el-input v-if="scope.row.isnew" v-model="scope.row.xmMs" placeholder="项目名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="供应商" align="center" prop="gysMc" width="200">
            <template #default="scope">
              <el-input v-if="scope.row.isnew" v-model="scope.row.gysMc" placeholder="供应商"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="容器码" align="center" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.trayCode" placeholder="请输入容器码"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="身份码" align="center" width="200">
            <template #default="scope">
              <el-input v-model="scope.row.entityId" placeholder="请输入身份码"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="一次封样号" align="center" width="200">
            <template #default="scope">
              <el-input v-model="scope.row.fycde1" placeholder="请输入一次封样号"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="二次封样号" align="center" width="200">
            <template #default="scope">
              <el-input v-model="scope.row.fycde2" placeholder="请输入二次封样号"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="上传" align="center" width="150" v-if="isExamine == 1">
            <template #default="scope">
              <el-upload class="upload-demo" :action="actionUrl" :multiple="false" :headers="headers"
                :on-preview="handlePreview" :on-remove="function (response) {
                  return handleRemove(
                    response,
                    scope.row.id,
                    scope.row.pcode
                  );
                }
                  " :on-success="function (response) {
                    return handleAvatarSuccess(
                      response,
                      scope.row.id,
                      scope.row.pcode
                    );
                  }
                    ">
                <el-button type="primary" size="small" v-show="!scope.row.photoUrl && scope.row.pcode">选择图片</el-button>
              </el-upload>
            </template>
          </el-table-column>
        </el-table>
        <!-- 审批模块 暂时注释-->
        <div class="examine" v-show="isExamine == 1">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="审批人">
                <el-select v-model="storeData.approverId" clearable filterable placeholder="请选择审批人">
                  <el-option v-for="dict in personList" :key="dict.userId" :label="dict.userName"
                    :value="dict.userId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 移库 -->
    <el-dialog title="移库" v-model="openMove" append-to-body width="60%">
      <el-form :model="checkStockList" :rules="rules">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="物料号">
              <el-input v-model="checkStockList[0].wlNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目号">
              <el-input v-model="checkStockList[0].xmNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单号">
              <el-input v-model="checkStockList[0].sapNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目描述">
              <el-input v-model="checkStockList[0].xmMs" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="移库原因">
              <el-input v-model="moveReason" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-table :data="checkStockList" height="400" style="width: 100%">
          <el-table-column label="数量" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.realQty" placeholder="数量">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="存放位置" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.toPcode" clearable filterable placeholder="请选择库位">
                <el-option v-for="item in kwOptions" :key="item.id" :label="item.pcode" :value="item.pcode" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="容器码" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.toTrayCode" placeholder="请输入容器码"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center">
            <template #default="scope">
              <el-cascader :options="warehouseList" v-model="scope.row.toCangku" @change="pcodeList" :props="{
                children: 'children',
                label: 'warehouseName',
                value: 'warehouseCode',
              }" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMoveForm">确 定</el-button>
          <el-button @click="cancelMove">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 图片预览 -->
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <!-- 上传图片 -->
    <el-dialog title="图片上传" v-model="dialogPicVisible">
      <el-upload v-model:file-list="fileList" :multiple="true" list-type="picture-card" :on-change="handleChange"
        :auto-upload="false" :on-preview="handlePictureCardPreview" :on-remove="handleScRemove">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">上 传</el-button>
          <el-button @click="dialogPicVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="图片详情" v-model="dialogPicDetailVisible">
      <!-- <div v-for="url in picList" :key="url" > -->
      <!-- <span class="demonstration">{{ fit }}</span> -->
      <div class="picBox">
        <div v-for="obj in picList" :key="obj.id" class="everyPicBox">
          <el-icon class="closeBox" :size="23" @click="delPic(obj.id)">
            <CircleCloseFilled />
          </el-icon>
          <el-image style="width: 100px; height: 100px; margin-right: 20px" :src="obj.url"
            :preview-src-list="urlList" />
        </div>
      </div>

      <!-- </div> -->
    </el-dialog>

    <el-dialog title="入库单" v-model="dialogBill" append-to-body width="80%" :close-on-click-modal="false">
      <bill :billAllObj="billAllObj" billStatus="rk" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogBill = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="调度任务" v-model="dispatchOpen" width="30%" :close-on-click-modal="false">
      <el-form>
        <el-row>
          <el-col>
            <el-form-item label="调度模式">
              <el-radio-group v-model="resource">
                <el-radio value="1">仅立库</el-radio>
                <el-radio value="2">立库+AGV</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDispatch">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bill">
// wisdomDelStock
import {
  listBill,
  addBill,
  updateBill,
  delBill,
  listStock,
  appendBill,
  moveRecord,
  updateRecord,
  backoutRecord,
  recordFinish,
  recordRemove
} from "@/api/wisdom/bill";
import {
  uploadContract,
  getStock,
  delStock,
  addStock,
  updateStock,
  getPlan,
  moveHouse,
  getAudit,
  wisdomDelStock,
  ckDelStock,
  wlSearch,
  picDetail,
  printTag,
  delPicF,
  editBill,
  addOneStock,
  getEditInfo,
} from "@/api/wisdom/stock";
import { generateDispatch } from "@/api/wisdom/outbound";
import { getToken } from "@/utils/auth";
import { warehousingDict } from "@/api/information/warehousingtype"; //入库类型
import { materialtypeDict } from "@/api/information/materialtype"; //物资类型
import { warehouseAll } from "@/api/information/warehouseinfo"; //所属仓库
import { personListDict } from "@/api/system/user"; //理货员
import { getKwAllList } from "@/api/information/pcdedetail"; //库位下拉数据
import { Plus } from "@element-plus/icons-vue";
import bill from "@/components/storageBill/bill.vue";
import printBill from "@/components/printBill/bill.vue";
import { ref } from "vue";
import { parseTime } from '@/utils/manage';
const headers = ref({
  Authorization: "Bearer " + getToken(),
});
const { proxy } = getCurrentInstance();

const open = ref(false);

const showSearch = ref(true);
const idEdit = ref(0);
const title = ref("");
const planLoading = ref(true);
const planList = ref([]); //从供应计划中添加列表

const orderNum = ref(""); //搜索条件：订单号
const kwOptions = ref([]); //库位下拉
const showContent = ref(false); // 控制打印内容是否显示
const dateStr = ref(""); //打印单据生成的日期
const storeStatusList = ref([
  { id: 0, statusName: "已入库" },
  { id: 1, statusName: "已出库" },
]);
const printNumList = ref([
  { id: 1, statusName: "1" },
  { id: 2, statusName: "2" },
  { id: 3, statusName: "3" },
  { id: 4, statusName: "4" },
]);
const printNum = ref(1); //打印机编号
const moveReason = ref(""); //移库原因
const operationTime = ref([]);
const actionUrl =
  import.meta.env.VITE_APP_BASE_API + "/wisdom/signature/upload";
// const actionUrla = import.meta.env.VITE_APP_BASE_API+"/photo/upload/batch"
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const srcList = ref([]);
const autoFill = ref(false); //是否自动填充备注
const kzms = ref("");

const billObj = ref({
  billNo: "",
  type: null,
});
const uploadParams = ref({
  photoType: null,
  billNo: "",
  typeName: "",
  gysMc: "",
  xmMs: "",
});
const picList = ref([]);
const urlList = ref([]);
// const fileList = ref([])
const dialogPicVisible = ref(false);
const dialogPicDetailVisible = ref(false);
const isSingle = ref(false);
const resource = ref(""); //调度模式 1仅立库；2立库+AGV
const dispatchOpen = ref(false); //调度任务弹窗

const data = reactive({
  fileList: [],
  form: {},
  storeData: {
    operationTime: "",
  }, //入库数据

  queryParams: {
    keyword: "",
    pageNum: 1,
    pageSize: 10,
    startDate: null,
    endDate: null,
    operationType: "",
    wlType: "", //物资类型
  },
  detailQueryParams: {
    pageNum: 1,
    pageSize: 1000,
    billNo: null,
    billNoCk: null,
  },
  rules: {
    operationType: [
      { required: true, message: "入库类型不能为空", trigger: "change" },
    ],
    wlType: [
      { required: true, message: "物资类型不能为空", trigger: "change" },
    ],
    warehouseCode: [
      {
        required: true,
        type: "array",
        message: "所属仓库不能为空",
        trigger: "change",
      },
    ],
    operator: [
      { required: true, message: "理货员不能为空", trigger: "change" },
    ],
    execStatus: [
      { required: true, message: "是否预入库不能为空", trigger: "change" },
    ],
    operationTime: [
      { required: true, message: "入库时间不能为空", trigger: "change" },
    ],
  },
  switchRules: {
    toCangku: [
      { required: true, message: "目标仓库不能为空", trigger: "change" },
    ],
    toPcode: [
      { required: true, message: "目标存放位置不能为空", trigger: "change" },
    ],
  },
  printViewInfo: {
    id: "printMe", //打印区域的唯一的id属性
    popTitle: "入库信息打印", // 页眉文字 （不设置时显示undifined）（页眉页脚可以在打印页面的更多设置的选项中取消勾选）
    beforeOpenCallback() {
      showContent.value = false;
    }, // 开始打印之前的callback
    openCallback() { }, // 调用打印时的callback
    closeCallback() { }, // 关闭打印的callback(无法区分确认or取消)
    clickMounted() { },

    standard: "",
    extarCss: "",
  },
});

const {
  fileList,
  queryParams,
  detailQueryParams,
  storeData,
  rules,
  form,
  printViewInfo,
  switchRules,
} = toRefs(data);

const warehouseList = ref([]); //所属仓库下拉数据

// 新增库存状态
const execStatusMenu = ref([
  { value: "0", label: "预入库" },
  { value: "1", label: "已入库" },
]);

const getExecStatusName = (value) => {
  return execStatusMenu.value.find((item) => item.value === value)?.label;
};

//所属仓库
function warehouseFun() {
  //所属仓库下拉数据
  warehouseAll().then((response) => {
    warehouseList.value = response.data;
  });
}
//所属仓库
warehouseFun();

//库位字典
function pcodeList(value) {
  getKwAllList(value[1]).then((response) => {
    kwOptions.value = response.data;
  });
}

const wzTypeList = ref([]); //物资类型下拉数据
//物资类型
function materialFun() {
  //获取物资类型下拉数据
  materialtypeDict().then((response) => {
    wzTypeList.value = response.data;
  });
}
//物资类型
materialFun();

const storeTypeList = ref([]); //入库类型下拉数据
function rklxList() {
  //获取入库类型下拉数据
  warehousingDict().then((response) => {
    storeTypeList.value = response.data;
  });
}
//入库类型下拉数据
rklxList();

const personList = ref([]); //理货员下拉数据
function lhyList() {
  //理货员下拉数据
  personListDict().then((response) => {
    personList.value = response.data;
  });
}
//理货员下拉数据
lhyList();

const loading = ref(true);
const billList = ref([{ execStatus: 0 }]); //单据列表
const total = ref(0); //单据
/** 查询库存单据主列表 */
function getList() {
  loading.value = true;
  queryParams.value.bizTypeList = [0];
  listBill(queryParams.value).then((response) => {
    billList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
//数据列表
getList();

/** 新增按钮操作 */
function handleAdd(single) {
  isSingle.value = single;
  reset();
  open.value = true;
  outTempData.value = []
  title.value = "添加库存单据";
}

// 新增入库弹窗--删除某一条数据
function delLineFun(index) {
  proxy.$modal
    .confirm("确定删除吗？")
    .then(function () {
      return planList.value.splice(index, 1);
    })
    .then(() => { })
    .catch(() => { });
}
// 新增入库的列表状态
const statusList = ref([
  { value: 0, label: "未到货" },
  { value: 1, label: "已入库" },
  { value: 2, label: "部分入库" },
]);
const checkPlanList = ref([]); //已选中的要入库的数据

// 点击添加至入库
const outTempData = ref([]);
function addData() {
  if (checkPlanList.value.length == 0) {
    proxy.$modal.msgError("请勾选数据");
    return;
  }
  let data = outTempData.value.concat(checkPlanList.value);
  // let arr = []; // 去重后的最终数组
  // let duplicateSapNos = ''; // 存储重复数据的sapNo
  // let invalidQtySapNos = ''; // 存储入库数量有误的sapNo
  // const uniqueKeys = new Set(); // 用于存储唯一的组合键 (id+pcode+realQty)

  // // 遍历数组，先校验数量合法性，再判断唯一性
  // data.forEach(item => {
  //   // 1. 校验realQty是否大于0（处理空值/非数字情况）
  //   const realQty = Number(item.realQty);
  //   if (isNaN(realQty) || realQty <= 0) {
  //     // 避免同一个sapNo重复添加到提示中
  //     if (!invalidQtySapNos.includes(item.sapNo)) {
  //       invalidQtySapNos += item.sapNo + ',';
  //     }
  //     return; // 数量不合法，直接跳过后续唯一性判断
  //   }

  //   // 2. 生成唯一标识组合键
  //   const uniqueKey = `${item.id}_${item.pcode}_${realQty}`;

  //   // 3. 检查组合键是否已存在
  //   if (uniqueKeys.has(uniqueKey)) {
  //     // 存在重复，拼接sapNo（去重避免重复拼接）
  //     if (!duplicateSapNos.includes(item.sapNo)) {
  //       duplicateSapNos += item.sapNo + ',';
  //     }
  //   } else {
  //     // 不存在重复，加入结果数组并记录组合键
  //     arr.push(item);
  //     uniqueKeys.add(uniqueKey);
  //   }
  //   console.log(uniqueKeys)
  // });

  // // 处理入库数量有误的提示
  // if (invalidQtySapNos) {
  //   invalidQtySapNos = invalidQtySapNos.slice(0, -1); // 去掉最后一个逗号
  //   proxy.$modal.msgError(`入库数量有误：${invalidQtySapNos}（入库数量需大于0）`);
  //   return
  // }

  // // 处理重复数据的提示
  // if (duplicateSapNos) {
  //   duplicateSapNos = duplicateSapNos.slice(0, -1); // 去掉最后一个逗号
  //   proxy.$modal.msgError(`存在重复数据：${duplicateSapNos}`);
  // }

  outTempData.value = data
}

const generateSimpleUniqueStr = () => {
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
    return crypto.randomUUID();
  }

  // 兼容旧版浏览器/Node.js（crypto API 降级）
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
  );
}

// 查看所有的出库数据
const viewData = () => {
  let arr = JSON.parse(JSON.stringify(outTempData.value));
  planList.value = arr.map(item => ({
    ...item,
    uniqueId: generateSimpleUniqueStr() // 新增随机唯一值
  }));
}

// 删除选中的出库数据
const deleteData = () => {
  if (checkPlanList.value.length == 0) {
    proxy.$modal.msgError("请勾选数据");
    return;
  }
  proxy.$modal.confirm("确认删除选中的出库数据吗？").then(() => {
    const uniqueIds = checkPlanList.value.map(item => item.uniqueId);
    console.log(uniqueIds)
    planList.value = planList.value.filter(item => {
      // 无id的元素默认保留（如果想删除无id的，可改为 item?.id && !arr2Ids.has(item.id)）
      return !uniqueIds.includes(item?.uniqueId);
    });
    outTempData.value = planList.value
  });
}


//新增入库 多选框选中数据
function handleSelectionChange(selection, $event) {
  checkPlanList.value = selection;
}

//从供应计划中添加 搜索
function searchPlan() {
  if (!orderNum.value) {
    proxy.$modal.msgWarning("采购订单号不能为空");
    return;
  }
  //查供应计划
  getPlan(orderNum.value).then((response) => {
    let planData = response.data;
    if (planData.length > 0) {
      for (let i = 0; i < planData.length; i++) {
        planData[i].realQty = planData[i].waitQty;
        planData[i].gysJhId = planData[i].id;
        planData[i].pcode = "";
        if (autoFill.value && kzms.value != "") {
          planData[i].remark = kzms.value;
        }
        planData[i].isnew = false;
      }
      if (planData.some((item) => item.status == "1")) {
        proxy.$modal.msgWarning(response.msg);
      }
    } else {
      proxy.$modal.msgWarning("暂无数据");
      return;
    }
    planList.value = planList.value.concat(planData);
  });
}

//供应计划中没有，手动添加的数据
function addLineFun() {
  let remarkFill = "";
  if (autoFill.value && kzms.value) {
    remarkFill = kzms.value;
  }
  const info = {
    dw: "",
    entityId: "", //身份码
    gysMc: "",
    gysNo: "",
    wlNo: "",
    wlMs: "",
    htDj: "", //单价
    pcode: "",
    trayCode: "",
    realQty: "",
    sapNo: "",
    xmNo: "",
    xmMs: "",
    gysMc: "",
    remark: remarkFill,
    status: 0,
    fycde1: "",
    fycde2: "",
    gysJhId: null,
    isnew: true,
  };
  planList.value.push(info);
}

// 选择库位修改库位数组
const changePcode = (e) => {
  if (e) {
    let index = kwOptions.value.findIndex((item) => item.pcode == e);
    kwOptions.value.splice(index, 1);
    kwOptions.value.unshift({ pcode: e });
  }
}

//添加数量
function addNum(row) {
  let addRow = {};
  Object.assign(addRow, row);
  addRow.pcode = "";
  addRow.realQty = "";
  addRow.entityId = "";
  addRow.trayCode = "";
  addRow.remark = autoFill.value && kzms.value != "" ? kzms.value : "";
  addRow.photoUrl = "";
  addRow.fycde1 = "";
  addRow.fycde2 = "";
  addRow.isAdd = true;
  planList.value.push(addRow);
}

/** 确定入库按钮 */
function submitForm() {
  if (outTempData.value.length !== planList.value.length) {
    proxy.$modal.msgError("请查看勾选数据");
    return;
  }
  proxy.$refs["stockRef"].validate((valid) => {
    if (valid) {
      if (checkPlanList.value.length == 0) {
        proxy.$modal.msgError("请勾选数据");
        return;
      }
      if (checkPlanList.value.filter((x) => !x.realQty).length > 0) {
        proxy.$modal.msgError("入库数量不能为空");
        return;
      }
      if (
        isExamine.value == 1 &&
        checkPlanList.value.filter((x) => !x.photoUrl).length > 0
      ) {
        proxy.$modal.msgError("现场图片不能为空");
        return;
      }
      // let iscfwz = false; //库位是否为空
      // let bigData = checkPlanList.value;
      // for (let i = 0; i < bigData.length; i++) {
      //   //库位
      //   if (!bigData[i].pcode) {
      //     iscfwz = true;
      //   }
      // }
      //发现场入库类型可以不用选库位
      // if (storeData.value.operationType != "RK025" && iscfwz) {
      //   proxy.$modal.msgError("请选择库位");
      //   return;
      // }
      // if(isExamine.value==1 && !storeData.value.approverId){
      //   proxy.$modal.msgError("审批人不能为空");
      //   return
      // }
      checkPlanList.value.forEach((item) => {
        item.bizType = 0;
      });
      if (idEdit.value != 0) {
        //修改
        let obj = JSON.parse(JSON.stringify(checkPlanList.value[0]));
        obj.cangku = storeData.value.warehouseCode[
          storeData.value.warehouseCode.length - 1
        ];
        let arr = JSON.parse(JSON.stringify(obj));
        updateRecord(arr).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          detailList();
        });
      } else {
        //新增
        console.log(storeData.value);
        let submitData = {
          rkBill: {
            cangku:
              storeData.value.warehouseCode[
              storeData.value.warehouseCode.length - 1
              ], //所属仓库
            operator: storeData.value.operator, //理货员
            operationType: storeData.value.operationType, //入库类型
            wlType: storeData.value.wlType, //物资类型
            approverId: storeData.value.approverId, //审批人
            operationTime: storeData.value.operationTime, //入库时间
            execStatus: storeData.value.execStatus, //是否预入库
            id: idEdit.value,
            bizType: 0,
            billNo:
              storeData.value.billNo && isSingle.value
                ? storeData.value.billNo
                : null,
          },
          rkInfoList: checkPlanList.value,
        };
        console.log(submitData);
        if (isSingle.value) {
          //单条添加
          appendBill(submitData).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            detailList();
          });
        } else {
          //多条添加
          addBill(submitData).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    }
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  if (operationTime.value && operationTime.value.length > 0) {
    queryParams.value.startDate = operationTime.value[0];
    queryParams.value.endDate = operationTime.value[1];
  } else {
    queryParams.value.startDate = "";
    queryParams.value.endDate = "";
  }
  queryParams.value.pageNum = 1;
  stockList.value = [];
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  operationTime.value = [];
  handleQuery();
}

// 显示预出库的状态
const tableBillRowClassName = ({ row, rowIndex }) => {
  if (row.execStatus == 0) {
    return "success-row";
  }
  return "";
};

// 左侧显示库存状态
const bizTypeList = ref([
  { value: 0, label: "已入库", elTagType: "success", elTagClass: null },
  { value: 1, label: "已出库", elTagType: "warning", elTagClass: null },
  { value: 2, label: "借料出库", elTagType: "danger", elTagClass: null },
  { value: 3, label: "已归还", elTagType: "primary", elTagClass: null },
]);
const dictTagData = () => {
  return bizTypeList.value.map((item) => ({
    ...item,
    value: String(item.value),
  }));
};

//修改主单据
const openBill = ref(false);
const billData = ref({});
function editData(row) {
  let obj = JSON.parse(JSON.stringify(row));
  billData.value.wlType = obj.wlType;
  billData.value.operationType = obj.operationType;
  billData.value.operator = obj.operator;
  billData.value.operationTime = obj.operationTime;
  billData.value.id = obj.id;
  billData.value.billNo = obj.billNo;
  billData.value.execStatus = obj.execStatus;
  openBill.value = true;
}
//修改主单据、保存
function editForm() {
  updateBill(billData.value).then((response) => {
    proxy.$modal.msgSuccess(response.msg);
    openBill.value = false;
    getList();
  });
}

// 删除单据
const delData = (row) => {
  delBill([row.id]).then((response) => {
    proxy.$modal.msgSuccess("删除成功");
    getList();
  });
}

// 单击单据
const billTableRef = ref(null);
// 单击列表的颜色
const infoTableRef = ref(null);
// const tableInfoRowClick = (row, ref) => {
//   ref.setCurrentRow(row)
// }

//双击单据，查询明细
const billDoubleClickObj = ref({});
const detailLoading = ref(false); //加载列表详情
function billClick(row, type, status) {
  if (type != "bill") {
    detailLoading.value = true;
  }
  billDoubleClickObj.value = row;
  detailList(type);
}

const billSelectionChange = (selection) => {
  console.log(selection);
  if (selection.length > 1) {
    proxy.$modal.msgError("只能选择一条数据");
    return;
  }
}

const checkStockList = ref([]); //移库、调度 多选框选中数据
//移库  多选框选中数据  生成调度任务多选
function printSelectionChange(selection) {
  checkStockList.value = JSON.parse(JSON.stringify(selection));
}

// 移库弹框
const openMove = ref(false); //移库
//移库弹框
function handleMove() {
  moveReason.value = "";
  if (checkStockList.value.length != 1) {
    proxy.$modal.msgError("请勾选一条数据");
    return;
  }
  checkStockList.value[0].toCangku = [
    checkStockList.value[0].parentWarehouseCode,
    checkStockList.value[0].cangku,
  ];
  checkStockList.value[0].toPcode = checkStockList.value[0].pcode;
  checkStockList.value[0].toTrayCode = checkStockList.value[0].trayCode;
  checkStockList.value[0].num = checkStockList.value[0].realQty;
  openMove.value = true;
  pcodeList([
    checkStockList.value[0].parentWarehouseCode,
    checkStockList.value[0].cangku,
  ]);
}
//移库提交
function submitMoveForm() {
  if (checkStockList.value.filter((item) => item.realQty == 0).length > 0) {
    proxy.$modal.msgError("数量不能为空");
    return;
  }
  if (checkStockList.value.filter((item) => !item.toPcode).length > 0) {
    proxy.$modal.msgError("存放位置不能为空");
    return;
  }
  if (checkStockList.value.filter((item) => !item.toCangku).length > 0) {
    proxy.$modal.msgError("仓库不能为空");
    return;
  }
  if (checkStockList.value[0].pcode == checkStockList.value[0].toPcode) {
    proxy.$modal.msgError(
      "不允许选择原来的库位【" + checkStockList.value[0].pcode + "】"
    );
    return;
  }
  if (checkStockList.value[0].realQty < checkStockList.value[0].num) {
    proxy.$modal.msgError("移库数量不正确");
    return;
  }
  let arr = JSON.parse(JSON.stringify(checkStockList.value));
  arr[0].toCangku = arr[0].toCangku[1];
  let submitData = {
    fromRkId: checkStockList.value[0].id,
    moveReason: moveReason.value,
    targets: arr,
  };
  moveRecord(submitData).then((response) => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess("操作成功");
      //数据列表
      detailList();
      openMove.value = false;
    } else {
      proxy.$modal.msgError("操作失败");
    }
  });
}
function cancelMove() {
  openMove.value = false;
}

function isMoveFun(isMove) {
  if (isMove == 0) {
    return "否";
  } else if (isMove == 1) {
    return "是";
  }
}

// 查看入库单
const dialogBill = ref(false);
const billAllObj = ref([]);
const stockList = ref([]); //明细列表
//查询明细列表数据方法
function detailList(type) {
  listStock(billDoubleClickObj.value.billNo).then((response) => {
    if (response.data.length == 0) {
      proxy.$modal.msgError("该条入库单暂无明细");
      return;
    }
    if (type == "bill") {
      billAllObj.value = response.data;
      dialogBill.value = true;
      return;
    }
    stockList.value = response.data;
    detailLoading.value = false;
  });
}

// 单条添加物料
function addOne() {
  handleAdd(true);
  if (stockList.value.length > 0) {
    storeData.value.operationType = stockList.value[0].operationType;
    storeData.value.wlType = billDoubleClickObj.value.wlType;
    storeData.value.operator = stockList.value[0].operator;
    storeData.value.warehouseCode = [
      stockList.value[0].parentWarehouseCode,
      stockList.value[0].cangku,
    ];
    pcodeList(storeData.value.warehouseCode);
    storeData.value.operationTime = stockList.value[0].operationTime;
    storeData.value.billNo = stockList.value[0].billNo;
  }
}

//根据物料号查询物料信息
function searchInfo(wlNo, index) {
  wlSearch(wlNo).then((res) => {
    if (res.rows.length > 0) {
      let info = res.rows[0];
      planList.value[index].wlMs = info.desMat;
      planList.value[index].dw = info.unt;
      planList.value[index].htDj = info.uprc;
    } else {
      proxy.$modal.msgWarning("暂无物料信息");
      return;
    }
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  idEdit.value = row.id;
  row.isnew = true;
  planList.value = [JSON.parse(JSON.stringify(row))];
  storeData.value.warehouseCode = [
    row.parentWarehouseCode,
    row.cangku,
  ];
  pcodeList(storeData.value.warehouseCode);
  open.value = true;
  outTempData.value = []
  title.value = "修改库存单据";
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 右侧修改的表单重置
function reset() {
  planList.value = [];
  storeData.value = {};
  proxy.resetForm("stockRef");
}
function closeDialog() {
  idEdit.value = 0;
}

// 撤销入库
const handleStockDelete = (row) => {
  proxy.$modal
    .confirm("确定撤销吗？")
    .then(function () {
      return backoutRecord({ ids: [row.id] });
    })
    .then(() => {
      detailList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => { });
};

// 一键撤销
const handleOneClickStockDelete = (row) => {
  if (checkStockList.value.length == 0) {
    proxy.$modal.msgError("请勾选数据");
    return;
  }
  const ids = []
  for (let i = 0; i < checkStockList.value.length; i++) {
    if (checkStockList.value[i].execStatus == 1) {
      ids.push(checkStockList.value[i].id)
    }
  }
  if (ids.length == 0) {
    proxy.$modal.msgSuccess("勾选数据撤销完成");
    return;
  }
  backoutRecord({ ids: ids }).then((response) => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess("操作成功");
      detailList();
    } else {
      proxy.$modal.msgError("操作失败");
    }
  });
};

// 一键删除
const handleOneClickStockDel = () => {
  if (checkStockList.value.length == 0) {
    proxy.$modal.msgError("请勾选数据");
    return;
  }
  if (checkStockList.value.some(item => item.execStatus == 1)) {
    proxy.$modal.msgError("已入库数据不能删除");
    return;
  }
  const ids = checkStockList.value.map(item => item.id)
  recordRemove(ids).then((response) => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess("操作成功");
      detailList();
    } else {
      proxy.$modal.msgError("操作失败");
    }
  });
};



//  一键入库
function handleOneClickWarehousing() {
  if (checkStockList.value.length == 0) {
    proxy.$modal.msgError("请勾选数据");
    return;
  }
  const ids = []
  for (let i = 0; i < checkStockList.value.length; i++) {
    if (checkStockList.value[i].execStatus == 0) {
      ids.push(checkStockList.value[i].id)
    }
  }
  if (ids.length == 0) {
    proxy.$modal.msgSuccess("勾选数据入库完成");
    return;
  }
  recordFinish({ ids: ids }).then((response) => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess("操作成功");
      detailList();
    } else {
      proxy.$modal.msgError("操作失败");
    }
  });
}

// **************************************************************************



































function handleDispatch() {
  if (checkStockList.value.length == 0) {
    proxy.$modal.msgError("请勾选数据");
    return;
  }
  let isDiaodu = checkStockList.value.some((item) => item.execStatus == 0);
  if (isDiaodu) {
    proxy.$modal.msgWarning("预入库数据不能生成调度任务");
    return;
  }
  dispatchOpen.value = true;
}
// 提交调度任务
function submitDispatch() {
  // console.log(resource.value)
  if (!resource.value) {
    proxy.$modal.msgWarning("请选择调度模式");
    return;
  }
  let data;

  data = checkStockList.value.map((item) => ({
    sourceName: "V01-010101",
    targetName: item.pcode,
    taskTypeName: "上架",
    taskType: 0,
    mid: item.wlNo,
    num: 1,
    dispatchMode: resource.value,
  }));

  // if (billStatus.value == "rk") {
  //   data = checkStockList.value.map((item) => ({
  //     sourceName: "V01-010101",
  //     targetName: item.pcode,
  //     taskTypeName: "上架",
  //     taskType: 0,
  //     mid: item.wlNo,
  //     num: 1,
  //     dispatchMode: resource.value,
  //   }));
  // } else if (billStatus.value == "ck") {
  //   data = checkStockList.value.map((item) => ({
  //     sourceName: item.pcode,
  //     targetName: "V01-010101",
  //     taskTypeName: "下架",
  //     taskType: 1,
  //     mid: item.wlNo,
  //     num: 1,
  //     dispatchMode: resource.value,
  //   }));
  // }
  //调用生成调度任务接口
  generateDispatch(data).then((response) => {
    // console.log(11111)
    // console.log(response)
    if (response.code == 200) {
      proxy.$modal.msgSuccess("生成调度任务成功");
      dispatchOpen.value = false;
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });
}
const handleChange = (file, fileLists) => {
  fileList.value = fileLists.map((f) => f.raw); // 提取原始文件对象
};
function submitUpload() {
  const formData = new FormData();
  fileList.value.forEach((file) => {
    formData.append("files", file.raw); // 后端需支持多文件字段
  });

  formData.append("photoType", uploadParams.value.photoType);
  formData.append("billNo", uploadParams.value.billNo);
  formData.append("documentType", uploadParams.value.typeName);
  if (uploadParams.value.photoType == 1) {
    formData.append("xmMs", uploadParams.value.xmMs);
  } else {
    formData.append("gysMc", uploadParams.value.gysMc);
  }
  uploadContract(formData).then((response) => {
    if (response.code == 200) {
      uploadParams.value = {};
      fileList.value = [];
      dialogPicVisible.value = false;
    }
  });
}
//查看图片详情
function picDetailFun(billId, type, isOpen) {
  if (isOpen == 1) {
    billObj.value.billNo = billId;
    billObj.value.type = type;
  }
  picDetail({ billNo: billId, photoType: type }).then((response) => {
    if (response.data.length > 0) {
      if (isOpen == 1) {
        dialogPicDetailVisible.value = true;
      }
      picList.value = response.data;
      urlList.value = response.data.map((item) => {
        return item.url;
      });
    } else {
      picList.value = [];
      urlList.value = [];
      proxy.$modal.msgWarning("暂无图片");
    }
    this.$forceUpdate();
  });
}

function preview(url) {
  srcList.value = [url];
}
//勾选自动填充备注
function autoFillFun() {
  if (autoFill.value && !kzms.value) {
    autoFill.value = false;
    proxy.$modal.msgWarning("扩展描述不能为空");
    return;
  }
  if (autoFill.value && kzms.value && planList.value.length > 0) {
    for (let i = 0; i < planList.value.length; i++) {
      planList.value[i].remark = kzms.value;
    }
  } else if (!autoFill.value) {
    for (let i = 0; i < planList.value.length; i++) {
      planList.value[i].remark = "";
    }
  }
  // console.log(autoFill.value)
}
// 上传成功回调
function handleAvatarSuccess(res, id, pcode) {
  for (let i = 0; i < planList.value.length; i++) {
    if (planList.value[i].id == id && planList.value[i].pcode == pcode) {
      planList.value[i].photoUrl = res.url;
    }
  }

}
//删除图片
function handleRemove(res, id, pcode) {
  for (let i = 0; i < planList.value.length; i++) {
    if (planList.value[i].id == id && planList.value[i].pcode == pcode) {
      planList.value[i].photoUrl = "";
    }
  }
}
function delPic(picId) {
  proxy.$modal
    .confirm("确定删除吗？")
    .then(function () {
      return delPicF(picId);
    })
    .then(() => {
      picDetailFun(billObj.value.billNo, billObj.value.type, 2);
      // getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => { });
}
//预览图片
function handlePreview(uploadFile) {
  // console.log(222222)
  // console.log(res)
  dialogImageUrl.value = uploadFile.response.url;
  dialogVisible.value = true;
}
function tableRowClassName({ row, rowIndex }) {
  // console.log(row)
  // 根据每行的数据，判断isError来增加class属性
  if (row.isAdd) {
    return "warning-row";
  }
  // else {
  //   return 'success-row'
  // }
  return "";
}


//入库上传图片按钮
function rkUpload() {
  if (!uploadParams.value.billNo) {
    proxy.$modal.msgWarning("请选择单据");
    return;
  }
  dialogPicVisible.value = true;
}
function handlePictureCardPreview(info) {
  dialogVisible.value = true;
  dialogImageUrl.value = info.url;
  // console.log(info)
}

const dialogDelStock = ref(false);
const delStockFormRef = ref(null);
const delStockForm = ref({
  billNo: "",
});
const delStockRules = ref({
  billNo: [{ required: true, message: "请输入单据号", trigger: ["blur"] }],
});
const submitDelStock = () => {
  proxy.$refs["delStockFormRef"].validate((valid) => {
    if (valid) {
      wisdomDelStock(delStockForm.value.billNo).then((response) => {
        if (response.code == 200) {
          proxy.$modal.msgSuccess("操作成功");
          //数据列表
          getList();
          dialogDelStock.value = false;
        } else {
          proxy.$modal.msgError("操作失败");
        }
      });
    }
  });
};
/** 导出按钮操作 */
function handleExport() {
  let obj = JSON.parse(JSON.stringify(queryParams.value));
  obj.bizTypeList = [0];
  proxy.download(
    "wisdom/record/export",
    obj,
    `入库管理_${parseTime(new Date().getTime(), '{y}年{m}月{d}日 {h}_{i}_{s}')}.xlsx`

  );
}
//打印单据
function handlePrint() {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 月份从0开始，需要加1
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  dateStr.value =
    year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
  showContent.value = true;
}
//打印标签
function handlePrintTag() {
  if (checkStockList.value.length == 0) {
    proxy.$modal.msgError("请勾选数据");
    return;
  }
  if (!printNum.value) {
    proxy.$modal.msgError("请选择打印机编号");
    return;
  }
  // let newArr = new Array();
  for (let i = 0; i < checkStockList.value.length; i++) {
    checkStockList.value[i].printer = printNum.value;
  }

  printTag(checkStockList.value).then((response) => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess("打印指令已发送");
    } else {
      proxy.$modal.msgError("操作失败");
    }
  });
}

const isExamine = ref(0); //是否需要开启审核 1开启；0不开启
//判断是否需要开启审核功能
function isAudit() {
  // {configKey:"stock.audit.enabled"}
  getAudit().then((response) => {
    // console.log(2222222)
    // console.log(response.msg)
    isExamine.value = response.msg;
  });
}
//是否开启审核
isAudit();
</script>
<style scoped lang="scss">
.printMeBox {
  div {
    line-height: 30px;
  }
}

.topBox {
  /* margin-bottom: 10px; */
  display: flex;
  flex-wrap: wrap;
}

.bottomBox {
  margin-top: 20px;
}

.oneLineBox {
  display: flex;
}

.everyBox {
  /* width: 30%; */
  width: 50%;
}

.examine {
  margin-top: 20px;
  height: 100px;
  background-color: #ededed;
  padding: 20px 0 0 20px;
  border-radius: 10px;
}

/* .dialog_class{
  pointer-events: none;
}
.el-dialog{
  pointer-events: auto;
} */
/* /deep/  .el-overlay .el-modal-dialog {
    z-index: 4;
	} */
::v-deep .el-modal-dialog {
  z-index: 1;
}

.picBox {
  display: flex;
}

.everyPicBox {
  position: relative;
}

.closeBox {
  position: absolute;
  right: 5px;
  z-index: 1;
  top: -15px;
}

.searchBtn {
  display: flex;
  justify-content: flex-end;
}


.addBox {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  cursor: pointer;

  .addData {
    display: flex;
    align-items: center;
    color: var(--el-text-color-regular);
    font-weight: bold;
  }

}
</style>
