<template>
  <el-dialog
    v-dialogDrag
    title="货位"
    :visible.sync="viewOpen"
    width="1200px"
    append-to-body
    @open="dialogOpen"
    @close="dialogClose"
  >
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
    >
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="货位编码" prop="locationCode">
            <el-input
              v-model="queryParams.locationCode"
              placeholder="请输入仓库货位编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="库存单位" prop="storageUnit">
            <el-select
              v-model="queryParams.storageUnit"
              placeholder="请选择库存单位"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in getDictDatas(DICT_TYPE.MES_UNIT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="库位容量" prop="storageQty">
            <el-input
              v-model="queryParams.storageQty"
              placeholder="请输入库位容量"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="可放物料" prop="materials">
            <el-input
              v-model="queryParams.materials"
              placeholder="请输入可放物料"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
            >重置</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:stock-location:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          :loading="exportLoading"
          @click="handlePrint"
          >标签打印</el-button
        >
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 列表（含单选限制方法） -->
    <!-- <el-table
      v-loading="loading"
      :data="list"
      border
      size="mini"
      @selection-change="tableSelected"
      @select="select"
      @select-all="selectAll"
    > -->
    <!-- 列表（不含单选限制方法） -->
    <el-table
      v-loading="loading"
      :data="list"
      border
      size="mini"
      @selection-change="tableSelected"
    >
      <el-table-column
        type="selection"
        width="55"
        fixed="left"
        align="center"
      />
      <el-table-column
        label="货位编码"
        width="120"
        show-overflow-tooltip
        align="center"
        prop="locationCode"
      />
      <el-table-column
        label="货位名称"
        align="center"
        prop="name"
        width="160"
        show-overflow-tooltip
      />
      <el-table-column label="库存单位" align="center" prop="storageUnit">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.MES_UNIT" :value="scope.row.storageUnit" />
        </template>
      </el-table-column>
      <el-table-column label="库位容量" align="center" prop="storageQty" />
      <el-table-column
        label="货架号"
        align="center"
        prop="shelfNo"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="层号"
        align="center"
        prop="storey"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="位置编码"
        align="center"
        prop="position"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="可放物料"
        align="center"
        prop="materials"
        width="150"
      >
        <template slot-scope="{ row }">
          <el-tag
            v-for="item in row.materialsName"
            :key="item.code"
            type="primary"
            size="mini"
            >{{ item.name }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['wms:stock-location:update']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-hasPermi="['wms:stock-location:delete']"
            size="mini"
            type="text"
            class="text-danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      @open="updateOpen"
      @close="dialogCloseWithUpdate"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="区域名称" prop="wmsStockAreaId">
          <el-input
            v-model="names"
            placeholder="请输入对应仓库区域"
            clearable
            disabled
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="货位编码" prop="locationCode">
          <el-input
            v-model="form.locationCode"
            placeholder="仓库货位编码自动生成"
            disabled
          />
        </el-form-item>
        <el-form-item label="货架号" prop="shelfNo">
          <!-- <el-input
            v-model="form.shelfNo"
            oninput="value=value.replace(/[^A-Z]/g, '')"
            placeholder="请输入A-Z的货架号"
            @change="shelfNoChange"
          /> -->
          <DictSelect
            v-model="form.shelfNo"
            placeholder="请选择货架号"
            dict-type="WMS_SHELVES_CODE"
            @change="shelfNoChange"
          />
        </el-form-item>
        <el-form-item label="层" prop="storey">
          <!-- <el-input
            v-model="form.storey"
            oninput="value=value.replace(/^\D*(\d*(?:.\d)?).*$/g, '$1')"
            placeholder="请输入层"
            @change="storeyChange"
          /> -->
          <DictSelect
            v-model="form.storey"
            placeholder="请选择层号"
            dict-type="WMS_LEVEL_CODE"
            @change="storeyChange"
          />
        </el-form-item>
        <el-form-item label="位置" prop="position">
          <!-- <el-input
            v-model="form.position"
            oninput="value=value.replace(/^\D*(\d*(?:.\d)?).*$/g, '$1')"
            placeholder="请输入位置"
            @change="positionChange"
          /> -->
          <DictSelect
            v-model="form.position"
            placeholder="请选择位置"
            dict-type="WMS_LOCATION_CODE"
            @change="positionChange"
          />
        </el-form-item>
        <el-form-item label="货位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入仓库货位名称" />
        </el-form-item>
        <el-form-item label="库存单位" prop="storageUnit">
          <el-select
            v-model="form.storageUnit"
            placeholder="请选择库存单位"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in getDictDatas(DICT_TYPE.MES_UNIT)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库位容量" prop="storageQty">
          <el-input
            v-model="form.storageQty"
            placeholder="请输入库位容量"
            oninput="value=value.replace(/^\D*(\d*(?:.\d{0,7})?).*$/g, '$1')"
          />
        </el-form-item>
        <el-form-item label="可放物料编码" prop="materials">
          <MaterialSelect
            ref="materialsSelect"
            v-model="form.materials"
            multiple
            filterable
            placeholder="请选择可放物料"
            @change="change"
          />
        </el-form-item>
        <el-form-item
          v-if="selectedMaterialList.length > 0"
          label="可放物料名称"
          prop="materialsName"
        >
          <!-- <MaterialSelect
            v-model="form.materialsName"
            multiple
            filterable
            placeholder="请选择可放物理"
          /> -->
          <!-- <el-input v-model="form.materialsName" placeholder="请输入可放物料" /> -->
          <div class="material-wrapper">
            <el-tag
              v-for="item in selectedMaterialList"
              :key="item.code"
              type="primary"
              size="small"
              class="material-wrapper-item"
              >{{ item.name }}</el-tag
            >
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            maxlength="200"
            show-word-limit
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 标签打印 -->
    <IssuePrinit ref="issuePrint" />
  </el-dialog>
</template>

<script>
import {
  createStockLocation,
  updateStockLocation,
  deleteStockLocation,
  getStockLocation,
  getStockLocationPage,
  exportStockLocationExcel,
} from "@/api/wms/base/stockLocation";
import MaterialSelect from "./MaterialSelect.vue";
const AccessTokenKey = "ACCESS_TOKEN";
import IssuePrinit from "../../output/productionIssue/issueDetails/IssuePrinit.vue";

export default {
  name: "StockLocation",
  components: {
    MaterialSelect,
    IssuePrinit,
  },
  props: {
    id: {
      type: [String, Number],
      default: "",
    },
    code: {
      type: String,
      default: "",
    },
    names: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      editDisable: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // WMS 仓库 仓库货位列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      viewOpen: false,
      // 打印参数
      tokens: "",
      baseUrl: "",
      reportId: "",
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        wmsStockAreaId: null,
        locationCode: null,
        storageUnit: null,
        storageQty: null,
        remark: null,
        materials: null,
        createTime: [],
      },
      // 表单参数
      form: {},
      selectedMaterialList: [],
      selectedMaterialListCopied: [],
      currentRows: [],
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            message: "对应仓库区域表ID不能为空",
            trigger: "blur",
          },
        ],
        // locationCode: [{ required: true, message: '仓库货位编码不能为空', trigger: 'blur' }],
        storageUnit: [
          { required: true, message: "库存单位不能为空", trigger: "blur" },
        ],
        storageQty: [
          { required: true, message: "库位容量不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getStockLocationPage(this.queryParams)
        .then((response) => {
          this.list = response.data.list.map((i) => {
            const { materialsName } = i;
            if (materialsName) {
              i.materialsName = JSON.parse(materialsName);
            } else {
              i.materialsName = [];
            }
            return i;
          });
          this.total = response.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        wmsStockAreaId: undefined,
        locationCode: undefined,
        storageUnit: undefined,
        storageQty: undefined,
        remark: undefined,
        materials: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加WMS 仓库 仓库货位";
      this.form.wmsStockAreaId = this.id;
      // this.form.locationCode = this.code
      this.form.names = this.names;
      this.editDisable = false;
    },
    updateOpen() {
      this.$nextTick(() => {
        this.$refs.materialsSelect.copiedOptions = this.selectedMaterialList;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      this.editDisable = true;
      getStockLocation(id).then((response) => {
        const { data = {} } = response;
        data.materials = data.materials ? data.materials.split(",") : [];
        this.selectedMaterialList = data.materialsName
          ? JSON.parse(data.materialsName)
          : [];
        this.form = data;
        this.open = true;
        this.title = "修改WMS 仓库 仓库货位";
      });
    },
    // 计算货位
    positionChange(v) {
      const { shelfNo, storey } = this.form;
      if (!shelfNo || !storey) {
        this.form.locationCode = undefined;
        return;
      }
      this.form.locationCode =
        this.names + "-" + shelfNo + "-" + storey + "-" + v;
    },
    shelfNoChange(v) {
      const { position, storey } = this.form;
      if (!position || !storey) {
        this.form.locationCode = undefined;
        return;
      }
      this.form.locationCode =
        this.names + "-" + v + "-" + storey + "-" + position;
    },
    // 根据层计算货位
    storeyChange(v) {
      const { shelfNo, position } = this.form;
      if (!position || !shelfNo) {
        this.form.locationCode = undefined;
        return;
      }
      this.form.locationCode =
        this.names + "-" + shelfNo + "-" + v + "-" + position;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        // 修改的提交
        // this.form.materials = this.form.materials.join(',')
        const params = JSON.parse(JSON.stringify(this.form));
        params.materials = params.materials ? params.materials.join(",") : "";
        params.materialsName = JSON.stringify(
          this.selectedMaterialList.map((i) => {
            const { name, code } = i;
            return { name, code };
          })
        );
        if (params.id != null) {
          updateStockLocation(params).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
            this.selectedMaterialList = [];
          });
          return;
        }
        // 添加的提交
        params.wmsStockAreaId = this.queryParams.wmsStockAreaId;
        createStockLocation(params).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
          this.selectedMaterialList = [];
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { id } = row;
      this.$modal
        .confirm('是否确认删除WMS 仓库 仓库货位编号为"' + id + '"的数据项?')
        .then(function () {
          return deleteStockLocation(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有WMS 仓库 仓库货位数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportStockLocationExcel(params);
        })
        .then((response) => {
          this.$download.excel(response, "WMS 仓库 仓库货位.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    dialogOpen() {
      this.getList();
      this.tokens = localStorage.getItem(AccessTokenKey);
      this.baseUrl = process.env.VUE_APP_REPORT_API;
      this.reportId = this.$route.meta.reportId;
    },
    dialogClose() {
      this.list = [];
    },
    change(list) {
      this.selectedMaterialList = list;
      // const index = this.selectedMaterialList.findIndex(item => !(v.includes(item.code)))
      // if (index > -1) {
      //   this.selectedMaterialList.splice(index, 1)
      // }
    },
    // 表格选中
    tableSelected(val) {
      this.currentRows = val;
      const list = this.currentRows.map((item) => item.deliveryOrderNo);
      this.ids = list.join(",");
    },
    // select和selectAll两个方法在全选时只会选中第一条数据
    select(selection, row) {
      if (selection.length > 1) {
        const del_row = selection.shift();
        this.$refs.multipleTable.toggleRowSelection(del_row, false);
      }
    },
    selectAll(selection) {
      if (selection.length > 1) {
        selection.length = 1;
      }
    },
    dialogCloseWithUpdate() {
      this.selectedMaterialList = [];
    },
    handlePrint() {
      if (this.currentRows.length <= 0) {
        this.$modal.msgWarning("请先选择你要打印的数据!");
        return;
      }
      console.log(this.currentRows);
      // 只能单个打印
      // const { id, locationCode } = this.currentRows[0];
      // const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&id=${id}&code=${locationCode}`;
      // 可以批量打印
      const ids = this.currentRows.map((row) => row.id).join(",");
      const codes = this.currentRows.map((row) => row.locationCode).join(",");
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&id=${ids}&code=${codes}`;
      this.$refs.issuePrint.title = "单据打印";
      this.$refs.issuePrint.dialogVisible = true;
      this.$refs.issuePrint.src = src;
    },
  },
};
</script>

<style lang="scss" scoped>
.material-wrapper {
  .material-wrapper-item + .material-wrapper-item {
    margin-left: 5px;
  }
}
</style>
