<template>
  <view class="page">
    <StickyNavBar>
      <NavBar title="生产发料"></NavBar>
      <view class="headerTitle">
        <view class="">
          <view class="items"
            >领料申请:{{ goodsInfo.applyNo }}</view
          >
          <view class="items"
            >{{ goodsInfo.workstationCode }}/{{
              goodsInfo.workstationName
            }}</view
          >
          <view class="items"
            >计划日期:{{ goodsInfo.startTime }}</view
          >
        </view>
        <view class="checkedCase">
          <checkbox-group @change="checkedChange">
            <checkbox value="r1" :checked="checkedBox" />是否结案
          </checkbox-group>
        </view>
      </view>
      <view class="btn">
        <uni-easyinput
          prefixIcon="search"
          :disabled="isDisabled"
          v-model="wxparams"
          :focus="isFocus"
          placeholder="请扫描产品包装条码/外箱码"
		  @confirm="handleConfirm"
        ></uni-easyinput>
      </view>
      <view class="total">
        <view class="left">物料明细</view>
        <view class="right">
          物料数量：
          <text class="">{{ goodsList.length }}</text>
        </view>
      </view>
    </StickyNavBar>
    <ContentLoadingMore class="cardbox" :list="goodsList">
      <view class="cardContent" v-for="(item, index) in goodsList" :key="index">
        <scanningList :item="item" :list="item.details" />
      </view>
    </ContentLoadingMore>
    <BottomBtn :btnArr="btnArr" @getBtnHandle="getBtnHandle"></BottomBtn>
  </view>
</template>

