<template>
  <div class="app-container" >
    
    <el-splitter>
      <el-splitter-panel size="40%">
          <el-form :model="queryParams" ref="queryRef"  v-show="showSearch" label-width="90">
            <el-row >
              <el-col :span="12">
                <el-form-item label="入库时间" prop="rkTime">
                  <el-date-picker
                    v-model="rkTime"
                    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>
              <!-- billNo -->
              <el-col :span="10">
                <el-form-item label="单据号" prop="keyword">
                  <el-input
                    v-model="queryParams.keyword"
                    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="10">
                <el-form-item label="出库单据号" prop="billNoCk">
                  <el-input
                    v-model="queryParams.billNoCk"
                    placeholder="请输入入库单据号"
                    clearable
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="10">
                <el-form-item label="库存状态" prop="isChuku">
                  <el-select v-model="queryParams.isChuku" placeholder="请选择" clearable @change="changeStore" @keyup.enter="handleQuery">
                      <el-option v-for="dict in storeStatusList" :key="dict.id" :label="dict.statusName" :value="dict.id" />
                  </el-select>
                </el-form-item>
              </el-col> -->
              
            </el-row>
          </el-form>
          <el-row  class="mb8">
            <el-col :span="4">
              <el-button
                type="primary"
                plain
   
                @click="handleAdd(false)"
                v-hasPermi="['wisdom:bill:add']"
              >新增入库</el-button>
            </el-col>
            <el-col :span="4">
              <el-button
                type="warning"
                plain
           
                @click="handleExport"
                v-hasPermi="['wisdom:bill:export']"
              >导出</el-button>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" plain   @click="editData">修改</el-button>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" plain  @click="rkUpload">图片上传</el-button>
            </el-col>
            
            <el-col :span="8" >
              <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-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Switch"
                @click="handleSwitch"
                v-hasPermi="['wisdom:stock:move']"
              >出库上传</el-button>
            </el-col> -->
            <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
          </el-row> 
          <!-- @selection-change="printSelectionChange" -->
        <el-table v-loading="loading" highlight-current-row  :data="billList" :row-class-name="tableBillRowClassName"  @row-dblclick="billClick" @current-change="uploadSelectionChange">
          <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">
              <dict-tag :options="dictTagData()" :value="scope.row.bizType" />
            </template>
          </el-table-column>
          <el-table-column label="理货员" align="center" prop="operatorName" width="100" />
          <el-table-column label="入库类型" align="center" prop="operationTypeName" width="120"/>
          <el-table-column label="所属大库" align="center" prop="parentWarehouseName" width="120"/>
          <el-table-column label="所属小库" align="center" prop="warehouseName" width="120"/>
          <el-table-column label="物资类型" align="center" prop="wlTypeName" width="100">
            <template #default="scope">
              <span>{{ wzTypeFun(scope.row.wlType)  }}</span>
            </template>
          </el-table-column>
          <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="teamName" width="160" /> -->
          <el-table-column label="操作" align="center"  width="280">
            <template #default="scope">
              <el-button link type="primary"  @click="picDetailFun(scope.row.billNo,0,1)">入库图片</el-button>
              <el-button link type="primary"  @click="picDetailFun(scope.row.billNoCk,1,1)">出库图片</el-button>
              <el-button link type="primary" @click="billClick(scope.row, 'bill', 'rk')">入库单</el-button>
              <!-- <el-button link type="primary" v-show="scope.row.isChuku == 1 || scope.row.isChuku == 3"  @click="billClick(scope.row, 'bill', 'ck')">出库单</el-button> -->
            </template>
          </el-table-column>
          <!-- <el-table-column label="所属仓库" align="center" prop="cangkuName" /> -->
        </el-table>
        <!-- <el-pagination
        style="margin-top: 20px;"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="queryParams.pageSize"
        @current-change="getList"
      ></el-pagination> -->
      <!-- <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        /> -->
        <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="handleSwitch"
                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="5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleDispatch"
              >生成调度任务</el-button>
            </el-col>
            <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
          </el-row> 
        <el-table v-loading="detailLoading" 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" width="100">
            <template #default="scope">
              <dict-tag :options="dictTagData()" :value="scope.row.isChuku" />
            </template>
          </el-table-column> -->
          <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="sapNo" width="150"/>
          <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="isMove" >
            <template #default="scope">
              <span>{{ isMoveFun(scope.row.hasMoved)  }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库位码" align="center" prop="pcode" width="120"/>
          <el-table-column label="托盘码" align="center" prop="trayCode" />
          <el-table-column label="身份码" align="center" prop="entityId" width="200"/>
          <!-- <el-table-column label="入库类型" align="center" prop="rkTypeName" width="150"/> -->
          <!-- <el-table-column label="物资类型" align="center" prop="wlTypeName" width="100"/> -->
          <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="rkTime" width="200">
            <template #default="scope">
              <span>{{ parseTime(scope.row.rkTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="还料时间" align="center" prop="returnTime" width="200">
            <template #default="scope">
              <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="库龄" align="center" prop="stockAge" />
          <!-- <el-table-column label="理货员" align="center" prop="lihuoYName" /> -->
          <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="remark" width="200"/>
          <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"  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']" v-show="scope.row.isChuku!=1 && scope.row.isChuku!=3">修改</el-button>
              <!-- <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleStockDelete(scope.row)"
              v-hasPermi="['wisdom:bill:delete']"
              v-show="scope.row.isChuku==0|| scope.row.isChuku==1"
            >撤销</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"  >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库类型" >
              <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="物资类型" >
              <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="warehouseCode">
              <el-cascader :options="warehouseList" v-model="billData.warehouseCode" :props="{children: 'children', label: 'warehouseName', value: 'warehouseCode'}" />
              
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="入库时间" >
              <el-date-picker
              style="width: 100%;"
                v-model="billData.rkTime"
                type="datetime"
              />
            </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>
    <!-- 添加或修改库存单据主对话框 -->
    <!-- append-to-body -->
    <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" v-if="idEdit==0">
          <el-col :span="6">
            <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">
            <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-select v-model="storeData.cangku" placeholder="请选择仓库" clearable >
                <el-option v-for="dict in warehouseList" :key="dict.id" :label="dict.warehouseName" :value="dict.warehouseCode" />
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="理货员" prop="lihuoY">
              <el-select v-model="storeData.lihuoY" 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="rkTime">
              <!-- type="date" -->
              <el-date-picker
                v-model="storeData.rkTime"
                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 execStatusList" :key="dict.id" :label="dict.name" :value="dict.id" />
              </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-col :span="2">
            <el-button type="danger" @click="delLineFun" >删除</el-button>
          </el-col> -->
        </el-row>
        <el-table :data="planList" height="400" style="width: 100%" show-overflow-tooltip :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="50" />
          <el-table-column label="状态" align="center" prop="status" width="100">
            <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-select
                v-model="scope.row.pcode"
                :disabled="idEdit!=0"
                clearable
                filterable
                placeholder="请选择库位"
              >
                <el-option
                  v-for="item in kwOptions"
                  :key="item.id"
                   
                  :label="item.pcode"
                  :value="item.pcode"
                />
              </el-select>
              <!-- <div style="color:#409eff;cursor:pointer;" @click="selectKw(scope.row)">请选择</div> -->
            </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="200">
            <template #default="scope">
              <el-input v-model="scope.row.remark" 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" 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="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="openSwitch"  append-to-body width="60%">
          
      <el-form  :model="switchData" :rules="rules" >
        
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="物料号" >
              <el-input v-model="printList[0].wlNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目号" >
              <el-input v-model="printList[0].xmNo"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单号" >
              <el-input v-model="printList[0].sapNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目描述" >
              <el-input v-model="printList[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-row :gutter="20">
          <el-col :span="6">
            <el-form-item  >
              <el-button type="primary"  icon="Plus" @click="addLine">添加</el-button>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-table :data="switchData" height="400" style="width: 100%" >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          
          <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>
              <!-- <div style="color:#409eff;cursor:pointer;" @click="selectKw(scope.row)">请选择</div> -->
            </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-select
                v-model="scope.row.toCangku"
                clearable
                filterable
                placeholder="请选择仓库"
              >
              <el-option v-for="dict in warehouseList" :key="dict.id" :label="dict.warehouseName" :value="dict.warehouseCode" />
              </el-select> -->
              <el-cascader :options="warehouseList" v-model="scope.row.toCangku" @change="pcodeList" :props="{children: 'children', label: 'warehouseName', value: 'warehouseCode'}" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
    
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.$index)" >删除</el-button>
            </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="billStatus == 'rk' ? '入库单' : '出库单'" v-model="dialogBill"  append-to-body width="80%" :close-on-click-modal="false">
      <bill :billAllObj="billAllObj" :billStatus="billStatus" />
      <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, listStock } 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";

const headers = ref({
  Authorization: "Bearer " + getToken()
});
const { proxy } = getCurrentInstance();

const stockList = ref([]);  //明细列表
const open = ref(false);
const openSwitch = ref(false);  //移库
const detailLoading = ref(false);  //加载列表详情
const showSearch = ref(true);
const idEdit = ref(0);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const planLoading = ref(true);
const planList = ref([]); //从供应计划中添加列表
const checkPlanList = ref([]);  //已选中的要入库的数据

const orderNum = ref("")    //搜索条件：订单号
const kwOptions = ref([]);  //库位下拉
const showContent = ref(false); // 控制打印内容是否显示
const dateStr = ref("")   //打印单据生成的日期
const printList = 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(0)     //打印机编号
const moveReason = ref("")  //移库原因
const rkTime = 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 billData = ref({})
const openBill = ref(false)
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 dispatchList = ref([]) //要生成调度任务的数据列表
const resource = ref("") //调度模式 1仅立库；2立库+AGV
const dispatchOpen = ref(false) //调度任务弹窗

const data = reactive({
  fileList:[],
  form: {},
  storeData:{
    rkTime: ''
  },   //入库数据
  switchData:[],  //移库数据
  queryParams: {
    keyword:"",
    pageNum: 1,
    pageSize: 10,
    startTime:null,
    endTime: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" }],
    lihuoY: [{ required: true, message: "理货员不能为空", trigger: "change" }],
    execStatus: [{ required: true, message: "是否预入库不能为空", trigger: "change" }],
    rkTime: [{ 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,switchData,switchRules } = toRefs(data);

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

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 execStatusList = ref([
  {id:0, name:"是"},
  {id:1, name:"否"}
])

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

// 显示预出库的状态
const tableBillRowClassName = ({ row, rowIndex }) => {
  if (rowIndex == 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)
  }));
}




function handleDispatch(){
  if(dispatchList.value.length==0){
    proxy.$modal.msgError("请勾选数据");
    return
  }
  dispatchOpen.value = true
  
}
// 提交调度任务
function submitDispatch(){
  // console.log(resource.value)
  if(!resource.value){
    proxy.$modal.msgWarning("请选择调度模式");
    return
  }
  let data
  if(billStatus.value == 'rk'){
    data = dispatchList.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 = dispatchList.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);
    }
  })

}
function billFun(row){
  if(row.isChuku == 0){
    return row.billNo
  } else if(row.isChuku == 1 || row.isChuku==3){
    return row.billNoCk
  }
}
const handleChange = (file, fileLists) => {
  // console.log(file)
  fileList.value = fileLists.map(f => f.raw); // 提取原始文件对象
  // console.log(fileList.value)
};
function submitUpload() {
      // console.log(fileList.value)
      // return
  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);
  }
  // console.log(formData)
  // return

  /**
   * 所有选择的文件，放到FormData对象中上传
   * fileName[] 属性名根据自身情况定义
   */
  // console.log(fileList.value)
  // return
  // fileList.value.map((file) => {
  //   uploadParams.value.files.push(file.raw)
  // });
  // console.log(uploadParams.value)
  // console.log(uploadParams.value)
  // return
  uploadContract(formData).then(response => {
    if(response.code == 200){
      uploadParams.value = {}
      fileList.value = []
      dialogPicVisible.value = false
    }
    // this.fileList = [];
  });
}
//查看图片详情
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()
        // console.log(1111)
        // console.log(response)
  });
  
}

