<template>
  <!--  -->
  <div class="app-container">
    <el-form
      :model="queryParams"
      size="mini"
      ref="queryParams"
      :inline="true"
      v-show="showSearch"
      label-width="70px">
      <el-form-item label="库位名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入库位名称"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item
        :class="['treeselectForm', { borderRed: !validTree }]"
        label="组织架构"
        prop="orgIds">
        <tree @treeselectFn="treeselectFn" :treeval="queryParams.orgIds" :ismultiple="true"></tree>
      </el-form-item>
      <el-form-item label="库位代码" prop="warehouseCode">
        <el-input
          v-model="queryParams.warehouseCode"
          placeholder="请输入库位代码"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="库位类型" prop="warehouseType">
        <el-select v-model="queryParams.warehouseType" placeholder="库位类型" clearable>
          <el-option
            v-for="dict in wlwarehouseType"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="库位级别" prop="inventoryLeavel">
        <el-select v-model="queryParams.inventoryLeavel" placeholder="库位级别" clearable>
          <el-option
            v-for="dict in dict.type.material_level_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
            <p style="margin: 0" @click="inventoryLeavelFn">{{ dict.label }}</p>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物料类型" prop="materialTypeName">
        <el-select
          v-model="queryParams.materialTypeName"
          size="mini"
          clearable
          filterable
          @change="materialTypeChangeQuery">
          <el-option
            v-for="item in materialTypeOption"
            :key="item.signType"
            :label="item.signType"
            :value="item.signType" />
        </el-select>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialDataName">
        <el-select
          v-model="queryParams.materialDataName"
          size="mini"
          clearable
          filterable
          @change="onInput()">
          <el-option
            v-for="item in materialNameOptionQuery"
            :key="item.signName"
            :label="item.signName"
            :value="item.signName" />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="物料种类" prop="materialTypeName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.materialTypeName"-->
      <!--          placeholder="请输入物料种类"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="物料名称" prop="materialDataName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.materialDataName"-->
      <!--          placeholder="请输入物料名称"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="listRresetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-alert title="不支持销售员库存的调拨和调整" type="warning" :closable="false" show-icon>
    </el-alert>
    <br />
    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sfa:materialInventory:add']"
          >新增</el-button
        >
      </el-col>-->
      <el-col :span="3" class="drfbrw">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="addBatchImport"
          v-hasPermi="['sfa:materialInventory:batchImport']"
          >批量分发
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
       <el-button
         type="success"
         plain
         icon="el-icon-edit"
         size="mini"
         :disabled="single"
         @click="handleUpdate"
         v-hasPermi="['sfa:materialInventory:edit']"
       >修改</el-button>
     </el-col>
     <el-col :span="1.5">
       <el-button
         type="danger"
         plain
         icon="el-icon-delete"
         size="mini"
         :disabled="multiple"
         @click="handleDelete"
         v-hasPermi="['sfa:materialInventory:remove']"
       >删除</el-button>
     </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['sfa:materialInventory:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialInventoryList">
      <el-table-column label="库位类型" align="center" prop="warehouseType">
        <template slot-scope="scope">
          <dicts-tag :options="wlwarehouseType" :value="scope.row.warehouseType" />
        </template>
      </el-table-column>
      <el-table-column
        label="库位名称"
        prop="warehouseName"
        width="180"
        :show-overflow-tooltip="true" />
      <el-table-column label="库位代码" prop="warehouseCode" />
      <el-table-column label="库位层次" prop="inventoryLeavel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_level_type" :value="scope.row.inventoryLeavel" />
        </template>
      </el-table-column>
      <el-table-column label="物料类型" prop="materialTypeName" />
      <el-table-column label="物料名称" prop="materialDataName" :show-overflow-tooltip="true" />
      <el-table-column label="物料编码" prop="materialDataCode" width="130" />
      <!--      <el-table-column label="实时库存" align="center" prop="inventoryNum" />-->
      <el-table-column label="实时库存" align="center" width="80" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="linkks" @click="inventoryLogDataFn(scope.row.inventoryId)">{{
            scope.row.inventoryNum
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公司" prop="inventoryGsDeptName" :show-overflow-tooltip="true" />
      <el-table-column label="大区" prop="inventoryDqDeptName" :show-overflow-tooltip="true" />
      <el-table-column label="销售部" prop="inventoryMdDeptName" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-position"
            @click="handleUpdateGrant(scope.row)"
            v-hasPermi="['sfa:materialInventory:grant']"
            >发放</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateAllot(scope.row)"
            v-hasPermi="['sfa:materialInventory:adjust']"
            >调整</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-sort"
            @click="handleUpdateAllots(scope.row)"
            v-hasPermi="['sfa:materialInventory:allocate']"
            >调拨</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body>
      <el-form
        :model="queryParamsRw"
        size="mini"
        ref="queryParamsRw"
        :inline="true"
        v-show="showSearch"
        label-width="120px">
        <el-form-item label="操作人库位" prop="changeWarehouseName">
          <el-input
            v-model="queryParamsRw.changeWarehouseName"
            placeholder="请输入操作人库位"
            clearable
            size="small"
            @keyup.enter.native="handleQueryRw" />
        </el-form-item>
        <el-form-item label="变更类型" prop="changeType">
          <el-select
            v-model="queryParamsRw.changeType"
            placeholder="变更类型"
            clearable
            style="width: 240px">
            <el-option
              v-for="dict in dict.type.material_change_log_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryRw"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="listRresetQueryRw">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loadingRW" :data="materialInventoryLogList">
        <el-table-column label="操作人库位名称" align="center" prop="changeWarehouseName" />
        <el-table-column label="操作人库位代码" align="center" prop="changeWarehouseCode" />
        <!--        <el-table-column label="操作人库位层次" align="center" prop="inventoryLeavel">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.material_level_type" :value="scope.row.inventoryLeavel"/>
                  </template>
                </el-table-column>-->
        <el-table-column label="库存变更量" align="center" prop="inventoryNum" />
        <el-table-column label="变更类型" align="center" prop="changeType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.material_change_log_type" :value="scope.row.changeType" />
          </template>
        </el-table-column>
        <el-table-column label="变更时间" align="center" prop="createTime" />
        <!--        <el-table-column label="公司" align="center" prop="inventoryGsDeptName" />
                <el-table-column label="大区" align="center" prop="inventoryDqDeptName" />
                <el-table-column label="销售部" align="center" prop="inventoryMdDeptName" />-->
      </el-table>
      <pagination
        v-show="totalRw > 0"
        :total="totalRw"
        :page.sync="queryParamsRw.pageNum"
        :limit.sync="queryParamsRw.pageSize"
        @pagination="getMaterialInventoryLogData" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openAdd" width="60%" append-to-body>
      <el-form ref="formAd" :model="formAd" size="mini" :rules="rulesAd" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item
              :class="['treeselectForm', { borderRed: !validTree }]"
              label="组织架构"
              prop="deptId">
              <treeselect
                class="treePopup"
                v-model="formAd.deptId"
                :multiple="false"
                value-consists-of="LEAF_PRIORITY"
                :options="menuOptions"
                :normalizer="normalizer1"
                placeholder="选择组织架构"
                noOptionsText="暂无数据"
                :show-count="true"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料类型" prop="materialTypeName">
              <el-select
                v-model="formAd.materialTypeName"
                size="small"
                clearable
                filterable
                @change="materialTypeChangeQuery"
                style="width: 100%">
                <el-option
                  v-for="item in materialTypeOption"
                  :key="item.signType"
                  :label="item.signType"
                  :value="item.signType" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialDataId">
              <el-select
                v-model="formAd.materialDataId"
                size="small"
                clearable
                filterable
                @change="onInput()"
                style="width: 100%">
                <el-option
                  v-for="item in materialNameOptionQuery"
                  :key="item.id"
                  :label="item.signName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调拨数量" prop="inventoryNum">
              <el-input-number
                v-model="formAd.inventoryNum"
                controls-position="right"
                :min="1"
                @input="onInput"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAd">确 定</el-button>
        <el-button @click="cancelAd">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 盘点/调拨 -->
    <el-dialog
      :title="title"
      :visible.sync="openAllot"
      @close="dialogClose"
      width="60%"
      append-to-body>
      <el-form ref="formAllot" :model="formAllot" :rules="rulesAllot" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="组织架构" prop="warehouseName" size="mini">
              <el-input v-model="formAllot.warehouseName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位类型" prop="warehouseName" style="height: 32px" size="mini">
              <dicts-tag :options="wlwarehouseType" :value="formAllot.warehouseType" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料类型名称" prop="materialTypeName" size="mini">
              <el-input v-model="formAllot.materialTypeName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialDataName" size="mini">
              <el-input v-model="formAllot.materialDataName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变更类型" prop="changeType" size="mini">
              <el-select
                disabled
                v-model="formAllot.changeType"
                clearable
                placeholder="请选择变更类型"
                style="width: 100%"
                @change="onInput">
                <el-option
                  v-for="item in changeTypeOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="inventoryNumss" size="mini" style="height: 32px">
              <el-input
                disabled
                v-model="formAllot.inventoryNumss"
                placeholder="库存"
                @input="onInput" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              :label="inventoryNumLabel"
              prop="inventoryNum"
              v-if="formAllot.changeType == 3 || formAllot.changeType == 4"
              size="mini">
              <el-input-number
                v-model="formAllot.inventoryNum"
                controls-position="right"
                :min="1"
                @input="onInput"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formAllot.changeType == 3">
            <el-form-item label="调拨库" prop="followInventoryNames" size="mini">
              <div @click="followOpen">
                <el-input
                  v-model="formAllot.followInventoryNames"
                  placeholder="请输入调拨库"
                  @input="onInput" />
              </div>
            </el-form-item>
          </el-col>
          <template v-if="formAllot.changeType == 6">
            <el-col :span="12">
              <el-form-item label="分发类型" prop="grantType" size="mini">
                <el-select
                  v-model="formAllot.grantType"
                  placeholder="请选择分发类型"
                  style="width: 100%"
                  @change="changeGrantType">
                  <el-option
                    v-for="item in dictDataList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <div style="float: left; width: 100%">
              <el-col :span="12">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="addDistribute"
                  >添加</el-button
                >
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="batchAll"
                  :disabled="!selectData.length"
                  >批量删除</el-button
                >
              </el-col>
              <el-col :span="12" style="text-align: right">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-upload2"
                  size="mini"
                  @click="addStoreImport"
                  >导入分发信息</el-button
                >
              </el-col>
            </div>
          </template>
        </el-row>
      </el-form>
      <!-- 添加后的数据列表 -->
      <addTable
        v-if="tableData.length"
        :tableData="tableData"
        @deleteTableData="deleteTableData"
        @selectChange="selectChange" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitFormAllot">确 定</el-button>
        <el-button size="mini" @click="cancelAllot">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openAbet" width="90%" append-to-body>
      <el-form
        :model="queryParamsAbet"
        ref="queryParamsAbet"
        :inline="true"
        v-show="showSearch"
        label-width="120px">
        <el-form-item label="库位名称" prop="deptName" size="mini">
          <el-input
            v-model="queryParamsAbet.deptName"
            placeholder="请输入库位名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item
          :class="['treeselectForm', { borderRed: !validTree }]"
          label="组织架构"
          prop="orgIds">
          <tree
            @treeselectFn="treeselectFnAbet"
            :treeval="queryParamsAbet.orgIds"
            :ismultiple="true"></tree>
        </el-form-item>
        <el-form-item label="库位代码" prop="deptCode" size="mini">
          <el-input
            v-model="queryParamsAbet.deptCode"
            placeholder="请输入库位代码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="库位级别" prop="deptLevel" size="mini">
          <el-select
            v-model="queryParamsAbet.deptLevel"
            placeholder="库位级别"
            clearable
            style="width: 240px">
            <el-option
              v-for="dict in dict.type.material_level_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryAbet"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="listRresetQueryAbet"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="materialInventoryListAbet">
        <el-table-column label="库位名称" align="center" prop="deptName" />
        <el-table-column label="库位代码" align="center" prop="deptCode" />
        <el-table-column label="库位层次" align="center" prop="deptLevel">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.material_level_type" :value="scope.row.deptLevel" />
          </template>
        </el-table-column>

        <!--        <el-table-column label="物料类型" align="center" prop="signType" />-->
        <!--        <el-table-column label="物料名称" align="center" prop="signName" />-->
        <el-table-column label="公司" align="center" prop="inventoryGsDeptName" />
        <el-table-column label="大区" align="center" prop="inventoryDqDeptName" />
        <el-table-column label="销售部" align="center" prop="inventoryMdDeptName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdateAllotlist(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="totalAbet > 0"
        :total="totalAbet"
        :page.sync="queryParamsAbet.pageNum"
        :limit.sync="queryParamsAbet.pageSize"
        @pagination="getListAbet" />
      <!--      <div slot="footer" class="dialog-footer">-->
      <!--        <el-button type="primary" @click="submitFormAllot">确 定</el-button>-->
      <!--        <el-button @click="openAbet=false">关 闭</el-button>-->
      <!--      </div>-->
    </el-dialog>

    <!-- 上传发布任务 -->
    <el-dialog
      class="upload"
      :title="upload2.title"
      :visible.sync="upload2.open"
      width="400px"
      append-to-body>
      <div style="margin-bottom: 14px">
        <el-link type="primary" style="font-size: 14px" @click="importTemplate">下载模板</el-link>
      </div>
      <el-upload
        ref="upload2"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload2.headers"
        :action="upload2.url + upload2.urlParams"
        :disabled="upload2.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :disabled="upload2.isUploading"
          >确 定</el-button
        >
        <el-button @click="upload2.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加分发任务 dialog -->
    <distributeModel
      v-if="distributeFlag"
      :grantType="formAllot.grantType"
      :warehouseCode="activeRow ? activeRow.warehouseCode : ''"
      :warehouseType="activeRow ? activeRow.warehouseType : ''"
      @closeDistribute="closeDistribute"
      @addSuccess="addSuccess"
      :tableData="tableData" />

    <!--任务列表数据导入-->
    <el-dialog :title="upload3.title" :visible.sync="upload3.open" width="400px" append-to-body>
      <div class="batchImportSelectBox">
        <div class="label">组织架构</div>
        <treeselect
          class="treePopup"
          v-model="batchImportDeptCode"
          :multiple="false"
          value-consists-of="LEAF_PRIORITY"
          :options="menuOptions"
          :normalizer="normalizer2"
          placeholder="选择组织架构"
          noOptionsText="暂无数据"
          :show-count="true" />
      </div>
      <el-upload
        ref="upload3"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload3.headers"
        :action="upload3.url + upload3.urlParams"
        :disabled="upload3.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess3"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplateBatch"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm3">确 定</el-button>
        <el-button @click="upload3.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tree from '@/views/components/sfa/treeselectParentNo';
import treeSingle from '@/views/components/sfa/treeselectSingle';
import user from '@/views/components/sfa/user';
import {
  listMaterialInventory,
  getMaterialInventory,
  delMaterialInventory,
  addMaterialInventory,
  updateMaterialInventory,
} from '@/api/sfa/materialInventory';
import {
  listMaterialInventoryLog,
  getMaterialInventoryLog,
  addMaterialInventoryLog,
  updateMaterialInventoryLog,
  delMaterialInventoryLog,
} from '@/api/sfa/materialInventoryLog';
import { listDictype } from '@/api/sfa/dictype';
import {
  adjustList,
  justList,
  materialInventory,
  updateChange,
  importTemplate,
  addGrantMaterialInventory,
} from '@/api/sfa/allotInventory';
import { listDept } from '@/api/system/dept';
import Treeselect from '@riophae/vue-treeselect';
import { importData } from '@/api/sfa/taskuser';
import { getToken } from '@/utils/auth';
import distributeModel from './distribute.vue';
import addTable from './addTable.vue';
import { Message } from 'element-ui';
export default {
  name: 'MaterialInventory',
  components: { treeSingle, user, tree, Treeselect, distributeModel, addTable },
  dicts: [
    'material_level_type',
    'material_change_type',
    'material_change_log_type',
    'material_change_type',
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      openAdd: false,
      //遮罩层（变更记录）
      loadingRW: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //总条数（变更记录）
      totalRw: 0,
      totalAbet: 0,
      // 物料库存表格数据
      materialInventoryList: [],
      materialTypeOption: [],
      materialNameOptionQuery: [],
      // 物料库存变更表格数据
      materialInventoryLogList: [],
      materialInventoryListAbet: [],
      changeTypeOptions: [],
      wlwarehouseType: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openAllot: false,
      inventoryNumLabel: '',
      openAbet: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inventoryGsDeptId: null,
        inventoryGsDeptName: null,
        inventoryDqDeptId: null,
        inventoryDqDeptName: null,
        inventoryMdDeptId: null,
        inventoryMdDeptName: null,
        materialTypeId: null,
        materialTypeName: null,
        materialDataId: null,
        materialDataName: null,
        inventoryNum: null,
        inventoryLeavel: null,
        status: null,
        orgIds: null,
        warehouseName: null,
        warehouseCode: null,
        inventoryLyUserId: null,
        inventoryLyUserName: null,
      },
      // 查询参数（变更记录）
      queryParamsRw: {
        pageNum: 1,
        pageSize: 10,
        materialInventoryId: null,
        changeWarehouseName: null,
        changeWarehouseCode: null,
        changeType: null,
      },
      queryParamsAbet: {
        pageNum: 1,
        pageSize: 10,
        deptCodeTwo: null,
        materialDataId: null,
        orgIds: null,
        deptName: null,
        deptCode: null,
        deptLevel: null,
      },
      validTree: true,
      // 表单参数
      form: {},
      formAllot: {},
      formAd: {},
      // 表单校验
      rulesAllot: {
        followInventoryNames: [{ required: true, message: '请输入调拨库', trigger: 'change' }],
        inventoryNum: [{ required: true, message: '请输入数量', trigger: 'blur' }],
      },
      rules: {},
      rulesAd: {
        deptId: [{ required: true, message: '请选择组织机构', trigger: 'change' }],
        materialDataId: [{ required: true, message: '请选择物料', trigger: 'change' }],
        inventoryNum: [{ required: true, message: '请输入数量', trigger: 'blur' }],
      },
      menuOptions: [],
      dictDataList: [], //分发类型option
      upload2: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + 'sfa/materialInventory/importData',
        loadProgress: 10,
        urlParams: '',
      },
      upload3: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + 'sfa/materialInventory/batchImportData',
        urlParams: '',
      },
      distributeFlag: false, //添加发布任务弹框状态
      activeRow: null, //当前选中数据
      tableData: [],
      selectData: [], // 添加的数据table select选择的数据
      batchImportDeptCode: null, //物料分发批量导入组织架构code
    };
  },
  created() {
    this.getDicts('material_change_type').then((response) => {
      this.changeTypeOptions = response.data;
    });
    this.getDicts('wl_warehouse_type').then((response) => {
      this.wlwarehouseType = response.data;
    });
    this.getList();
    this.getMaterialTypeOption();
    this.getTreeselect();
  },
  methods: {
    inventoryLeavelFn(val) {
      setTimeout(() => {
        if (this.queryParams.inventoryLeavel == 0) {
          this.queryParams.orgIds = undefined;
        }
      });
    },
    getTreeselect() {
      listDept().then((response) => {
        this.menuOptions = this.handleTree(response.data, 'deptId', 'parentId');
        if (
          this.menuOptions.length == 1 &&
          (this.menuOptions[0].children == null ||
            this.menuOptions[0].children == undefined ||
            (this.menuOptions[0].children != undefined &&
              this.menuOptions[0].children != null &&
              this.menuOptions[0].children.length == 0))
        ) {
          this.form.orgId = this.menuOptions[0].deptId;
        }
      });
    },
    normalizer1(node) {
      let that = this;
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
        isDisabled: that.isDisabled,
      };
    },
    normalizer2(node) {
      let that = this;
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptCode,
        label: node.deptName,
        children: node.children,
        isDisabled: that.isDisabled,
      };
    },
    materialTypeChangeQuery(val) {
      this.queryParams.materialName = '';
      if (val != '' && val != null) {
        let pid;
        this.materialTypeOption.forEach((item) => {
          if (item.signType == val) {
            pid = item.id;
            let obj = {
              type: 1,
              pid,
            };
            this.getMaterialNameOption(obj, 'materialNameOptionQuery');
          }
        });
      } else {
        this.materialNameOptionQuery = [];
      }
      this.$forceUpdate();
    },
    getMaterialTypeOption() {
      let obj = {
        type: 0,
      };
      this.getMaterialNameOption(obj, 'materialTypeOption');
    },
    onInput() {
      this.$forceUpdate();
    },
    getMaterialNameOption(obj, str) {
      let that = this;
      listDictype(obj).then((response) => {
        if (str == 'materialNameOptionAll') {
          that.materialNameOptionAll = response.rows;
        } else if (str == 'materialTypeOption') {
          that.materialTypeOption = response.rows;
        } else if (str == 'materialNameOption') {
          that.materialNameOption = response.rows;
        } else if (str == 'materialNameOptionQuery') {
          that.materialNameOptionQuery = response.rows;
        }
      });
    },
    /** 查询物料库存列表 */
    getList() {
      this.loading = true;
      justList(this.queryParams).then((response) => {
        this.materialInventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getListAbet() {
      this.loading = true;
      this.queryParamsAbet.warehouseType = this.formAllot.warehouseType;
      adjustList(this.queryParamsAbet).then((response) => {
        this.materialInventoryListAbet = response.rows;
        this.totalAbet = response.total;
        this.loading = false;
      });
    },
    /** 查询物料变更记录列表 */
    getListRw() {
      this.loadingRW = true;
      listMaterialInventoryLog(this.queryParamsRw).then((response) => {
        this.materialInventoryLogList = response.rows;
        this.totalRw = response.total;
        this.loadingRW = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelAd() {
      this.openAdd = false;
      this.reset();
    },
    cancelAllot() {
      this.openAllot = false;
      this.resetAllot();
    },
    // Dialog 关闭的回调
    dialogClose() {
      this.tableData = [];
    },
    resetAllot() {
      this.formAllot = {
        inventoryId: null,
        inventoryGsDeptId: null,
        inventoryGsDeptName: null,
        inventoryDqDeptId: null,
        inventoryDqDeptName: null,
        inventoryMdDeptId: null,
        inventoryMdDeptName: null,
        materialTypeId: null,
        materialTypeName: null,
        materialDataId: null,
        materialDataName: null,
        inventoryNum: null,
        followInventoryId: null,
        followInventoryName: null,
        inventoryLeavel: null,
        status: '0',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        warehouseName: null,
        warehouseCode: null,
        inventoryLyUserId: null,
        inventoryLyUserName: null,
      };
      this.resetForm('formAllot');
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryId: null,
        inventoryGsDeptId: null,
        inventoryGsDeptName: null,
        inventoryDqDeptId: null,
        inventoryDqDeptName: null,
        inventoryMdDeptId: null,
        inventoryMdDeptName: null,
        materialTypeId: null,
        materialTypeName: null,
        materialDataId: null,
        materialDataName: null,
        inventoryNum: null,
        inventoryLeavel: null,
        status: '0',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        warehouseName: null,
        warehouseCode: null,
        inventoryLyUserId: null,
        inventoryLyUserName: null,
      };
      this.resetForm('form');
    },
    resetAd() {
      this.formAd = {
        inventoryId: null,
        inventoryGsDeptId: null,
        inventoryGsDeptName: null,
        inventoryDqDeptId: null,
        inventoryDqDeptName: null,
        inventoryMdDeptId: null,
        inventoryMdDeptName: null,
        materialTypeId: null,
        materialTypeName: null,
        materialDataId: null,
        materialDataName: null,
        inventoryNum: null,
        inventoryLeavel: null,
        status: '0',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        warehouseName: null,
        warehouseCode: null,
        inventoryLyUserId: null,
        inventoryLyUserName: null,
      };
      this.resetForm('formAd');
    },
    // 变更记录表单重置
    resetRw() {
      this.form = {
        materialInventoryId: null,
        status: '0',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        changeWarehouseName: null,
        changeWarehouseCode: null,
        changeType: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 变更记录搜索按钮操作 */
    handleQueryRw() {
      this.queryParamsRw.pageNum = 1;
      this.getListRw();
    },
    handleQueryAbet() {
      this.queryParamsAbet.pageNum = 1;
      this.getListAbet();
    },
    handleUpdateAllotlist(row) {
      this.formAllot.warehouseCodeThree = row.deptCode;
      this.formAllot.followInventoryNames = row.deptName;
      this.openAbet = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    followOpen() {
      this.openAbet = true;
      this.listRresetQueryAbet();
    },
    listRresetQueryAbet() {
      this.queryParamsAbet = {
        pageNum: 1,
        pageSize: 10,
        deptCodeTwo: null,
        materialDataId: null,
        orgIds: null,
        deptName: null,
        deptCode: null,
        deptLevel: null,
      };
      this.queryParamsAbet.warehouseCodeTwo = this.formAllot.warehouseCode;
      this.queryParamsAbet.materialDataId = this.formAllot.materialDataId;
      this.handleQueryAbet();
    },
    // 库存重置
    listRresetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orgIds: null,
        warehouseCode: '',
        inventoryLeavel: '',
        materialTypeName: '',
        materialDataName: '',
      };
      this.handleQuery();
    },
    // 变更记录重置
    listRresetQueryRw() {
      this.queryParamsRw.pageNum = 1;
      this.queryParamsRw.pageSize = 10;
      this.queryParamsRw.changeType = '';
      this.queryParamsRw.changeWarehouseName = '';
      this.queryParamsRw.changeWarehouseCode = '';
      this.handleQueryRw();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.inventoryId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetAd();
      this.openAdd = true;
      this.title = '添加物料库存';
    },
    handleUpdateGrant(row) {
      this.resetAllot();
      this.tableData = [];
      const inventoryId = row.inventoryId || this.ids;
      getMaterialInventory(inventoryId).then((response) => {
        response.data.followInventoryNames = '';
        response.data.inventoryNumss = response.data.inventoryNum;
        this.formAllot = response.data;
        this.formAllot.changeType = '6';
        this.formAllot.inventoryNum = '';
        this.openAllot = true;
        this.dictDataList = response.data.dictDataList;
        // 分发类型 默认选择第一个
        this.formAllot.grantType = this.dictDataList.length ? this.dictDataList[0].dictValue : '';
        // 当前选中数据
        this.activeRow = row;
        // 上传附件参数
        this.upload2.urlParams = `?grantType=${this.formAllot.grantType}&warehouseCode=${
          this.activeRow ? this.activeRow.warehouseCode : ''
        }&warehouseType=${this.activeRow ? this.activeRow.warehouseType : ''}`;
        this.title = '物料发放';
      });
    },
    handleUpdateAllot(row) {
      this.resetAllot();
      const inventoryId = row.inventoryId || this.ids;
      getMaterialInventory(inventoryId).then((response) => {
        response.data.followInventoryNames = '';
        response.data.inventoryNumss = response.data.inventoryNum;
        response.data.inventoryNum = '';
        this.formAllot = response.data;
        this.formAllot.changeType = '4';
        this.formAllot.followInventoryNames = '';
        this.formAllot.inventoryNum = '';
        this.openAllot = true;
        this.title = '物料调整';
        this.inventoryNumLabel = '调整数量';
      });
    },
    handleUpdateAllots(row) {
      this.resetAllot();
      const inventoryId = row.inventoryId || this.ids;
      getMaterialInventory(inventoryId).then((response) => {
        response.data.followInventoryNames = '';
        response.data.inventoryNumss = response.data.inventoryNum;
        this.formAllot = response.data;
        this.formAllot.changeType = '3';
        this.formAllot.inventoryNum = '';
        this.openAllot = true;
        this.title = '物料调拨';
        this.inventoryNumLabel = '调拨数量';
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inventoryId = row.inventoryId || this.ids;
      getMaterialInventory(inventoryId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = '修改物料库存';
      });
    },
    /** 提交按钮 */
    submitFormAd() {
      this.$refs['formAd'].validate((valid) => {
        if (valid) {
          materialInventory(this.formAd).then((response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess('操作成功');
              this.openAdd = false;
              this.getList();
            }
          });
        }
      });
    },
    submitFormAllot() {
      if (this.title == '物料发放') {
        if (!this.tableData.length) {
          Message.warning('请添加发放部门或销售员');
          return;
        } else {
          this.submitFaFang();
        }
      } else {
        this.$refs['formAllot'].validate((valid) => {
          if (valid) {
            updateChange(this.formAllot).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess('操作成功');
                this.openAllot = false;
                this.getList();
              }
            });
          }
        });
      }
    },
    // 发放提交
    submitFaFang() {
      let paramsData = [];
      this.tableData.forEach((val) => {
        if (val.grantNum) {
          paramsData.push({
            grantCode: val.receiveCode,
            grantName: val.receiveName,
            grantNum: val.grantNum,
          });
        }
      });
      if (paramsData.length == this.tableData.length) {
        addGrantMaterialInventory({
          inventoryGrantVos: paramsData,
          inventoryId: this.activeRow.inventoryId,
          grantType: this.formAllot.grantType,
        }).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess('操作成功');
            this.openAllot = false;
            this.getList();
          }
        });
      } else {
        Message.warning('请输入发放数量');
      }
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.inventoryId != null) {
            updateMaterialInventory(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addMaterialInventory(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryIds = row.inventoryId || this.ids;
      this.$modal
        .confirm('是否确认删除物料库存编号为"' + inventoryIds + '"的数据项？')
        .then(function () {
          return delMaterialInventory(inventoryIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'sfa/materialInventory/export',
        {
          ...this.queryParams,
        },
        `materialInventory_${new Date().getTime()}.xlsx`
      );
    },
    treeselectFn(val) {
      this.queryParams.orgIds = val;
      if (this.queryParams.inventoryLeavel == 0 && this.queryParams.orgIds.length > 0) {
        this.queryParams.inventoryLeavel = '';
      }
      this.$forceUpdate();
    },
    treeselectFnAbet(val) {
      this.queryParamsAbet.orgIds = val;
    },
    inventoryLogDataFn(id) {
      this.queryParamsRw.materialInventoryId = id;
      this.queryParamsRw.pageNum = 1;
      this.queryParamsRw.changeType = '';
      this.queryParamsRw.changeWarehouseName = '';
      this.queryParamsRw.changeWarehouseCode = '';
      this.getMaterialInventoryLogData();
    },
    //变更记录点击事件
    getMaterialInventoryLogData() {
      this.loadingRW = true;
      listMaterialInventoryLog(this.queryParamsRw).then((response) => {
        this.materialInventoryLogList = response.rows;
        this.loadingRW = false;
        this.totalRw = response.total;
        this.open = true;
        this.title = '库存变更记录';
      });
    },
    // 分发类型select change
    changeGrantType(value) {
      this.tableData = [];
      // 上传附件参数
      this.upload2.urlParams = `?grantType=${value}&warehouseCode=${
        this.activeRow ? this.activeRow.warehouseCode : ''
      }&warehouseType=${this.activeRow ? this.activeRow.warehouseType : ''}`;
    },
    // 添加下发单位
    addDistribute() {
      this.distributeFlag = true;
    },
    // 导入发布任务
    addStoreImport() {
      this.upload2.title = '物料分发导入';
      this.upload2.open = true;
    },
    // 分发批量导入
    addBatchImport() {
      this.batchImportDeptCode = null;
      this.upload3.title = '物料分发批量导入';
      this.upload3.open = true;
    },
    // 下载导入模板
    importTemplateBatch() {
      let url = process.env.VUE_APP_Target + '/profile/upload/template/批量分发导入模版.xlsx';
      window.open(url, '_blank');
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload2.isUploading = true;
      this.upladLoading = this.$loading({
        lock: true,
        text: '拼命上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload2.open = false;
      this.upload2.isUploading = false;
      this.upladLoading.close();
      this.$refs.upload2.clearFiles();
      if (response.code == 200) {
        let paramsData = [];
        response.data.forEach((val) => {
          if (val.grantNum) {
            paramsData.push({
              receiveCode: val.grantCode,
              receiveName: val.grantName,
              grantNum: val.grantNum,
            });
          }
        });
        this.tableData = paramsData;
        Message.success('导入成功');
      } else {
        this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true });
      }
      // this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload2.submit();
    },
    // 下载模板
    importTemplate() {
      this.download(
        'sfa/materialInventory/importTemplate',
        {
          grantType: this.formAllot.grantType,
        },
        `物料分发.xlsx`
      );
    },
    // 关闭弹框
    closeDistribute() {
      this.distributeFlag = false;
    },
    // 添加成功回调
    addSuccess(list) {
      this.tableData = list;
      this.distributeFlag = false;
    },
    // 选中的数据
    selectChange(list) {
      this.selectData = list;
    },
    // 删除选中的数据 单个删除
    deleteTableData(receiveCode) {
      let ind = null;
      let count = 0;
      this.tableData.forEach((val, ind) => {
        count++;
        if (val.receiveCode == receiveCode) {
          ind = ind;
        }
        // 执行结束
        if (count === this.tableData.length) {
          if (ind != null) {
            this.tableData.splice(ind, 1);
          }
        }
      });
    },
    // 批量删除
    batchAll() {
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const listCode = this.selectData.map((item) => item.receiveCode);
        this.tableData = this.tableData.filter((item) => !listCode.includes(item.receiveCode));
        this.$forceUpdate();
      });
    },
    handleFileSuccess3(response) {
      this.upladLoading.close();
      this.$refs.upload3.clearFiles();
      if (response.code == 200) {
        Message.success('导入成功');
      } else {
        this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true });
      }
    },
    // 物料分发批量导入
    submitFileForm3() {
      // 上传附件参数
      if (!this.batchImportDeptCode) {
        Message.warning('请选择组织结构');
        return;
      }
      this.$set(this.upload3, 'urlParams', `?deptCode=${this.batchImportDeptCode}`);
      this.$nextTick(() => {
        this.$refs.upload3.submit();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.batchImportSelectBox {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .label {
    width: 66px;
    &::before {
      content: '*';
      color: red;
    }
  }
  .treePopup {
    flex: 1;
  }
}
</style>
