<template>
  <view>
    <uni-popup ref="popup" background-color="#fff" :mask-click="false">
      <view class="title"
        >选择货位
        <view class="btn">
          <u-icon
            name="scan"
            color="#fff"
            size="80"
            @click="handleScan"
          ></u-icon>
        </view>
      </view>
      <view class="select-group" :key="forceUpdate">
        <view class="select-col">
          <text class="select-label">仓库</text>
          <picker
            @change="
              (e) =>
                handlePicker(e, warehouseList, 'warehouseName', 'warehouseId')
            "
            :disabled="warehouseDisabled"
            :value="pickerIndex"
            :range="warehouseList"
            range-key="name"
            ><u-input
              :value="formData.warehouseName"
              disableColor="#ffffff"
              placeholder="请选择"
              disabled
              type="select"
          /></picker>
          <!-- <uni-data-select
            v-model="warehouse"
            v-if="!warehouseDisabled"
            :localdata="warehouseList"
          ></uni-data-select> -->
          <!-- <template v-else> {{ formData.warehouse.name }}</template> -->
        </view>
        <view class="select-col">
          <text class="select-label">库区</text>
          <picker
            @change="(e) => handlePicker(e, areaList, 'areaName', 'area')"
            :value="pickerIndex"
            :range="areaList"
            range-key="name"
            :disabled="!formData.warehouseId"
            ><u-input
              @click.native="areaClick"
              :value="formData.areaName"
              disableColor="#ffffff"
              placeholder="请选择"
              disabled
              type="select"
          /></picker>
          <!-- <uni-data-select
            v-model="area"
            :localdata="areaList"
          ></uni-data-select> -->
        </view>
        <view class="select-col">
          <text class="select-label">货架</text>
          <picker
            @change="
              (e) => handlePicker(e, shelvesList, 'shelvesName', 'shelves')
            "
            :value="pickerIndex"
            :range="shelvesList"
            :disabled="!formData.area"
            range-key="name"
            ><u-input
              @click.native="shelvesClick"
              :value="formData.shelvesName"
              disableColor="#ffffff"
              placeholder="请选择"
              disabled
              type="select"
          /></picker>
          <!-- <uni-data-select
            v-model="shelves"
            :localdata="shelvesList"
          ></uni-data-select> -->
        </view>
      </view>
      <scroll-view>
        <view class="content-box" :key="forceUpdate">
          <view
            v-for="p in locationList"
            :key="p.id"
            class="box"
            @click="cur = p"
            :class="{ active: cur.goodsAllocationId == p.goodsAllocationId }"
            :style="{
              'background-color': getStatus(p.allocationStatus).color,
              cursor: [1, 2].includes(p.allocationStatus)
                ? 'pointer'
                : 'not-allowed',
            }"
          >
            {{ p.goodsAllocationCode }}
          </view>
          <view class="placeholder-box"></view>
          <view class="placeholder-box"></view>
          <view class="placeholder-box"></view>
          <view class="placeholder-box"></view>
        </view>
      </scroll-view>
      <view class="footer">
        <uni-button @tap="cancel">取消</uni-button>
        <uni-button @tap="handleSelect" type="success" class="confim"
          >确认</uni-button
        >
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { postJ } from "@/utils/api.js";
import ScanCode from "@/components/ScanCode.vue";
const warehouseDefinition_locationStatus = [
  { id: 1, label: "空置", color: "rgba(202, 249, 130, 1)" },
  { id: 2, label: "在用", color: "rgba(129, 211, 248, 1)" },
  { id: 3, label: "已满", color: "rgba(255, 14, 14, 1)" },
  { id: 4, label: "失效", color: "rgba(215, 215, 215, 1)" },
];
export default {
  components: {
    ScanCode,
  },
  props: {
    // 主动关闭
    selfClose: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      pickerIndex: 0,
      forceUpdate: false,
      warehouseDisabled: false,
      visible: false,
      value: "",
      row: {},
      cur: {},
      formData: {
        // warehouse: {},
        // area: {},
        // shelves: {},
        warehouseName: "",
        warehouseId: "",
        area: "",
        areaName: "",
        shelves: "",
        shelvesName: "",
      },
      warehouse: "",
      area: "",
      areaName: "",
      shelves: "",
      shelvesName: "",
      warehouseList: [],
      callback: null,
    };
  },
  computed: {
    areaList() {
      this.formData.areaName = "";
      this.formData.area = "";
      this.formData.shelvesName = "";
      this.formData.shelves = "";
      return (
        this.warehouseList.find((i) => i.id === this.formData.warehouseId)
          ?.wareHouseArea || []
      ).map((i) => ({
        name: i.areaName,
        id: i.areaId,
        ...i,
      }));
    },
    shelvesList() {
      this.formData.shelvesName = "";
      this.formData.shelves = "";
      return (
        this.areaList.find((i) => i.areaId === this.formData.area)
          ?.wareHouseGoodsshelves || []
      ).map((i) => ({
        name: i.goodsshelvesCode,
        id: i.goodsshelvesId,
        ...i,
      }));
    },
    locationList() {
      return (
        this.shelvesList.find((i) => i.goodsshelvesId === this.formData.shelves)
          ?.wareHouseGoodsAllocation || []
      ).map((i) => ({
        name: i.goodsAllocationCode,
        id: i.goodsAllocationId,
        ...i,
      }));
    },
  },

  created() {
    this._getWarehouseChildren();
  },
  mounted() {},
  methods: {
    scancodedate(data) {
      this.qrContent = data.code.trim();
      this.getData();
    },
    initScan() {
      this.$store.commit("app/SET_SCANCODEDATE", "warehouse");
      const _this = this;

      uni.$off("warehouse"); // 每次进来先 移除全局自定义事件监听器
      uni.$on("warehouse", function (data) {
        _this.qrContent = data.code.trim();
        _this.getData();
      });
    },
    handleScan() {
      const _this = this;
      uni.scanCode({
        onlyFromCamera: true,
        success: function (res) {
          console.log("条码类型：" + res.scanType);
          console.log("条码内容：" + res.result);
          _this.isCamera = true;
          _this.qrContent = res.result.trim();
          _this.getData();
        },
      });
    },
    open(warehouse, callback) {
      this.cur = {};
      this.formData.warehouseName = "";
      this.formData.warehouseId = "";
      this.formData.areaName = "";
      this.formData.shelvesName = "";
      this.formData.shelves = "";

      if (warehouse) {
        this.formData.type = warehouse.type;
        this.formData.warehouseName = warehouse.name;
        this.formData.warehouseId = warehouse.id;
        this.warehouseDisabled = !!warehouse?.id;
      }
      this.$refs.popup.open("bottom");
      this.visible = true;
      this.initScan();

      this.callback = callback;
    },
    openDefault(warehouse, callback) {
      if (warehouse) {
        this.cur = warehouse;
        this.cur.goodsAllocationId = warehouse.cargoSpaceId;
        this.cur.goodsAllocationCode = warehouse.cargoSpaceCode;
        this.formData.warehouseName = warehouse?.warehouseName;
        this.formData.warehouseId = warehouse?.warehouseId;
        this.$nextTick(() => {
          this.formData.area = warehouse?.areaId || "";
          this.$nextTick(() => {
            this.formData.shelves = warehouse?.shelfId || "";
          });
        });
      }
      this.$refs.popup.open("bottom");
      this.visible = true;
      this.initScan();

      this.callback = callback;
    },
    shelvesClick() {
      if (!this.formData.area) {
        uni.showToast({
          title: "请先选择库区！",
          icon: "none",
        });
      }
    },
    areaClick() {
      if (!this.formData.warehouseId) {
        uni.showToast({
          title: "请先选择库区！",
          icon: "none",
        });
      }
    },
    // 根据条码请求设备数据 @_@
    getData() {
      let par = {
        barType: this.qrContent.split("@_@")[1] || 0,
        qrContent: this.qrContent,
      };
      if (!["2", "7"].includes(par.barType)) {
        return uni.showToast({
          title: "请扫描货架或货位码",
          icon: "none",
        });
      }
      postJ(this.apiUrl + "/scan/getAssetInfo", par).then((res) => {
        let data = res.data;
        console.log(data, "qrContent");
        this.setWarehosue(data, par.barType);
      });
    },
    setWarehosue(data, barType) {
      if (this.warehouseDisabled) {
        //  选定仓库
        if (data.warehouseId != this.formData.warehouseId) {
          uni.showToast({
            title: `请扫描${this.formData.warehouseName}下的${
              barType == 2 ? "货位" : "货架"
            }`,
            icon: "none",
          });
          return;
        }
      }

      this.cur = {};
      this.formData.area = "";
      this.formData.areaName = "";

      // this.cur.goodsAllocationId = data.cargoSpaceId
      // this.cur.goodsAllocationCode = data.cargoSpaceCode
      this.formData.warehouseName = data?.warehouseName;
      this.formData.warehouseId = data?.warehouseId;
      this.$nextTick(() => {
        this.formData.area = data?.warehouseAreaId || "";
        this.formData.areaName = data?.warehouseAreaName || "";
        this.$nextTick(() => {
          this.formData.shelves = data?.warehouseAreaGoodsId || data?.id || "";
          this.formData.shelvesName =
            data?.warehouseAreaGoodsCode || data?.goodsshelvesCode || "";
        });
      });
      if (barType == 2) {
        this.cur = {
          allocationStatus: data.allocationStatus,
          goodsAllocationCode: data.goodsAllocationCode,
          goodsAllocationId: data.id,
          id: data.id,
        };
      }
    },
    cancel() {
      this.warehouse = "";
      this.$refs.popup.close();
      this.visible = false;
      this.$store.commit("app/RESET_SCANCODEDATE");
    },
    // 抬头下拉信息保存
    handlePicker(e, list, nameKey, idKey) {
      if (idKey) {
        this.formData[idKey] = list[e?.detail.value]?.id;
      }
      if (nameKey) {
        this.formData[nameKey] = list[e?.detail.value]?.name;
      }
    },
    getStatus(id) {
      return (
        warehouseDefinition_locationStatus.find((item) => item.id === id) || {}
      );
    },
    handleSelect() {
      if (!this.cur?.id) {
        uni.showToast({
          title: "请选择货位",
          icon: "none",
        });
        return;
      }

      if (this.formData.type == "out") {
        if (this.cur.allocationStatus === 4) {
          uni.showToast({
            title: "失效的货位无法选择",
            icon: "none",
          });
          return;
        } else if (this.cur.allocationStatus === 1) {
          uni.showToast({
            title: "当前货位无货物!",
            icon: "none",
          });
          return;
        }
      } else if (![1, 2].includes(this.cur.allocationStatus)) {
        uni.showToast({
          title: "已满和失效的货位无法选择",
          icon: "none",
        });
        return;
      }

      const data = {};
      data.warehouseId = this.formData.warehouseId;
      data.warehouseName = this.formData.warehouseName;

      data.areaId = this.formData.area;
      data.areaName = this.formData.areaName;

      data.shelfId = this.formData.shelves;
      data.shelfCode = this.formData.shelvesName;

      data.cargoSpaceId = this.cur.goodsAllocationId;
      data.cargoSpaceCode = this.cur.goodsAllocationCode;

      this.callback && this.callback(data);
      this.$emit("success", data);
      if (!this.selfClose) {
        this.cancel();
      }
    },
    async _getWarehouseChildren() {
      const res = await postJ(
        this.apiUrl + "/outInWarehouse/select/getWarehouseChildren"
      );

      if (res?.success) {
        this.warehouseList = res.data.map((i) => ({
          name: i.name,
          id: i.id,
          ...i,
        }));
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  line-height: 80rpx;
  background-color: $j-primary-border-green;
  color: #fff;

  .btn {
    position: absolute;
    right: 0rpx;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80rpx;

    padding-right: 30rpx;
  }
}
.select-group {
  display: flex;
  flex-wrap: wrap;
  .select-col {
    width: 50%;
    display: flex;
    align-items: center;
    padding: 20rpx;
    box-sizing: border-box;
    .select-label {
      width: 5em;
    }
  }
}

.content-box {
  display: flex;
  justify-content: space-between;
  align-content: flex-start;
  flex-wrap: wrap;
  max-height: 60vh;
  min-height: 40vh;
  overflow: auto;
  padding: 0 12rpx;
  .box {
    cursor: pointer;
    min-width: 120rpx;
    padding: 0 10rpx;
    height: 80rpx;
    margin-right: 6rpx;
    margin-bottom: 12rpx;
    line-height: 80rpx;
    text-align: center;
    &.active {
      box-shadow: 2px 2px 2px 2px #ccc;
    }
  }
  .placeholder-box {
    width: 120rpx;
  }
}
.footer {
  display: flex;
  justify-content: space-between;

  button {
    width: 50%;
    border: none;
    border-radius: 0;
  }

  .confim {
    background-color: $j-primary-green;
    color: #fff;
  }
}
</style>