const billNo = ref('')
//双击单据，查询明细
function billClick(row, type, status){
  if (type != 'bill') {
    detailLoading.value = true;
  }
  billNo.value = row.billNo
  detailList();
}
//查询明细列表数据方法
function detailList(){
  listStock(billNo.value).then(response => {
    stockList.value = response.data;
    detailLoading.value = false;
  });
}
function lhyFun(row){
  if(row.isChuku==0){
    // return row.lihuoY
    return row.lihuoYName
  }else {
    return row.ckLihuoY
  }
}
function wzTypeFun(wlType){
  let wlTypeName = ""
  wzTypeList.value.forEach(item=>{
    if(item.typeCode == wlType){
      wlTypeName = item.typeName
    }
  })
  
  return wlTypeName
}
function isChukuFun(isChuku){
  // scope.row.isChuku==0?"已入库":(scope.row.isChuku==1?"已出库":"审批中")
  if(isChuku == 0){
    return "已入库"
  } else if(isChuku == 1){
    return "已出库"
  }else if(isChuku == 3){
    return "借料出库"
  }else if(isChuku == 2){
    return "审批中"
  }else if(isChuku == 4){
    return "入库撤销"
  }else if(isChuku == 5){
    return "出库撤销"
  }
}
function isMoveFun(isMove){
  if(isMove == 0){
    return "否"
  } else if(isMove == 1){
    return "是"
  }
}
function changeStore(val){
  if(val==0){
    queryParams.value.isChukuList = [0]
  }else if(val==1){
    queryParams.value.isChukuList = [1,3]
  }else{
    queryParams.value.isChukuList = [0,1,3]
  }
}
function delLineFun(index){
  // console.log(index)
  proxy.$modal.confirm('确定删除吗？').then(function() {
    
    return  planList.value.splice(index,1)
  
  
}).then(() => {
  
}).catch(() => {});
  // if(checkPlanList.value.length==0){
  //   proxy.$modal.msgWarning("请勾选数据");
  //   return
  // }

}
//供应计划中没有，手动添加的数据
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)
}
//根据物料号查询物料信息
function searchInfo(wlNo,index){
  // console.log(33333)
  // console.log(index)
  // return
  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
    }
    
    // console.log(111111)
    // console.log(res)
  })
}
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){
  // console.log(222222)
  // console.log(id)
  // console.log(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
    }
  }
  // console.log(222222)
  // console.log(res)
  // console.log(row)
}
//删除图片
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 = ""
    }
  }
  // console.log(33333333)
  // console.log(planList.value)
  // console.log(res)
  // console.log(id)
  // console.log(pcode)
}
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 getDetailList(){
  
      listStock(detailQueryParams.value).then(response => {
        stockList.value = response.rows;
        detailTotal.value = response.total;
        detailLoading.value = false;
      });
}

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




// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
//移库取消
function switchCancel(){
  openSwitch.value = false
  switchData.value = {}
}
// 表单重置
function reset() {
  planList.value = []
  storeData.value = {}
  proxy.resetForm("stockRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  
  if(rkTime.value && rkTime.value.length>0){
    queryParams.value.startTime = rkTime.value[0]
    queryParams.value.endTime = rkTime.value[1]
  }else{
    queryParams.value.startTime = ""
    queryParams.value.endTime = ""
  }
  queryParams.value.pageNum = 1;
  if(printList.value.length>0){
    queryParams.value.ids = printList.value.map( item => item.id )	
  }
  // console.log(queryParams.value)
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  rkTime.value = []
  // queryParams.value.startTime = ""
  // queryParams.value.endTime = ""
  queryParams.value.isChukuList = [0,1,3]
  handleQuery();
}

//新增入库 多选框选中数据
function handleSelectionChange(selection) {
  // console.log(selection)
  checkPlanList.value = selection
  // console.log(selection)
  // ids.value = selection.map(item => item.id);
  
}

//上传、修改 单选 选中数据
function uploadSelectionChange(selection){
  if(selection){
    billData.value = selection  //修改数据用
    billData.value.warehouseCode = billData.value.cangku
    uploadParams.value.photoType = selection.isChuku
    uploadParams.value.billNo = selection.billNo
    uploadParams.value.typeName = selection.rkTypeName

    if(selection.isChuku=='3' || selection.isChuku=='1'){
      uploadParams.value.photoType = 1
      uploadParams.value.billNo = selection.billNoCk
      uploadParams.value.typeName = selection.ckTypeName
    }
    
    
    uploadParams.value.gysMc = selection.gysMc
    uploadParams.value.xmMs = selection.xmMs
  }
  
  // console.log(selection)
}

//移库、修改  多选框选中数据  生成调度任务多选
function printSelectionChange(selection){
  dispatchList.value = selection
  printList.value = selection
  // console.log(printList.value)
  queryParams.value.ids = selection.map(item => item.id)
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  // console.log(queryParams.value.ids)
}
//修改主单据
function editData(){
  // if(billData.value && billData.value.isChuku == 0){
    //查询修改信息
    // console.log(billData.value)
    getEditInfo(billData.value.billNo).then(response=>{
      billData.value = response.data
      billData.value.warehouseCode = [billData.value.parentWarehouseCode,billData.value.warehouseCode]
      // console.log(billData.value)
      openBill.value = true
    })
  // }else{
  //   proxy.$modal.msgWarning("仅支持修改入库单据");
  //     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)
}
// function handleScRemove(info){
//   console.log(info)
// }
// 单条添加物料
function addOne(){
  handleAdd(true)
  
  if(stockList.value.length>0){
    storeData.value.operationType = stockList.value[0].operationType
    storeData.value.wlType = stockList.value[0].wlType
    // storeData.value.cangku = stockList.value[0].cangku
    storeData.value.lihuoY =  Number(stockList.value[0].lihuoY)
    storeData.value.warehouseCode =  [stockList.value[0].parentWarehouseCode ,stockList.value[0].warehouseCode]
    storeData.value.rkTime = stockList.value[0].rkTime
    storeData.value.billNo = stockList.value[0].billNo
    
  }
}

/** 新增按钮操作 */
function handleAdd(single) {
  isSingle.value = single
  reset();
  open.value = true;
  title.value = "添加库存单据";
  //获取入库类型下拉数据
  warehousingDict().then(response=>{
    storeTypeList.value = response.data
  })
  //理货员下拉数据
  personListDict().then(response=>{
    personList.value = response.data
  })
}





// 新增入库的列表状态
const statusList = ref([
  { value: 0, label: "未到货"},
  { value: 1, label: "已入库"},
  { value: 2, label: "部分入库"}
])


//从供应计划中添加 搜索
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].jhQty
        planData[i].gysJhId = planData[i].id
        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
    }
    // console.log(planData)
    planList.value = planData
    // planLoading.value = false
  })
  
}
//添加数量
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 = ""
  // console.log(addRow)
  addRow.isAdd = true
  // console.log(row)
  planList.value.push(addRow)
}
// function selectKw(row){
//   console.log(row)
// }
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  idEdit.value = row.id
  getStock(row.id).then(response => {
    let dataInfo = response.data
    dataInfo.isnew = true
    storeData.value.operationType = dataInfo.operationType
    storeData.value.wlType = dataInfo.wlType
    storeData.value.rkTime = dataInfo.rkTime
    storeData.value.warehouseCode = [dataInfo.parentWarehouseCode ,dataInfo.warehouseCode]
    pcodeList(storeData.value.warehouseCode)
    storeData.value.lihuoY = parseInt(dataInfo.lihuoY) 
    planList.value = [dataInfo]
    // form.value = response.data;
    open.value = true;
    title.value = "修改库存单据";
  });
}
function closeDialog(){
  idEdit.value = 0
}
//修改主单据、保存
function editForm(){
  console.log(billData.value.warehouseCode)
  billData.value.warehouseCode = billData.value.warehouseCode[billData.value.warehouseCode.length-1]
  editBill(billData.value).then(response=>{
    proxy.$modal.msgSuccess(response.msg);
    openBill.value = false
    getList();
  })
}

