<template>
  <el-form :model="formData" label-width="100px">
    <el-button-group
      style="display: flex; margin: 0px 0 10px 80%; height: 35px"
    >
      <el-button size="mini" type="primary" @click.native="saveData()"
      >提交
      </el-button
      >
      <el-button size="mini" type="primary" @click.native="closePlaceDialog(1)"
      >关闭
      </el-button
      >
    </el-button-group>
    <el-row>
      <el-col :span="10">
        <el-form-item prop="invWarehouseCode" label="当前仓库:">
          <el-select
            v-model="formData.invCode"
            placeholder="当前仓库信息"
            :disabled="list.length > 0"
            @change="invChange"
            style="width: 90%"
          >
            <el-option
              v-for="item in invList"
              :key="item.name"
              :label="item.name"
              :value="item.code"
            >
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="10">
        <!--        <el-form-item label="上架货位:">-->
        <!--          <el-select v-model="formData.invSpaceName" placeholder="请选择上架货位"-->
        <!--                     @change="updateInvSpaceCode"-->
        <!--                     :disabled="list.length > 0"-->
        <!--                     :fetch-suggestions="querySearchAsync"-->
        <!--                     ref="spaceInputRef"-->
        <!--                     @select="handleSelect"-->
        <!--                     @keypress.enter.native="spaceEnterKey($event)"-->
        <!--                     style="width: 90%"-->
        <!--                     clearable-->
        <!--          >-->
        <!--            <el-option v-for="item in spaceList" :key="item.id"-->
        <!--                       :label="item.name" :value="item.id"/>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->


        <el-form-item class="query-form-item" label="上架货位:">
<!--          <el-autocomplete-->
<!--            v-model="formData.invSpaceName"-->
<!--            :disabled="list.length > 0"-->
<!--            :fetch-suggestions="querySearchAsync"-->
<!--            placeholder="请输入内容"-->
<!--            ref="spaceInputRef"-->
<!--            @select="handleSelect"-->
<!--            @keypress.enter.native="spaceEnterKey($event)"-->
<!--            style="width: 90%"-->
<!--            clearable-->
<!--          ></el-autocomplete>-->
          <el-autocomplete
            v-model="formData.invSpaceName"
            :disabled="list.length > 0"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            ref="spaceInputRef"
            @select="handleSelect"
            @keypress.enter.native="spaceEnterKey($event)"
            @clear="clearFormData"
            style="width: 90%"
            clearable
          ></el-autocomplete>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="18">
        <el-form-item class="query-form-item" label="扫码录入:">
          <el-input
            id="inputer"
            @focus="getInputFocus($event)"
            @keypress.enter.native="enterKey($event)"
            ref="inputRef"
            style="ime-mode: disabled"
            type="tel"
            v-model="formData.code"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-button
          type="primary"
          size="mini"
          @click.native.stop="addCode()"
          style="margin-left: 15px"
        >添加
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      style="width: 100%; margin-top: 20px"
      highlight-current-row
      border
      max-height="300"
      height="300"
    >
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column
        label="DI/物资编码"
        prop="relId"
        width="150"
      ></el-table-column>
      <el-table-column
        label="物资名称"
        prop="productName"
        width="150"
        show-tooltip-when-overflow
      ></el-table-column>
      <el-table-column
        label="规格型号"
        prop="ggxh"
        width="150"
      ></el-table-column>
      <el-table-column
        label="批次号"
        prop="batchNo"
        width="150"
      ></el-table-column>
      <el-table-column
        label="序列号"
        prop="serialNo"
        width="150"
      ></el-table-column>
      <el-table-column
        label="计量单位"
        prop="measname"
        width="150"
      ></el-table-column>
      <el-table-column
        label="货位"
        prop="invSpaceName"
        width="150"
      ></el-table-column>
      <el-table-column label="数量" prop="count" width="150"></el-table-column>
      <el-table-column
        label="注册备案号"
        prop="zczbhhzbapzbh"
        width="150"
        show-tooltip-when-overflow
      ></el-table-column>
      <el-table-column
        label="生产厂家"
        prop="manufactory"
        width="150"
      ></el-table-column>
      <el-table-column
        label="供应商"
        prop="supName"
        width="150"
      ></el-table-column>
    </el-table>
  </el-form>
