<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:storage: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:storage: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:storage: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:storage: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:storage:remove']"
            >禁用</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:storage: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="factoryId">-->
<!--          <el-input-->
<!--            v-model="queryParams.factoryId"-->
<!--            placeholder="请输入厂区"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="所属部门" prop="deptId">-->
<!--          <el-input-->
<!--            v-model="queryParams.deptId"-->
<!--            placeholder="请输入所属部门"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="仓库编号" prop="storageId">
          <!-- <el-input
            v-model="queryParams.storageId"
            placeholder="请输入仓库编号"
            clearable
            @keyup.enter.native="handleQuery"
          /> -->
          <el-select
            v-model="queryParams.storageId"
            placeholder="请选择仓库编号"
          >
           <!-- 手动添加第一个“请选择”选项 -->
          <el-option label="请选择" :value="null" />
          <el-option
              v-for="(item, index) in storageList"
              :key="index"
              :label="item.storageId"
              :value="item.storageId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="storageName">
          <!-- <el-input
            v-model="queryParams.storageName"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter.native="handleQuery"
          /> -->

          <el-select
            v-model="queryParams.storageName"
            placeholder="请选择仓库名称"
          >
           <!-- 手动添加第一个“请选择”选项 -->
          <el-option label="请选择" :value="null" />
          <el-option
              v-for="(item, index) in storageList"
              :key="index"
              :label="item.storageName"
              :value="item.storageName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="storageShortName">
          <!-- <el-input
            v-model="queryParams.storageShortName"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter.native="handleQuery"
          /> -->
          <el-select
            v-model="queryParams.storageShortName"
            placeholder="请选择仓库名称"
          >
           <!-- 手动添加第一个“请选择”选项 -->
          <el-option label="请选择" :value="null" />
          <el-option
               v-for="(item, index) in storageList"
              :key="index"
              :label="item.storageShortName"
              :value="item.storageShortName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库类型" prop="type">
          <el-select
            v-model="queryParams.type"
            placeholder="请选仓库类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.storage_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="agv库" prop="isAgv">
          <el-select
            v-model="queryParams.isAgv"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in dict.type.common_zero_or_one"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </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="storageList" @selection-change="handleSelectionChange" @header-dragend="handleHeaderDragEnd">
          <el-table-column type="selection" width="55" align="center" />

            <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.common_status" :value="scope.row[item.columnName]"/>
                <dict-tag  v-else-if="item.columnName === 'isAgv'"  v-slot="scope" :options="dict.type.common_zero_or_one" :value="scope.row[item.columnName]"/>
                <dict-tag  v-else-if="item.columnName === 'type'"  v-slot="scope" :options="dict.type.storage_type" :value="scope.row[item.columnName]"/>
                <span v-else>{{ scope.row[item.columnName] }}</span>
              </template>
            </el-table-column>

        </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-row>
              <el-col :span="12" v-if="form.deptId !== 0">
                <el-form-item label="所属部门" prop="deptId">
                  <treeselect
                    v-model="form.deptId"
                    :options="deptOptions"
                    :normalizer="normalizer"
                    placeholder="选择部门"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库名称" prop="storageShortName">
                <el-input
                  v-model="form.storageShortName"
                  placeholder="请输入仓库名称"
                />
              </el-form-item>
              </el-col>
            </el-row>
            <el-col :span="12">
              <el-form-item label="仓库编号" prop="storageId">
                <el-input
                  v-model="form.storageId"
                  placeholder="请输入仓库编号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库名称" prop="storageName">
                <el-input
                  v-model="form.storageName"
                  placeholder="请输入仓库名称"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否AGV库" prop="isAgv">
                <el-select v-model="form.isAgv" placeholder="请选择">
                  <el-option
                    v-for="dict in dict.type.common_zero_or_one"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="仓储类型" prop="type">
                <el-select v-model="form.type" placeholder="请择选仓储类型">
                  <el-option
                    v-for="dict in dict.type.storage_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态">
                  <el-option
                    v-for="dict in dict.type.common_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </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>
  </div>
</template>

<script>
import { listCOLUMN } from "@/api/system/column";
import { listDept } from "@/api/system/dept";
import {
  addStorage,
  changeStatus,
  delStorage,
  disabled,
  enabled,
  getStorage,
  listStorage,
  updateStorage,
} from "@/api/system/storage";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Storage",
  dicts: ["common_status", "is_solid", "common_zero_or_one",'storage_type'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库管理表格数据
      storageList: [],
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "storage",
      rightToolbarShow: false,
      tableNo: 0,
      rndKey:0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        factoryId: null,
        deptId: null,
        storageId: null,
        storageName: null,
        storageShortName: null,
        selectIds:[]
      },
      // 表单参数
      form: {},
      // 部门树选项
      deptOptions: [],
      // 表单校验
      rules: {
        storageId: [
          { required: true, message: "仓库编号不能为空", trigger: "blur" },
        ],
        storageShortName: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" },
        ],
        storageName: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" },
        ],
        isAgv: [
          { required: true, message: "是否agv库不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "仓库类型不能为空", trigger: "blur" },
        ],
      },
      columns: [],
    };
  },
  created() {
    this.getList();
    this.getListDept();
  },
  mounted() {
    this.computedTableHeight();
  },
  watch: {
    showSearch: function () {
      this.computedTableHeight();
    },
  },
  methods: {

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

    handleHeaderDragEnd (newWidth, oldWidth, column, event) {
      // 当列宽发生变化时，将变化值写入到columns变量中。
      this.columns.map((obj) => {
        if (obj.columnName == column.property) obj.width = newWidth;
      });
      this.$refs.toolBarRef.saveConfig(this.columns);

    },


    getListDept() {
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
    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;
      listStorage(this.queryParams).then((response) => {
        this.storageList = response.rows;
        this.total = response.total;
        if (this.columns.length == 0) this.columns = response.columns;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        factoryId: null,
        deptId: null,
        storageId: null,
        storageName: null,
        storageAddress: null,
        storageConcatsName: null,
        storageConcatsMobile: null,
        autoStatus: null,
        status: null,
        isAgv: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
      };
      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.form.deptId = 101;
      this.open = true;
      this.title = "添加仓库管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.form.deptId = 101;
      getStorage(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改仓库管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateStorage(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStorage(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 delStorage(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 用户状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '"id为"' + row.id + '"数据项？')
        .then(function () {
          return changeStatus(row.id, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 启用按钮操作 */
    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/storage/export",
        {
          ...this.queryParams,
        },
        `storage_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
}
</style>
