<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="type-title">载具入库</div>
        <ScanCodeInput
          v-model="boxSearch"
          :clearable="true"
          :showSuffix="true"
          placeholder="请扫描或输入料箱编号"
          @keyup.enter="enterBox"
          :disabled="outStatus || addStatus"
        />
        <el-scrollbar class="boxes-container base-container">
          <div
            v-for="(item, index) in boxesList"
            :key="index"
            :class="{ 'box-selected': index === currentBoxIndex }"
            class="box-item"
            @click="clickBox(item, index)"
          >
            <div class="box-header">
              <div class="box-name">{{ item.vehicleNo }}</div>
              <div class="box-name">
                {{ item.locationNo ? item.locationNo : "-" }}
              </div>
            </div>

            <div
              v-for="(material, index) in item.list"
              :key="index"
              class="box-info"
            >
              <div>{{ material.materialName }}</div>
              <div>{{ material.num }}</div>
            </div>
          </div>
        </el-scrollbar>
        <el-button
          class="sureBtn"
          type="primary"
          :disabled="outStatus || addStatus || Machinery"
          @click="sureToOut"
          >出库
        </el-button>
      </el-col>
      <el-col :span="8">
        <div class="type-title">盒内原有物料</div>
        <el-scrollbar class="outing-container">
          <div style="height: 300px" v-if="Machinery">
            <MachineryLoading />
          </div>
          <div v-if="!outStatus">
            <div class="addbox" v-if="addSuccessStatus">
              扫码的盒子编码:{{ addBoxInfo.code }}
            </div>

            <ScanCodeInput
              v-if="addStatus && addSuccessStatus == false"
              v-model="addBoxSearch"
              :clearable="true"
              :showSuffix="true"
              placeholder="请扫描或输入料箱编号"
              @keyup.enter="addenterBox"
            />
            <el-button
              class="sureBtn"
              :type="addStatus ? 'info' : 'primary'"
              @click="changeAddStatus"
              :disabled="Machinery"
              style="margin-bottom: 20px"
              >{{ addStatus ? "取消" : "入库新载具" }}
            </el-button>
          </div>
          <div
            v-for="(material, index) in outingMaterials"
            :key="index"
            class="outing-box"
          >
            <div class="outing-box-header">
              <div class="material-title">
                {{ material.materialName }} | {{ material.materialNo }}
              </div>
              <!-- <div
                @click=""
                class="material-title deleteSty"
              >
                删除
              </div> -->
              <i-ep-delete
                class="delete-btn"
                color="#ff4d4f"
                size="20px"
                @click="deleteIndexOld(index)"
              />
            </div>
            <div class="material-info">
              <div>批次号/序列号</div>
              <el-tooltip :content="material.batchCode" placement="top">
                <div class="batchCode">{{ material.batchCode }}</div>
              </el-tooltip>
            </div>
            <div class="material-info">
              <div>位置</div>
              <div>{{ material.locationNo }}</div>
            </div>
            <div class="material-info">
              <div>量值</div>
              <div>{{ material.num }}</div>
            </div>
          </div>
        </el-scrollbar>
        <el-button
          class="sureBtn"
          type="info"
          @click="backToStorage"
          :disabled="Machinery || !boxStatus"
          >入库
        </el-button>
      </el-col>
      <el-col :span="8">
        <div class="type-title">请扫码物料</div>
        <ScanCodeInput
          v-model="scanCodeInput"
          placeholder="请扫描或输入物料编码"
          @keyup.enter="handleScanCodeInput"
        />
        <el-scrollbar class="base-container">
          <div class="list-container">
            <div
              v-for="(item, index) in materialList"
              :key="index"
              class="list-box"
            >
              <div class="list-box-header">
                <div>
                  <div>
                    <div class="name">{{ item.materialName }}</div>
                    <div class="spec">{{ item.spec }}</div>
                  </div>
                  <div class="bottom">
                    <NumberInput v-model="item.num" />
                    <span class="unit">{{ item.unitDictLabel }}</span>
                  </div>
                </div>
                <!-- <div
                  @click="deleteIndexScanAdd(index)"
                  class="list-box-delete deleteSty"
                >
                  删除
                </div> -->
                <i-ep-delete
                  class="delete-btn"
                  color="#ff4d4f"
                  size="20px"
                  @click="deleteIndexScanAdd(index)"
                />
              </div>
            </div>
          </div>
        </el-scrollbar>
        <el-button
          class="sureBtn"
          type="primary"
          @click="sureToAdd"
          :disabled="Machinery || materialList.length < 1 || !boxStatus"
          >确认添加
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
//料箱
import {
  getDestinationList,
  getMaterialInfoByLabel,
} from "@/api/process/materialFlow";
import { getVehicleInfo } from "@/api/prepare";
import {
  backToStorageAPI,
  getStorageBoxesList,
  toOutBox,
  inBoxAPI,
} from "@/api/storage/in";
import { getStorageOrderInfo } from "@/api/storage/out";
import { useCommonStoreHook } from "@/store";

