<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:pallet: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:pallet:edit']"
            >修改</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:pallet: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:pallet: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
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:pallet: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:pallet:import']"
          >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:pallet: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="storageId">
          <el-input
            v-model="queryParams.storageId"
            placeholder="请输入所属仓库"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="容器编号" prop="palletId">
          <el-input
            v-model="queryParams.palletId"
            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="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="type">
          <el-select
            v-model="queryParams.type"
            placeholder="请选容器类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.container_type"
              :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="palletList" @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.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]
                 || '正常'"/>
                <dict-tag  v-else-if="item.columnName === 'type'"  v-slot="scope" :options="dict.type.container_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-col :span="8">
              <el-form-item label="容器编号" prop="palletId">
                <el-input
                  v-model="form.palletId"
                  placeholder="请输入容器编号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="容器名称" prop="palletName">
                <el-input
                  v-model="form.palletName"
                  placeholder="请输入容器名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="容器简称" prop="pyName">
                <el-input v-model="form.pyName" placeholder="请输入容器简称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="12">
              <el-form-item label="占用状态" prop="status">
                <el-select
                  v-model="form.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-col>
            <el-col :span="12">
              <el-form-item label="禁用状态" prop="isLock">
                <el-select
                  v-model="form.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-col>
          </el-row>
          <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="type">
                <el-select
                  v-model="form.type"
                  placeholder="请选容器类型"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.container_type"
                    :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 {
  addPallet,
  changeStatus,
  delPallet,
  disabled,
  enabled,
  getPallet,
  listPallet,
  updatePallet,
} from "@/api/system/pallet";
import { getToken } from "@/utils/auth";
export default {
  name: "Pallet",
  dicts: ["common_status","container_type","location_type"],
  data() {
    return {
      rndKey:0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 托盘表格数据
      palletList: [],
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        palletId: null,
        palletName: null,
        pyName: null,
        palletType: null,
        palletLong: null,
        palletWidth: null,
        palletHeight: null,
        volume: null,
        bearWeight: null,
        status: null,
        isLock: null,
        workType: null,
        type:null,
        selectIds:[],
        storageId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        palletId: [
          { required: true, message: "容器编号不能为空", trigger: "blur" },
        ],
        palletName: [
          { required: true, message: "容器名称不能为空", trigger: "blur" },
        ],
        type: [
          { 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/pallet/importData",
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.computedTableHeight();
  },
  watch: {
    showSearch: function () {
      this.computedTableHeight();
    },
  },
  methods: {
    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;
      listPallet(this.queryParams).then((response) => {
        this.palletList = response.rows;
        this.total = response.total;
        if (this.columns.length == 0) this.columns = response.columns;
        this.loading = false;
      });
    },
    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();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        palletId: null,
        palletName: null,
        pyName: null,
        palletType: null,
        palletLong: null,
        palletWidth: null,
        palletHeight: null,
        volume: null,
        bearWeight: null,
        status: null,
        isLock:null,
        remark: null,
        version: null,
        userId: null,
        workType: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        storageId: 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.open = true;
      this.title = "添加托盘";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPallet(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) {
            updatePallet(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPallet(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 delPallet(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 启用按钮操作 */
    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(() => {});
    },
    /** 用户状态修改 */
    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 () {

        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/pallet/export",
        {
          ...this.queryParams,
        },
        `pallet_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "托盘导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/pallet/importTemplate",
        {},
        `pallet_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>
