<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel" class="toolPanel">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <div class="toolTitle">库位管理</div>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:location:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:location:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:location:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleEnable"
            v-hasPermi="['system:location:edit']"
          >复位</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDisabled"
            v-hasPermi="['system:location:remove']"
          >占用</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleLockEnable"
            v-hasPermi="['system:location:edit']"
          >正常</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleLockDisable"
            v-hasPermi="['system:location:remove']"
          >禁用</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['system:location:import']"
          >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:location:export']"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-search" size="mini" @click="handleQuery"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >刷新</el-button
          >
        </el-col>
        <right-toolbar ref="toolBarRef" @customCols="customColsHandler" :showSearch.sync="showSearch"
                       showColumnsType="transfer" :columns="columns"></right-toolbar>
      </el-row>
    </div>
    <div class="search-container" ref="searchPanel">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="mini"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="库位编号" prop="locationId">
          <el-input
            v-model="queryParams.locationId"
            placeholder="请输入库位编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="助记码" prop="pyName">
                    <el-input
                        v-model="queryParams.pyName"
                        placeholder="请输入助记码"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item> -->
        <el-form-item label="仓库名称" prop="storageId">
          <el-select
            v-model="queryParams.storageId"
            placeholder="请选择仓库"
            clearable
          >
            <el-option
              v-for="dict in storageList"
              :key="dict.storageId"
              :label="dict.storageName"
              :value="dict.storageId"
            />
          </el-select>
        </el-form-item>
         <el-form-item label="禁用状态" prop="isLock">
            <el-select v-model="queryParams.isLock" placeholder="禁用状态" clearable>
              <el-option
                  v-for="dict in dict.type.common_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
         <!--         <el-form-item label="长" prop="locationLong">
                    <el-input
                        v-model="queryParams.locationLong"
                        placeholder="请输入长"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="宽" prop="locationWidth">
                    <el-input
                        v-model="queryParams.locationWidth"
                        placeholder="请输入宽"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="高" prop="locationHeight">
                    <el-input
                        v-model="queryParams.locationHeight"
                        placeholder="请输入高"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="容量" prop="volume">
                    <el-input
                        v-model="queryParams.volume"
                        placeholder="请输入容量"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="已占用容积" prop="hasVolume">
                    <el-input
                        v-model="queryParams.hasVolume"
                        placeholder="请输入已占用容积"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="承载重量" prop="bearWeight">
                    <el-input
                        v-model="queryParams.bearWeight"
                        placeholder="请输入承载重量"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="ABC分类" prop="abcId">
                    <el-input
                        v-model="queryParams.abcId"
                        placeholder="请输入ABC分类"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="排序" prop="sort">
                    <el-input
                        v-model="queryParams.sort"
                        placeholder="请输入排序"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item> -->
        <el-form-item label="占用状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.location_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="堆垛机编号" prop="decid">
                    <el-input
                        v-model="queryParams.decid"
                        placeholder="请输入堆垛机编号"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="入库站台" prop="instand">
                    <el-input
                        v-model="queryParams.instand"
                        placeholder="请输入入库站台"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="出库站台" prop="outstand">
                    <el-input
                        v-model="queryParams.outstand"
                        placeholder="请输入出库站台"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="入库输送线" prop="inLine">
                    <el-input
                        v-model="queryParams.inLine"
                        placeholder="请输入入库输送线"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="出库输送线" prop="outLine">
                    <el-input
                        v-model="queryParams.outLine"
                        placeholder="请输入出库输送线"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="行" prop="line">
                    <el-input
                        v-model="queryParams.line"
                        placeholder="请输入行"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="列" prop="cln">
                    <el-input
                        v-model="queryParams.cln"
                        placeholder="请输入列"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="层级" prop="layer">
                    <el-input
                        v-model="queryParams.layer"
                        placeholder="请输入层级"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="深度" prop="depth">
                    <el-input
                        v-model="queryParams.depth"
                        placeholder="请输入深度"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="入库站台" prop="instand1">
                    <el-input
                        v-model="queryParams.instand1"
                        placeholder="请输入入库站台"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="入库站台" prop="instand2">
                    <el-input
                        v-model="queryParams.instand2"
                        placeholder="请输入入库站台"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="出库站台" prop="outstand1">
                    <el-input
                        v-model="queryParams.outstand1"
                        placeholder="请输入出库站台"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="入库站台" prop="instand3">
                    <el-input
                        v-model="queryParams.instand3"
                        placeholder="请输入入库站台"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="出库站台" prop="outstand2">
                    <el-input
                        v-model="queryParams.outstand2"
                        placeholder="请输入出库站台"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="出库站台" prop="outstand3">
                    <el-input
                        v-model="queryParams.outstand3"
                        placeholder="请输入出库站台"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                  </el-form-item> -->
      </el-form>
    </div>

    <div class="table-container">
      <div ref="mainTablePanel" :style="{ height: mainTableDivHeight }">
        <el-table :key="rndKey" ref="providerTableRef" v-loading="loading" border size="mini" :height="mainTableHeight"
                  :data="locationList" @selection-change="handleSelectionChange" @header-dragend="handleHeaderDragEnd">
          <el-table-column type="selection" width="55" align="center" />
          <template>
            <el-table-column v-for="item in columns" :key="item.key" :label="item.label" align="center"
                             :prop="item.columnName" v-if="item.visible" :width="item.width" >

              <template v-slot="scope">
                <dict-tag
                  v-if="item.columnName === 'status'"
                  v-slot="scope"
                  :options="dict.type.location_type"
                  :value="scope.row[item.columnName]"
                />
                <dict-tag
                  v-else-if="item.columnName === 'isLock'"
                  v-slot="scope"
                  :options="dict.type.common_status"
                  :value="scope.row[item.columnName]"
                />
                <span v-else>{{ scope.row[item.columnName] }}</span>
              </template>
            </el-table-column>

          </template>
        </el-table>
        <div class="pagePanel">
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </div>
    </div>

    <!-- 添加或修改库位 对话框 -->
    <el-dialog
      id="dialog-container"
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <div class="edit-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="85px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="库位编号" prop="locationId">
                <el-input
                  v-model="form.locationId"
                  placeholder="请输入库位编号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库编号" prop="storageId">
                <el-select
                  v-model="form.storageId"
                  placeholder="请选择仓库"
                  clearable
                >
                  <el-option
                    v-for="dict in storageList"
                    :key="dict.storageId"
                    :label="dict.storageName"
                    :value="dict.storageId"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="助记码" prop="pyName">
                <el-input
                  v-model="form.pyName"
                  placeholder="请输入助记码"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="待收货库位" prop="fictitious">
                <el-checkbox v-model="form.fictitious" ></el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="禁用状态" prop="isLock">
                <el-select
                v-model="form.isLock"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.common_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 库位导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.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 text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的库位数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCOLUMN } from "@/api/system/column";
