<template>
  <el-dialog
    :visible.sync="visible"
    title="仓库"
    @before-close="cancel"
    width="1000px"
    append-to-body
  >
    <el-form :model="formData" label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="选择仓库">
            <el-select filterable v-model="warehouse" @change="warehouseChange">
              <el-option
                v-for="(item, index) in warehouseList"
                :key="index"
                :label="item.name"
                :value="item.id"
                @click.native="changeWarehouse(item)"
              ></el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="选择库区">
            <el-select filterable v-model="area" @change="getshelvesList">
              <el-option
                v-for="(item, index) in areaList"
                :key="index"
                :label="item.name"
                :value="item.id"
                @click.native="formData.area = item"
              ></el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="选择货架">
            <el-select filterable v-model="shelves" @change="changeshelvesList">
              <el-option
                v-for="(item, index) in shelvesList"
                :key="index"
                :label="item.goodsshelvesCode"
                :value="item.goodsshelvesCode"
                @click.native="formData.shelves = item"
              ></el-option>
            </el-select> </el-form-item
        ></el-col>
      </el-row>
    </el-form>
    <div class="status-legend">
      <div
        v-for="(item, index) in warehouseDefinition_locationStatus"
        :key="index"
      >
        <span :style="{ 'background-color': item.color }"></span
        >{{ item.label }}
      </div>
    </div>
    <div class="content-box">
      <div
        v-for="p in locationList"
        :key="p.id"
        class="box"
        @click="handlCur(p)"
        :class="{ active: cur.goodsAllocationCode == p.goodsAllocationCode }"
        :style="{
          'background-color': getStatus(p.allocationStatus).color,
          cursor: [1, 2].includes(p.allocationStatus)
            ? 'pointer'
            : 'not-allowed'
        }"
      >
        {{ p.goodsAllocationCode }}
      </div>
      <div class="placeholder-box"></div>
      <div class="placeholder-box"></div>
      <div class="placeholder-box"></div>
      <div class="placeholder-box"></div>
    </div>
    <el-table :data="tableList" style="width: 940px">
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="货位位置" prop="position" width="600">
        <template slot-scope="scope">
          {{ scope.row.warehouseName }} - {{ scope.row.areaName }} -
          {{ scope.row.shelfCode }} - {{ scope.row.cargoSpaceCode }}
        </template>
      </el-table-column>

      <el-table-column label="数量" prop="num" width="170">
        <template slot-scope="scope">
          <el-input
            v-model.trim="scope.row.num"
            style="width: 120px"
            size="mini"
          ></el-input>
        </template>
      </el-table-column>

      <el-table-column width="120" label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="delItem(scope.$index)" size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <template slot="footer">
      <el-button @click="handleSelect" type="primary">确认</el-button>
      <el-button @click="cancel">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';

  import { warehouseDefinition_locationStatus } from '@/utils/dict/warehouseDefinition';
  import { useDict } from '@/utils/dict/index';
  export default {
    data() {
      return {
        warehouseDefinition_locationStatus: [
          { code: 1, label: '空置', color: 'rgba(202, 249, 130, 1)' },
          { code: 2, label: '在用', color: 'rgba(129, 211, 248, 1)' },
          { code: 3, label: '已满', color: 'rgba(255, 14, 14, 1)' },
          { code: 4, label: '失效', color: 'rgba(215, 215, 215, 1)' }
        ],
        visible: false,
        warehouseList: [], //仓库
        areaList: [], //库区
        areaGoodsshelvesList: [], //货架
        allocationReqList: [], //货位
        value: '',
        row: {},
        formData: {
          warehouse: {},
          area: {},
          shelves: {}
        },
        warehouse: '',
        area: '',
        shelves: '',
        cur: {
          cargoSpaceId: ''
        },
        shelvesList: [],
        locationList: [],
        tableList: [],
        idx: null
      };
    },

    created() {},
    methods: {
      delItem(index) {
        if (index == 0 && this.tableList.length == 1) {
          return this.$message.warning('请至少保存一条数据！');
        }
        this.tableList.splice(index, 1);
      },
      handlCur(row, num) {
        if (![1, 2].includes(row.allocationStatus)) {
          return;
        }
        this.cur = { ...row };
        console.log('==this.formData', this.formData);
        // let shelfId=
        const { area, shelves, warehouse } = this.formData;
        let warehouseId = warehouse.id;
        let warehouseName = warehouse.name;

        let areaId = area.id;
        let areaName = area.name;
        // ==========li
        let shelfId = shelves.id;
        let shelfCode = shelves.goodsshelvesCode;
        // ==========li
        let cargoSpaceId = this.cur.id;
        let cargoSpaceCode = this.cur.goodsAllocationCode;

        let flag = true;
        this.tableList.forEach((f) => {
          if (f.cargoSpaceId == cargoSpaceId && f.shelfId == shelfId) {
            this.$message.info('请勿重复选择');
            flag = false;
          }
        });
        if (flag) {
          this.tableList.push({
            warehouseId: warehouseId,
            warehouseName,
            areaId,
            areaName,
            shelfId,
            shelfCode,
            cargoSpaceId,
            cargoSpaceCode,
            num: num ? num : this.row.outInNum
          });
        }
      },
      warehouseChange() {
        this.cur = {};
        this.shelves = '';
        this.locationList = [];
        this.area = '';
      },
      async getshelvesList(e) {
        this.cur = {};
        this.shelves = '';
        this.locationList = [];
        this.shelvesList = this.areaGoodsshelvesList.filter(
          (i) => i.reservoirAreaCode === this.area
        );
        const rep = await warehouseDefinition.getListByAreaId(e);
        this.shelvesList = rep;
      },
      async changeshelvesList(id) {
        this.cur = {};
        // this.locationList = this.allocationReqList.filter(
        //   (i) => i.goodsAllocationCode === this.shelves
        // );
        const goodsId = this.shelvesList.filter((item) => {
          return item.goodsshelvesCode == id;
        })[0].id;
        const res = await warehouseDefinition.getListByGoodId(goodsId);
        this.locationList = res;
      },
      getStatus: useDict(warehouseDefinition_locationStatus),
      async open(row, idx) {
        this.locationList = [];
        this.tableList = [];
        if (row.houseList.length != 0) {
          this.row = row;
          this.idx = idx;
          this.visible = true;
          await this._getWarehouseChildren();
          if (this.row?.warehouseId) {
            this.warehouse = this.row.warehouseId;
            this.formData.warehouse = this.warehouseList.find(
              (w) => w.id == this.row.warehouseId
            );
            const res = await warehouseDefinition.getById({
              id: this.row.warehouseId
            });

            // this.areaList = res.reservoirAreaList || [];
            const rep = await warehouseDefinition.getListByWarehouseId(
              this.row.warehouseId
            );
            this.areaList = rep || [];
            console.log('===', rep);
            //

            this.formData.area = this.areaList.find(
              (w) => w.id == this.row.houseList[0].areaId
            ); // this.row.areaId
            this.area = this.row.houseList[0].areaId;

            // ===============================
            const result = await await warehouseDefinition.getListByAreaId(
              this.row.houseList[0].areaId
            );
            this.areaGoodsshelvesList = result || [];
            this.shelvesList = this.areaGoodsshelvesList.filter(
              (i) => i.id === this.row.houseList[0].shelfId
            );
            this.formData.shelves = this.areaGoodsshelvesList.find(
              (w) => w.id == this.row.houseList[0].shelfId
            );
            this.shelves = this.row.houseList[0].shelfCode;
            // =========================
            const loca = await warehouseDefinition.getListByGoodId(
              this.row.houseList[0].shelfId
            );
            this.locationList = loca;
            const items = loca.filter(
              (item) => item.id == this.row.houseList[0].cargoSpaceId
            );
            this.handlCur(items[0], this.row.houseList[0].num);
            console.log('items111', items);
            // this.allocationReqList = res.goodsAllocationList || [];
            // this.locationList = this.allocationReqList.filter(
            //   (i) => i.goodsAllocationCode === this.shelves
            // );
            // this.cur = this.allocationReqList.find(
            //   (w) => w.code === this.row.cargoSpaceCode
            // );
          }
        } else {
          this.row = row;
          this.idx = idx;
          this.visible = true;
          await this._getWarehouseChildren();
          this.formData = {
            warehouse: {},
            area: {},
            shelves: {}
          };
          this.warehouse = '';
          this.area = '';
          this.shelves = '';
        }
      },
      async changeWarehouse(val) {
        this.formData.warehouse = val;
        const res = await warehouseDefinition.getListByWarehouseId(val.id);
        this.area = '';
        this.shelves = '';
        this.areaList = res || [];
        this.areaGoodsshelvesList = res.goodsShelvesList || [];
        this.allocationReqList = res.goodsAllocationList || [];

        // ======
        this.row.warehouseId = val.id;
        await this.seachWareHouse();
      },
      // 查仓库
      async seachWareHouse() {
        if (this.row?.warehouseId) {
          this.warehouse = this.row.warehouseId;
          this.formData.warehouse = this.warehouseList.find(
            (w) => w.id == this.row.warehouseId
          );
          const res = await warehouseDefinition.warehouseDetail(
            this.row.warehouseId
          );

          this.areaList = res.warehouseAreasSaveList || [];

          this.formData.area = this.areaList.find(
            (w) => w.id == this.row.areaId
          ); // this.row.areaId
          this.area = this.row.areaCode;

          this.areaGoodsshelvesList = res.areaGoodsshelvesList || [];
          this.shelvesList = this.areaGoodsshelvesList.filter(
            (i) => i.reservoirAreaCode === this.area
          );
          this.formData.shelves = this.areaGoodsshelvesList.find(
            (w) => w.code == this.row.shelfCode
          );
          this.shelves = this.row.shelfCode;

          this.allocationReqList = res.allocationReqList || [];
          this.locationList = this.allocationReqList.filter(
            (i) => i.goodsAllocationCode === this.shelves
          );
          this.cur = this.allocationReqList.find(
            (w) => w.goodsAllocationCode === this.row.cargoSpaceCode
          );
        }
      },
      handleSelect() {
        // if (![1, 2].includes(this.cur.warehouseStatVO.type)) {
        //   return;
        // }
        // const { warehouse, area, shelves } = this.formData;

        // this.row.warehouseId = warehouse.id;
        // this.row.warehouseName = warehouse.name;

        // this.row.areaId = area.id;
        // this.row.areaName = area.name;
        // this.row.areaCode = area.code;

        // this.row.shelfId = shelves.id;
        // this.row.shelfCode = shelves.code;

        // this.row.cargoSpaceId = this.cur.id;
        // this.row.cargoSpaceCode = this.cur.code;

        this.$emit('houseData', this.tableList, this.idx);
        this.cancel();
      },
      async _getWarehouseChildren() {
        const res = await warehouseDefinition.list({});
        console.log(res);
        this.warehouseList = res.map((item) => {
          return { ...item, name: item.factoryName + '-' + item.name };
        });

        // const res = await getWarehouseChildren();
        // if (res?.success) {
        //
        // }
      },
      cancel() {
        this.row = {};
        this.formData = {};
        this.visible = false;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .status-legend {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 12px 0;
    div {
      margin: 0 12px;
    }
    span {
      display: inline-block;
      width: 13px;
      height: 13px;
      margin: 0 4px;
    }
  }

  .content-box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    max-height: 40vh;
    overflow: auto;
    .box {
      cursor: pointer;
      width: 134px;
      height: 64px;
      background-clip: content-box;
      margin-bottom: 4px;
      line-height: 64px;
      text-align: center;
      &:hover,
      &.active {
        box-shadow: 2px 2px 2px 2px #ccc;
      }
    }
    .placeholder-box {
      width: 134px;
    }
  }
</style>