/** 提交按钮 */
function submitForm() {
  
  // console.log(submitData);return
  // // /pc/wisdom/stock/add
  // console.log(planList);return
  proxy.$refs["stockRef"].validate(valid => {
    
    if (valid) {
      // if(planList.value.filter(x=>x.realQty=="").length>0){
      //   proxy.$modal.msgError("入库数量不能为空");
      //   return
      // }
      // console.log(storeData.value.rkType)
      // return
      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 isNumTrue = false	  //入库数量是否正确
      let iscfwz = false      //库位是否为空
      let bigData = checkPlanList.value
      let smallData = checkPlanList.value
      for(let i=0;i<bigData.length;i++){
        // let sumNum = 0
        //库位
        if(!bigData[i].pcode){
          iscfwz = true
        }
        //入库数量
        // for(let j=0;j<smallData.length;j++){
        //   if(bigData[i].id == smallData[j].id){
        //     sumNum += Number(smallData[j].realQty)*1000
        //   }
        // }
        // if(bigData[i].jhQty != sumNum/1000){
        //   isNumTrue = true
        //   break;
        // }
      }
      // if(isNumTrue){
      //   proxy.$modal.msgError("入库数量不正确");
      //   return
      // }
      //发现场入库类型可以不用选库位
      if(storeData.value.operationType!="RK025" && iscfwz){
        proxy.$modal.msgError("请选择库位");
        return
      }
      if(isExamine.value==1 && !storeData.value.approverId){
        proxy.$modal.msgError("审批人不能为空");
        return
      }
      // console.log(checkPlanList.value)
      // return
      
      
      // console.log(submitData)
      // return
      checkPlanList.value.forEach(item=>{
        item.bizType = 0
      })
      let arr = JSON.parse(JSON.stringify(checkPlanList.value[0]))
      delete arr.warehouseCode
      // console.log(arr)
      if(idEdit.value!=0){  //修改
        let submitData = {
          cangku:storeData.value.warehouseCode[storeData.value.warehouseCode.length-1],    //所属仓库
          operator:storeData.value.lihuoY,    //理货员
          operationType:storeData.value.operationType,    //入库类型
          wlType:storeData.value.wlType,    //物资类型
          approverId:storeData.value.approverId,  //审批人
          operationTime:storeData.value.rkTime,    //入库时间
          execStatus:storeData.value.execStatus,    //是否预入库
          bizType: 0,
          id:idEdit.value,
          // rkList:planList.value
          ...arr
        }
        updateStock(submitData).then(response=>{
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          // getList();
          detailList()
        })
      }else{  //新增
        console.log(storeData.value)
        let submitData = {
          rkBill: {
            cangku:storeData.value.warehouseCode[storeData.value.warehouseCode.length-1],    //所属仓库
            operator:storeData.value.lihuoY,    //理货员
            operationType:storeData.value.operationType,    //入库类型
            wlType:storeData.value.wlType,    //物资类型
            approverId:storeData.value.approverId,  //审批人
            operationTime:storeData.value.rkTime,    //入库时间
            execStatus:storeData.value.execStatus,    //是否预入库
            id:idEdit.value,
            bizType: 0,
            billNo:storeData.value.billNo && isSingle.value ? storeData.value.billNo : null,
          },
          // rkList:planList.value
          rkInfoList:checkPlanList.value
        }
        console.log(submitData)
        // return
        if(isSingle.value){   //单条添加
          addOneStock(submitData).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              detailList()
          });
        }else{  //多条添加
          addBill(submitData).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            });
        }
        
      }
      
    }
  });
}
//移库弹框
function handleSwitch(){
  switchData.value = []
  moveReason.value = ""
  if(printList.value.length!=1){
    proxy.$modal.msgError("请勾选一条数据");
    return
  }
  if(printList.value[0].isChuku==1){
    proxy.$modal.msgError("已出库，不允许移库");
    return
  }
  //库位下拉数据
  // pcodeList()
  openSwitch.value = true
  const {
    realQty:realQty,
    pcode:toPcode,
    trayCode:toTrayCode,
    parentWarehouseCode:parentWarehouseCode,
    warehouseCode:warehouseCode
  } = printList.value[0]
  // console.log({realQty,toPcode})
  // switchData.value = printList.value
  switchData.value[0] = {
    realQty,
    toPcode,
    toTrayCode,
    toCangku:[parentWarehouseCode, warehouseCode]
  }
  pcodeList(switchData.value[0].toCangku)
  console.log(switchData.value[0].toCangku)
  // console.log(printList.value)
}
//减一行
function handleDelete(index){
  // console.log(index)
  switchData.value.splice(index, 1);
}
//加一行
function addLine(){
  const addData = {
    realQty:0,
    toPcode:"",
    toTrayCode:"",
    toCangku:""
  }
  switchData.value.push(addData)
}
//移库提交
function submitMoveForm(){
  if(switchData.value.length==0){
    proxy.$modal.msgError("请添加数据");
    return
  }
  if(switchData.value.filter(item=>item.realQty==0).length>0){
    proxy.$modal.msgError("数量不能为空");
    return
  }
  if(switchData.value.filter(item=>!item.toPcode).length>0){
    proxy.$modal.msgError("存放位置不能为空");
    return
  }
  if(switchData.value.filter(item=>!item.toCangku).length>0){
    proxy.$modal.msgError("仓库不能为空");
    return
  }
  // if(switchData.value.length==1 && printList.value[0].realQty==switchData.value[0].realQty && printList.value[0].pcode==switchData.value[0].toPcode && printList.value[0].cangku==switchData.value[0].toCangku){
  //   proxy.$modal.msgError("请选择新的存放位置");
  //   return
  // }
  if(switchData.value.filter(x=>x.toPcode==printList.value[0].pcode).length>0){
    proxy.$modal.msgError("不允许选择原来的库位【"+printList.value[0].pcode+"】");
    return
  }
  let sumNum=0
  for(let i=0;i<switchData.value.length;i++){
    sumNum += Number(switchData.value[i].realQty)*1000
  }
  if(printList.value[0].realQty<sumNum/1000){
    proxy.$modal.msgError("移库数量不正确");
    return
  }
  let arr = JSON.parse(JSON.stringify(switchData.value))
  arr[0].toCangku = arr[0].toCangku[1]
  let submitData = {
    fromRkId:printList.value[0].id,
    moveReason:moveReason.value,
    targets:arr
  }
  moveHouse(submitData).then(response=>{
    if(response.code==200){
      proxy.$modal.msgSuccess("操作成功");
      //数据列表
      // getList();
      detailList()
      openSwitch.value = false
    }else{
      proxy.$modal.msgError("操作失败");
    }
    
  })
  // console.log(submitData)
}
function cancelMove(){
  openSwitch.value = false
}
//移库提交
// function submitSwitchData(){
//   proxy.$refs["switchRef"].validate(valid => {
//     if (valid){
//       // console.log(switchData.value)
//       let submitData = {}
//       submitData.rkId = switchData.value.id
//       submitData.entityId = switchData.value.entityId   //实物ID(身份码)
//       submitData.fromCangku = switchData.value.cangku   //原仓库
//       submitData.fromPcode = switchData.value.pcode   //原库位码(原存放位置)
//       submitData.fromTrayCode = switchData.value.trayCode   //原托盘码(原容器码)
//       submitData.toCangku = switchData.value.toCangku   //目标仓库
//       submitData.toPcode = switchData.value.toPcode   //目标库位码
//       submitData.toTrayCode = switchData.value.toTrayCode   //目标托盘码
//       submitData.moveReason = switchData.value.moveReason   //移库原因
//       moveHouse(submitData).then(response=>{
//         if(response.code==200){
//           proxy.$modal.msgSuccess("操作成功");
//           //数据列表
//           getList();
//           openSwitch.value = false
//         }else{
//           proxy.$modal.msgError("操作失败");
//         }
        