import {
  addLocation,
  changeStatus,
  delLocation,
  disabled,
  enabled,
  getLocation,
  listLocation,
  updateLocation,
} from "@/api/system/location";
import { listStorage } from "@/api/system/storage";
import { getToken } from "@/utils/auth";
export default {
  name: "Location",
  dicts: ["sys_yes_no", "location_type","common_status"],
  data() {
    return {
      rndKey:0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库位 表格数据
      locationList: [],
      //仓库集合
      storageList: [],
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "location",
      rightToolbarShow: false,
      tableNo: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        locationId: null,
        pyName: null,
        storageId: null,
        isLock: null,
        locationLong: null,
        locationWidth: null,
        locationHeight: null,
        volume: null,
        hasVolume: null,
        bearWeight: null,
        abcId: null,
        sort: null,
        status: null,
        decid: null,
        instand: null,
        outstand: null,
        inLine: null,
        outLine: null,
        line: null,
        cln: null,
        layer: null,
        depth: null,
        instand1: null,
        instand2: null,
        outstand1: null,
        instand3: null,
        outstand2: null,
        outstand3: null,
        selectIds:[]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        locationId: [
          { required: true, message: "库位编号不能为空", trigger: "blur" },
        ],
        storageId: [
          { required: true, message: "仓库不能为空", trigger: "blur" },
        ],
      },
      columns: [],
      // 托盘导入参数
      upload: {
        // 是否显示弹出层（库位导入）
        open: false,
        // 弹出层标题（库位导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的库位数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/location/importData",
      },
    };
  },
  created() {
    this.getList();
    this.getStorageList();
  },
  mounted() {
    this.computedTableHeight();
  },
  watch: {
    showSearch: function () {
      this.computedTableHeight();
    },
  },
  methods: {
    /** 查询用户展示字段定义管理列表 */
    handleHeaderDragEnd (newWidth, oldWidth, column, event) {
      // 当列宽发生变化时，将变化值写入到columns变量中。
      this.columns.map((obj) => {
        if (obj.columnName == column.property) obj.width = newWidth;
      });
      this.$refs.toolBarRef.saveConfig(this.columns);

    },
    customColsHandler (columns) {
      this.columns = columns;
      this.rndKey = Math.random();
    },

    computedTableHeight() {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel.clientHeight;

        var tablePanelHeight = totalHeight - toolHeight - searchHeight - 14 - 5;

        this.mainTableDivHeight = tablePanelHeight + "px";
        this.mainTableHeight = tablePanelHeight - 25 + "px";
      });
    },
    /** 查询库位 列表 */
    getList() {
      this.loading = true;
      listLocation(this.queryParams).then((response) => {
        this.locationList = response.rows;
        this.total = response.total;
        if (this.columns.length == 0) this.columns = response.columns;
        this.loading = false;
      });
    },
    /** 获取仓库列表 */
    getStorageList() {
      listStorage().then((response) => {
        this.storageList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        locationId: null,
        pyName: null,
        storageId: null,
        isLock: null,
        locationLong: null,
        locationWidth: null,
        locationHeight: null,
        volume: null,
        hasVolume: null,
        bearWeight: null,
        abcId: null,
        sort: null,
        status: "0",
        remark: null,
        version: null,
        decid: null,
        instand: null,
        outstand: null,
        inLine: null,
        outLine: null,
        line: null,
        cln: null,
        layer: null,
        depth: null,
        instand1: null,
        instand2: null,
        outstand1: null,
        instand3: null,
        outstand2: null,
        outstand3: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        fictitious: false
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.queryParams.selectIds=this.ids;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库位 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getLocation(id).then((response) => {

        this.form = response.data;
        this.form.fictitious = this.form.fictitious == "1"?true:false;
        this.open = true;
        this.title = "修改库位 ";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.fictitious = this.form.fictitious? "1":0;
          if (this.form.id != null) {
            updateLocation(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLocation(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除库位 编号为"' + ids + '"的数据项？')
        .then(function () {
          return delLocation(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 用户状态修改 */
    handleLockEnable(row) {
      let text = "0";
      const ids = row.id || this.ids;
      this.$modal
        .confirm('确认要恢复id为' + ids + '"数据项？')
        .then(function () {
          return changeStatus(ids, text);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("恢复成功");
        })
        .catch(function () {

        });
    },
     /** 用户状态修改 */
     handleLockDisable(row) {
      let text = "1";
      const ids = row.id || this.ids;
      this.$modal
        .confirm('确认要禁用id为'  + ids + '"数据项？')
        .then(function () {
          return changeStatus(ids, text);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("禁用成功");
        })
        .catch(function () {

        });
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认设置库位 编号为"' + ids + '"的数据项为空闲？')
        .then(function () {
          return enabled(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("设置空闲成功");
        })
        .catch(() => {});
    },
    /** 禁用按钮操作 */
    handleDisabled(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认冻结库位 编号为"' + ids + '"的数据项？')
        .then(function () {
          return disabled(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("冻结成功");
        })
        .catch(() => {});
    },



    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/location/export",
        {
          ...this.queryParams,
        },
        `location_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "库位导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/location/importTemplate",
        {},
        `location_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
}
</style>