const commonS = useCommonStoreHook();

const boxSearch = ref("");
const deleteIndexOld = (index: any) => {
  outingMaterials.value.splice(index, 1);
  ElMessage.success("操作成功！");
};

const deleteIndexScanAdd = (index: any) => {
  materialList.value.splice(index, 1);
  ElMessage.success("操作成功！");
};
//硬件操作期间的状态:false 表示未有操作 true表示硬件在操作中
const Machinery = ref(false);
//盒内原有物料data
const boxesList = ref<any[]>([]);
//新加载具的开起状态
const addStatus = ref(false);
//新加载具的成功状态
const addSuccessStatus = ref(false);
//新加载具的内容
const addBoxInfo = ref();
//库中选中的item
const currentBox = ref<any>({});
//绑定当前盒子的状态
const boxStatus = ref(false);
const currentBoxIndex = ref(-1);
//库中选中的状态
const outStatus = ref(false);
//新扫时候的input值
const addBoxSearch = ref("");
const resetData = () => {
  addSuccessStatus.value = false;
  addBoxInfo.value = null;
  addBoxSearch.value = "";
  outingBox.value = {};
  outingRawBoxList = [];
  outingMaterials.value = [];
  materialList.value = [];
  currentBox.value = {};
  currentBoxIndex.value = -1;
  boxSearch.value = "";
  addStatus.value = false;
  outStatus.value = false;
  boxStatus.value = false;
};
const changeAddStatus = () => {
  if (addStatus.value == true) {
    resetData();
  } else {
    addStatus.value = !addStatus.value;
  }
};