<script>
import StickyNavBar from "@/components/StickyNavBar/index.vue";
import ContentLoadingMore from "@/components/ContentLoadingMore/index.vue";
import BottomBtn from "@/components/BottomBtn/index.vue";
import scanningList from "./scanningList.vue";
export default {
  components: {
    StickyNavBar,
    ContentLoadingMore,
    BottomBtn,
    scanningList,
  },
  data() {
    return {
      checkedBox: false,
      r1: "",
      // totalNum: 0,
      number: 0,
      show: true,
      nlpla: "YD-02-02-3",
      wxparams: "",
      btnArr: [
        {
          style: "",
          type: "warning",
          text: "返回",
          way: "goBack",
        },
        {
          style: "",
          type: "primary",
          text: "提交",
          way: "goSubmit",
        },
      ],
      goodsList: [],
      isFocus: true,
      isDisabled: false,
      OrderNum: "",
      list: [],
    };
  },
  computed: {
    goodsInfo() {
      return this.goodsList[0] || {}
    },
    totalNum() {
      let num = 0;
      let i = null,
        j = null;
      const data = JSON.parse(JSON.stringify(this.list));
      const result = data.filter((item, index, self) => {
        return self.findIndex((t) => t.itemCode === item.itemCode) === index;
      });
      for (i = 0; i < this.goodsList.length; i++) {
        if (
          this.goodsList[i].itemCode === result[i].itemCode &&
          result[i].vista
        ) {
          num++;
        }
      }
      return num || 0;
    },
  },
  onLoad(option) {
    if (option && option.order) {
      this.OrderNum = option.order;
      this.getOrder(option.order);
    }
  },
  watch: {},
  created() {},
  methods: {
    reset() {
      setTimeout(() => {
        this.wxparams = "";
        this.isFocus = true;
        this.isDisabled = false;
      }, 1000);
    },
    getOrder(applyNo) {
      this.$u.api.mesApi
        .pdaMaterialcreate({
          pageNum: 1,
          pageSize: 10,
          applyNo,
        })
        .then((res) => {
          if (res && res.code - 200 === 0) {
            this.goodsList = res.rows.reduce((acc, cur) => {
              if (acc.length === 0) {
                acc.push({
                  ...cur,
                  details: [{ ...cur, vista: 0 }],
                });
              } else {
                const item = acc.find((v) => v.sapItemCode == cur.sapItemCode);
                if (item) {
                  item.details.push({ ...cur, vista: 0 });
                } else {
                  acc.push({
                    ...cur,
                    details: [{ ...cur, vista: 0 }],
                  });
                }
              }
              return acc;
            }, []);

            console.log(this.goodsList, "----")
          } else {
            this.$u.toast(res.msg);
          }
          this.loading = false;
        });
    },
    checkedChange() {
      this.checkedBox = !this.checkedBox;
    },
    getBtnHandle(row) {
      this[row.way]();
    },
    goBack() {
      console.log("进来");
      uni.navigateBack({
        delta: 1,
      });
    },
    goSubmit() {
      const flag = this.goodsList.every((item) => {
        return item.details.every(v => v.PLNR)
      })

      if (!flag) {
        return this.$u.toast("请扫描产品包装条码/外箱码");
      }

      let arr = this.goodsList.reduce((acc, cur) => {
        acc.push(...cur.details)
        return acc
      }, [])

      // "windCase": null,是否结案   Y是  N否
      arr.forEach((ele, index) => {
        ele.windCase = this.checkedBox ? "Y" : "N";
        ele.AUFNR = ele.workorderCode;
        ele.ERFMG = ele.vista;
        ele.MTSNR = ele.applyNo;
        ele.ZEILE = index + 1;
        ele.RSNUM = ele.requirementNumber;
        ele.RSPOS = ele.requirementProjectNumber;
      });
      const params = {
        zencode: "A008",
        item: arr,
      };

      console.log(arr, '----')
      this.$u.api.sapApi.sapProiss(params).then((res) => {
        this.loading = false;
        if (!Array.isArray(res)) {
          return;
        }
        if (res.every((item) => item.TYPE === "S")) {
          // this.$u.toast('提交成功');
          this.handleMes(arr, res[0].MESSAGE_V1);
        }
        const foundObject = res.find((item) => item.TYPE === "E");
        if (foundObject && foundObject.MESSAGE) {
          this.$u.toast(foundObject.MESSAGE);
        }
      });
    },
    handleMes(arr, num) {
      arr.forEach((ele) => {
        ele.batchCode = ele.CHARG;
        ele.quantityIssued = ele.vista;
        ele.issueCode = num;
        ele.issueType = ele.materialType;
      });
      this.$u.api.mesApi.pdaSapissuecreate(arr).then((res) => {
        this.loading = false;
        console.log(res);
        if (res && res.code == 200) {
          this.$u.toast("提交成功");
          setTimeout(() => {
            this.goBack();
          }, 3000);
        } else {
          this.$u.toast(res.msg);
        }
      });
    },
    handleConfirm(e) {
      e && this.getPlnr(e);
    },
    getPlnr(plnr) {
      this.isDisabled = true;
      this.isFocus = false;
      this.$u.api.sapApi
        .sapBlpl({
          plnr,
          ztype: "002",
        })
        .then((res) => {
          if (res && res.MSG[0].TYPE === "S") {
            if (
              this.goodsList.some((item) =>
                item.details.some((v) => v.PLNR == plnr)
              )
            ) {
              this.reset();
              this.$u.toast("已经存在当前条码");
              return;
            }

            this.handleDetails(res.BLPL, plnr);

            this.reset();
          } else {
            this.reset();
            this.$u.toast(res.MSG[0].MESSAGE);
          }
          this.loading = false;
        });
    },
    handleDetails(data, plnr) {
      data.forEach((ele) => {
        let num = ele.PACMG;
        // 相同的物料
        const item = this.goodsList.find((v) => v.sapItemCode == ele.MATNR);

        if (item) {
          // 用于缓存新添加的 details
          const map = new Map();
		  
		  console.log(item, '-----')

          item.details.some((v, i) => {
            // 如果没有数量了，终止分配
            if (num <= 0) return true;

            // 没有分配数量时
            if (v.vista == 0) {
              // 如果是最最后一项 直接分配所有的数量
              if (i == item.details.length - 1) {
                v.vista = num;
              } else {
                v.vista = num > v.applyNum ? v.applyNum : num;
              }
              num = +(num - v.vista).toFixed(3);
              // v.CHARG = ele.CHARG;
              // v.PLNR = plnr;
              // v.LGORT = ele.LGORT;
              // v.LGOBE = ele.LGOBE;
              // v.NLPLA = ele.NLPLA;
              Object.assign(v, ele);
              // 添加两个字段，使用数量和剩余数量
              v.usedNum = v.vista;
              v.remainNum = +(v.applyNum - v.usedNum).toFixed(3);
            } else if (v.remainNum > 0) {
              // 已经分配，但是未分配满的情况 需要创建一条新的申请
              let vista = 0;

              // 如果是最后一项，直接分配所有的数量
              if (i == item.details.length - 1) {
                vista = num;
              } else {
                // 如果下项的工单号于目前工单号一样跳过
                if (v.workorderCode == item.details[i + 1].workorderCode) {
                  return false;
                }
                vista = num > v.remainNum ? v.remainNum : +num;
              }
              const reAddItem = {
                ...v,
                ...ele,
                usedNum: +(v.usedNum + vista).toFixed(3),
                remainNum: +(v.remainNum - vista).toFixed(3),
                vista,
              };
              map.set(i + 1, reAddItem);
              num = +(num - vista).toFixed(3);
            }
          });
          // 新增的申请插入到明细中
          for (const [key, value] of map.entries()) {
            item.details.splice(key, 0, value);
          }
        } else {
          this.$u.toast("没有物料");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  background: #f8f8f8;
}
.headerTitle {
  padding: 20rpx;
  font-weight: 600;
  .items {
    line-height: 40rpx;
  }
}
.btn {
  padding: 20rpx;
  background: #fff;
  .topSearch {
    margin-bottom: 20rpx;
  }
}
.bottomBtn {
  position: sticky;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  background: #fff;
  bottom: 0rpx;
  margin-top: 20rpx;
  .u-btn {
    width: 300rpx;
  }
}
.blue {
  color: #3f9dcc;
}
.total {
  background: #fff;
  color: #000;
  padding: 0rpx 40rpx;
  display: flex;
  justify-content: space-between;
  font-size: 32rpx;
  .line {
    margin: 0px 10rpx;
  }
}
.cardbox {
  min-height: calc(100vh - 480rpx);
  padding: 0rpx 20rpx;
  margin-top: 20rpx;
}
.cardContent {
  border-radius: 8px;
  background: #fff;
  margin-bottom: 20rpx;
}
.listItemTitle {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  border-bottom: 2px solid #f8f8f8;
  .u-btn {
    width: 150rpx;
    margin: 0px;
    margin-top: 10rpx;
  }
  .item {
    line-height: 50rpx;
    color: #333;
    font-size: 28rpx;
    font-weight: 500;
    word-break: break-all;
    font-weight: 600;
  }
}
.listBottom {
  .bottomTitle {
    height: 80rpx;
    position: relative;
    .desc {
      color: #bbb;
      font-size: 24rpx;
      line-height: 80rpx;
      padding-left: 20rpx;
    }
    .topIcons {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      color: #aaa;
    }
  }
  .bottomBox {
    padding: 20rpx;
    .bottomItem {
      background: #f8f8f8;
      padding: 20rpx;
      margin-bottom: 20rpx;
      .items {
        color: #333;
        font-size: 24rpx;
        height: 40rpx;
        line-height: 40rpx;
      }
    }
  }
}
/deep/ .u-sticky {
  top: 0 !important;
  background: #fff;
}
.checkedCase {
  margin-top: 10rpx;
}
</style>