</template>

<script>
import {getInvListByUser} from "@/api/system/invWarehouse";
import {getInvSpaceList} from "@/api/inventory/invSpace";
import {isBlank} from "@/utils/strUtil";
import {
  bindInvSpace,
  getInvPlaceOrderDetailList,
  getInvProductInfo,
} from "@/api/inventory/invPlace";
import A from "@/plugins/KeyScaner";

export default {
  props: {
    closePlaceDialog: {
      type: Function,
      required: true,
    },
  },
  name: "InvProductPlaceModify",
  data() {
    return {
      formData: {
        invCode: this.$store.getters.locInvCode,
        invSpaceCode: null,
        invSpaceName: null,
        code: null,
      },
      //spaceList: [{id: 1, name: '货位1'}, {id: 2, name: '货位2'}, {id: 3, name: '货位3'}],
      orderId: null,
      list: [],
      codeArray: [],
      invList: [],
      spaceList: [],
      loading: false,
      spaceSearchResult: [],
      sitcomScan: false,
    };
  },
  methods: {
    saveData() {
      if (isBlank(this.formData.invCode)) {
        this.$message.error("请选择当前仓库");
        return;
      }
      if (isBlank(this.formData.invSpaceCode)) {
        this.$message.error("请选择当前货位");
        return;
      }
      if (this.list.length === 0) {
        //this.$message.error(this.formData.invSpaceCode);

        this.$message.error("请录入需要上架的物资数据");
        return;
      }
      this.$confirm("是否确认保存当前数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            invCode: this.formData.invCode,
            invSpaceCode: this.formData.invSpaceCode,
            type: 1, //按物资上架
            orderId: this.orderId,
          };
          bindInvSpace(params)
            .then((res) => {
              if (res.code === 20000) {
                this.$message.success("上架成功");
                this.clearFormData();
                this.$nextTick(() => {
                  this.$refs.spaceInputRef.focus();
                });
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((error) => {
              this.$message.error(error.message);
            });
        })
        .catch(() => {
        });
    },
    updateInvSpaceCode() {
      // 根据所选的货位名称，更新对应的货位编码
      const selectedSpace = this.spaceList.find(space => space.id === this.formData.invSpaceName);
      this.formData.invSpaceCode = selectedSpace ? selectedSpace.code : null;
      //this.$message.error(this.formData.invSpaceCode);
      // if (selectedSpace) {
      //   this.formData.invSpaceCode = selectedSpace.id
      //   // if (this.formData.invSpaceCode == 1656491192791773184) {
      //   //   this.formData.invSpaceCode = '0010';
      //   // } else if (this.formData.invSpaceCode == 1656491242624299008) {
      //   //   this.formData.invSpaceCode = '0011';
      //   // } else if (this.formData.invSpaceCode == 1656491284529590272) {
      //   //   this.formData.invSpaceCode = '0012';
      //   // }
      // } else {
      //   this.formData.invSpaceCode = null
      // }
    },
    clearFormData() {
      //清空表单数据
      this.formData = {
        invCode: this.$store.getters.locInvCode,
        invSpaceCode: null,
        invSpaceName: null,
        code: null,
      };
      this.orderId = null;
      this.codeArray = [];
      this.list = [];
      //光标切回货位框
      this.$refs.spaceInputRef.focus();
    },
    invChange() {
      this.formData.invSpaceCode = null;
      this.formData.invSpaceName = null;
      this.list.forEach((item) => {
        item.invSpaceCode = null;
        item.invSpaceName = null;
      });
      this.getSpaceList();
      this.$nextTick(() => {
        this.$refs.spaceInputRef.focus();
      });
    },
    querySearchAsync(queryString, cb) {
      let restaurants = this.spaceList;
      restaurants.forEach((item) => {
        item.value = item.name;
      });

      let results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      if (!isBlank(queryString)) {
        this.spaceSearchResult = results;
      }
      cb(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        const {value, code} = state;
        return (
          value === queryString.toLowerCase() ||
          code === queryString.toLowerCase()
        );
      };
    },
    handleSelect(item) {
      this.formData.invSpaceCode = item.code;
      this.formData.invSpaceName = item.name;
      this.list.forEach((invProduct) => {
        invProduct.invSpaceCode = item.code;
        invProduct.invSpaceName = item.name;
      });
    },clearSpaceInput() {
      this.formData.invSpaceName = null; // 清空 formData.invSpaceName 的值
      this.$message.error(this.formData.invSpaceName);
    },
    getInvList() {
      getInvListByUser()
        .then((response) => {
          this.invList = response.data || [];
          this.getSpaceList();
          this.getList();
          this.$refs.spaceInputRef.focus();
        })
        .catch(() => {
        });
    },
    getSpaceList() {
      let params = {
        invWarehouseCode: this.formData.invCode,
        status: 1,
      };
      getInvSpaceList(params).then((res) => {
        this.spaceList = res.data.list || [];
      });
    },
    addCode(event) {
      if (event != null) {
        event.target.select();
      }
      this.$refs.inputRef.select();
      if (isBlank(this.formData.invCode)) {
        this.$message.error("当前仓库不能为空");
        return;
      }

      if (isBlank(this.formData.invSpaceName)) {
        this.$message.error("上架货位不能为空");
        return;
      }

      this.formData.code = this.formData.code.trim();
      if (this.$isBlank(this.formData.code)) return;
      this.getInvProductInfo(this.formData.code);
      this.$refs.inputRef.select();
    },
    getInvProductInfo(code) {
      let params = {
        orderId: this.orderId,
        invCode: this.formData.invCode,
        code: code,
        type: 1, //按物资上架
        invSpaceCode: this.formData.invSpaceCode,
      };
      getInvProductInfo(params).then((res) => {
        if (res.code == 20000) {
          this.orderId = res.data;
          getInvPlaceOrderDetailList({orderId: this.orderId}).then((res) => {
            this.list = res.data.list;
          });
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    getInputFocus(event) {
      event.currentTarget.select();
    },
    enterKey(event) {
      this.checkSuccess = true;
      this.addCode(event);
      this.$refs.inputRef.focus();
      this.$refs.inputRef.select();
    },
    spaceEnterKey(event) {
      if (this.spaceSearchResult.length > 0) {
        this.handleSelect(this.spaceSearchResult[0]);
        this.$refs.spaceInputRef.close();
        this.$refs.inputRef.focus();
        this.$refs.inputRef.select();
      } else {
        event.target.select();
      }
    },
  },
  created() {
    this.$watch('$store.getters.locInvCode', this.getSpaceList); // 监听库位编码变化并调用getSpaceList方法
    this.$watch('formData.invCode', this.getSpaceList); // 监听所属仓库编码变化并调用getSpaceList方法
    this.getInvList();
  },
  mounted() {
    //默认获取上架货物光标
    this.$refs.spaceInputRef.focus();
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    var that = this;
    var inputer = document.getElementById("inputer");
    window.sc = new A.KeyScaner(inputer);//传入要监听的DOM节点
    sc.onInput = function (text) {
      //onInput事件在检测到回车键按下或在连续输入后超过500ms没有继续输入时触发
      if (text.includes("delete")) {
        that.formData.code = "";
        return;
      }
      if (that.sitcomScan) {
        that.formData.code = that.formData.code;
      } else {
        that.formData.code = text;
      }
    };
    inputer.focus();//别忘了给要监听的节点放置焦点，如果是div一类默认不具备焦点的节点需要给它加上“tabindex”属性。不建议传入document、Body等全局节点，可能会影响其它输入控件的流畅性。

  },

};
</script>

<style scoped></style>