//扫盒子
const addenterBox = () => {
  addBoxSearch.value = addBoxSearch.value.trim();
  getVehicleInfo(addBoxSearch.value ? addBoxSearch.value : {}).then((res) => {
    addBoxInfo.value = res.data;
    addSuccessStatus.value = true;
    outingBox.value.vehicleNo = addBoxInfo.value.code;
    outingBox.value.vehicleId = addBoxInfo.value.id;
    outingBox.value.houseNo = "1";
    ElMessage.success("扫码成功！");
    boxStatus.value = true;
  });
};
//出库
const enterBox = () => {
  boxSearch.value = boxSearch.value.trim();
  getStorageBoxesList(
    boxSearch.value ? { vehicleCode: boxSearch.value } : {}
  ).then((res) => {
    boxesList.value = res.data;
    commonS.orderInId = res.data.orderId;
  });
};
const clickBox = (box: any, index: number) => {
  currentBox.value = box;
  currentBoxIndex.value = index;
};
//出库操作
const sureToOut = async () => {
  let res = await toOutBox({
    vehicleNo: currentBox.value.vehicleNo,
    houseNo: currentBox.value.houseNo,
  });
  ElMessage.success("出库成功,等待料箱到达捡料位置");

  commonS.orderInId = res.data.orderId;
  commonS.changeBoxType = 1;
  Machinery.value = true;
  checkHasOuting();
  outStatus.value = true;
};
//定时器任务
let outInterval: number = -1;
const checkHasOuting = () => {
  //   点击出库之后，需要在其他地方（机器）确实已经到达检料位置，才能进行捡料
  //   接口需要传入出库outBox接口返回的orderId转为id传上去， 如果有这个orderId就开始轮询
  // 如果没有数据则停止轮询。数据返回的state是1处理中2启用3处理异常4已完成， 当为3或者4的时候停止轮询，并且在派发后清空oderid。
  if (commonS.orderInId != -1) {
    outInterval = setInterval(() => {
      getStorageOrderInfo({ id: commonS.orderInId })
        .then((res: any) => {
          if (res.data) {
            if (res.data.state === 3 || res.data.state === 4) {
              clearInterval(outInterval);
              commonS.orderInId = -1;
              if (commonS.changeBoxType === 1) {
                outingBox.value = currentBox.value;
                if (outingBox.value.list.length > 0) {
                  outingMaterials.value = outingBox.value.list;
                  outingRawBoxList = JSON.parse(
                    JSON.stringify(outingBox.value.list)
                  );
                } else {
                  outingRawBoxList = [];
                  outingMaterials.value = [];
                }
                getStorageBoxesList({}).then((res: any) => {
                  boxesList.value = res.data;
                });
                currentBoxIndex.value = -1;
                ElMessage.success("料箱已到达");
                Machinery.value = false;
                boxStatus.value = true;
              } else {
                resetData();
                getStorageBoxesList({}).then((res) => {
                  boxesList.value = res.data;
                });
                ElMessage.success("料箱入库成功");
                Machinery.value = false;
              }
            } else {
              outStatus.value = false;
              ElMessage.error(res.msg);
            }
          } else {
            clearInterval(outInterval);
          }
        })
        .catch(() => {
          clearInterval(outInterval);
          commonS.orderInId = -1;
          Machinery.value = false;
        });
    }, 5000);
  }
};
let outingRawBoxList: any[] = []; //确认添加的时候会对比捡料位和扫描的数量，多次点击会导致捡料位的数字一直改变，所以用一个变量来保存原始的捡料位数据
const outingBox = ref<any>({});
const outingMaterials = ref<any[]>([]);
const backToStorage = async () => {
  const { data } = await backToStorageAPI({
    vehicleCode: outingBox.value.vehicleNo,
    houseNo: outingBox.value.houseNo,
    detailsList: outingMaterials.value,
  });
  outingBox.value = {};
  outingMaterials.value = [];
  ElMessage.success("返库操作成功,等待料箱到达");
  commonS.changeBoxType = 2;
  commonS.orderInId = data.orderId;
  Machinery.value = true;
  checkHasOuting();
};

// 物料
const scanCodeInput = ref("");
//扫码后的array
const materialList = ref<any>([]);
// 扫码料码
const handleScanCodeInput = () => {
  getMaterialInfoByLabel(scanCodeInput.value).then((res) => {
    //seq是序列号唯一的
    if (res.data.codeType == "SEQ") {
      res.data.seqNo = scanCodeInput.value;
    } else {
      res.data.seqNo = "";
    }
    materialList.value.push({ ...res.data });
    scanCodeInput.value = "";
    ElMessage.success("扫码成功！");
  });
};
//确认添加:只是页面静态添加 不做接口发送
const sureToAdd = () => {
  for (let i = 0; i < materialList.value.length; i++) {
    let status = false;
    for (let b = 0; b < outingMaterials.value.length; b++) {
      if (materialList.value[i].seqNo != "") {
        outingMaterials.value.push({
          ...materialList.value[i],
          materialNo: materialList.value[i].materialCode,
          unit: materialList.value[i].unitDictValue,
        });
        status = true;
      } else {
        if (
          materialList.value[i].materialCode ==
            outingMaterials.value[b].materialNo &&
          materialList.value[i].materialName ==
            outingMaterials.value[b].materialName &&
          materialList.value[i].batchCode == outingMaterials.value[b].batchCode
        ) {
          outingMaterials.value[b].num =
            outingMaterials.value[b].num + materialList.value[i].num;
          status = true;
        }
      }
    }
    if (status == false) {
      outingMaterials.value.push({
        ...materialList.value[i],
        materialNo: materialList.value[i].materialCode,
        unit: materialList.value[i].unitDictValue,
      });
    }
  }
  materialList.value = [];
  ElMessage.success("添加成功！");
};
// 流转终点
const destinationList = ref([]);
onMounted(() => {
  getDestinationList(1).then((res) => {
    destinationList.value = res.data;
  });
  getStorageBoxesList({}).then((res) => {
    boxesList.value = res.data;
  });
  checkHasOuting();
});
</script>