//       })
//     }
//   })
  
// }

/** 删除按钮操作 */
// function handleDelete(row) {
//   const _ids = row.id || ids.value;
//   proxy.$modal.confirm('是否确认删除库存单据主编号为"' + _ids + '"的数据项？').then(function() {
//     return delStock(_ids);
//   }).then(() => {
//     getList();
//     proxy.$modal.msgSuccess("删除成功");
//   }).catch(() => {});
// }

// 撤销入库
const handleStockDelete = (row) => {
  // dialogDelStock.value = true
  proxy.$modal.confirm('确定撤销吗？').then(function() {
    if(row.isChuku==0){
      let data = {
        id:row.id,
        realQty:row.realQty,
        gysJhId:row.gysJhId
      }
      return wisdomDelStock(data);
    }else if(row.isChuku==1){
      return ckDelStock(row.id)
    }
    
  }).then(() => {
    detailList()
    // getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});
}

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("操作失败");
        }
      })
    }
  })
}
const cancelDelStock = () => {
  dialogDelStock.value = false
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('wisdom/stock/export', {
    ...queryParams.value
  }, `stock_${new Date().getTime()}.xlsx`)
}
//打印单据
function handlePrint(){
  // if(printList.value.length==0){
  //   proxy.$modal.msgError("请勾选数据");
  //   return
  // }
  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(printList.value.length==0){
    proxy.$modal.msgError("请勾选数据");
    return
  }
  if(!printNum.value){
    proxy.$modal.msgError("请选择打印机编号");
    return
  }
  // let newArr = new Array();
  for(let i=0;i<printList.value.length;i++){
    printList.value[i].printer = printNum.value
  }

  printTag(printList.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()



const dialogBill = ref(false)
const billAllObj = ref([])
const billStatus = ref('')

</script>
<style>
.el-table .warning-row {
  --el-table-tr-background-color: var(--el-color-warning-lighter) !important;
}
.el-table .success-row {
  --el-table-tr-background-color: var(--el-color-success-lighter) !important;
}
</style>
<style scoped lang="scss">
:deep(.el-table .warning-row) {
  background-color: var(--el-color-warning-lighter) !important;
}
:deep(.el-table .success-row) {
  background-color: var(--el-color-success-lighter) !important;
}
.titleBox{
  text-align: center;
}
.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;
    }

</style>