<style lang="scss" scoped>
.type-title {
  font-weight: 500;
  font-size: 30px;
  color: rgba(0, 0, 0, 0.9);
  text-align: left;
  margin-bottom: 15px;
}

.base-container {
  width: 100%;
  margin-top: 15px;
  height: calc(100vh - 420px);
}

.boxes-container {
  .box-item {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 15px;
    padding: 10px 8px;
  }

  .box-selected {
    border: 2px solid #0a59f7;
  }
  .box-header {
    display: flex;
    justify-content: space-between;
  }
  .box-name {
    font-size: 20px;
    line-height: 40px;
  }

  .box-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bolder;
    font-size: 24px;
  }
}
.deleteSty {
  color: #0a59f7;
}
.outing-container {
  height: calc(100vh - 354px);

  .outing-box {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 15px;
    padding: 10px 8px;
  }
  .outing-box-header {
    display: flex;
    justify-content: space-between;
  }

  .material-title {
    font-weight: bolder;
    font-size: 24px;
    text-align: left;
  }

  .material-info {
    font-size: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .batchCode {
    max-width: 60%;
    flex-shrink: 0;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.list-container {
  width: 100%;
  display: grid;
  /*行间距*/
  grid-row-gap: 24px;
  /*列间距*/
  //grid-column-gap: 24px;

  grid-template-columns: 1fr;

  .list-box {
    height: 210px;
    background: #fff;
    border-radius: 16px 16px 16px 16px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: start;
    padding: 30px 30px;

    .list-box-header {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
    .list-box-delete {
      text-align: right;
      font-weight: bolder;
      font-size: 24px;
    }
    .name {
      font-weight: 500;
      font-size: 24px;
      color: rgba(0, 0, 0, 0.9);
      text-align: left;
    }

    .spec {
      font-size: 20px;
      color: rgba(0, 0, 0, 0.6);
      text-align: left;
    }

    .bottom {
      display: flex;
      justify-content: start;
      align-items: end;
    }

    .unit {
      font-weight: 500;
      font-size: 24px;
      color: rgba(0, 0, 0, 0.6);
      text-align: left;
      margin-left: 5px;
    }
  }
}

.destination {
  height: calc(100vh - 350px);
  margin-top: 15px;

  .end-box {
    height: 80px;
    background: #ffffff;
    border-radius: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 500;
    font-size: 24px;
    color: rgba(0, 0, 0, 0.9);
    display: flex;
    justify-content: space-evenly;
    align-items: center;
  }

  .end-box:not(:last-child) {
    margin-bottom: 15px;
  }

  .selected {
    border-radius: 40px;
    border: 2px solid rgba(10, 89, 247, 1);
  }

  .name {
    font-weight: 500;
    font-size: 24px;
    color: rgba(0, 0, 0, 0.9);
  }
}

.sureBtn {
  height: 80px;
  font-size: 24px;
  //background: #0a59f7;
  border-radius: 76px 76px 76px 76px;
  width: 100%;
  margin-top: 10px;
}
.addbox {
  margin-bottom: 10px;
  border-radius: 16px;
  background-color: white;
  text-align: center;
  padding: 20px 0;
  font-size: $f24;
}
</style>
