<template>
  <view class="page">
    <StickyNavBar>
      <NavBar title="成本中心领料"></NavBar>
      <view class="headerTitle">
        <view class="">
          <view class="items">领料申请：{{ goodsInfo.RSNUM }}</view>
          <view class="items"
            >{{ goodsInfo.KOSTL }} / {{ goodsInfo.KTEXT }}</view
          >
        </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";
import { parseTime } from "@/utils/ruoyi";

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: [],
      scanPLs: [],
    };
  },
  computed: {
    goodsInfo() {
      return this.goodsList[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.sapApi
        .sapSearchArbpl({
          RSNUM: applyNo,
        })
        .then((res) => {
          if (res.some((v) => v.TYPE === "E")) {
            // 查询出错
          } else {
            this.goodsList = res.map((v) => {
              v.details = [];
              return v;
            });
          }
        });
    },
    checkedChange() {
      this.checkedBox = !this.checkedBox;
    },
    getBtnHandle(row) {
      this[row.way]();
    },
    goBack() {
      console.log("进来");
      uni.navigateBack({
        delta: 1,
      });
    },
    goSubmit() {
      // 检查是否扫描PL
      if (!this.scanPLs.length) {
        return this.$u.toast("请扫描PL！");
      }

      // 可以少发，不可以超发
      if (
        this.goodsList.some((item) => {
          return (
            item.BDMNG <
            item.details.reduce((acc, cur) => {
              acc += +cur.ERFMG;
            }, 0)
          );
        })
      ) {
        return this.$u.toast("检查数量是否正确！");
      }

      // 获取items
      const items = this.goodsList.reduce((acc, cur) => {
        acc.push(
          ...cur.details.map((v) => {
            v.KOSTL = cur.KOSTL;
            return v;
          })
        );
        return acc;
      }, []);

      const params = {
        BLDAT: parseTime(new Date(), "{y}{m}{d}"),
        BUDAT: parseTime(new Date(), "{y}{m}{d}"),
        zencode: "A006",
        ZMARK: "A001",
        TYPE: "FL",
        item: items,
      };
      this.$u.api.sapApi.sapRrm([params]).then((res) => {
        this.loading = false;
        if (!Array.isArray(res)) {
          return;
        }
        const errObj = res.find((item) => item.TYPE === "E");
        if (errObj) {
          return this.$u.toast(errObj.MESSAGE);
        }
        // 提交成功 返回上一个页面
        this.$u.toast("提交成功！", 3000, {
          icon: "success",
          mask: true,
          complete: () => {
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 3000);
          },
        });
      });
    },

    handleConfirm(e) {
      if (this.scanPLs.includes(e)) {
        return this.$u.toast("请勿重复扫描！");
      }
      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") {
            this.handlePL(res.BLPL, plnr);
            this.reset();
          } else {
            this.reset();
            this.$u.toast(res.MSG[0].MESSAGE);
          }
          this.loading = false;
        });
    },
    handlePL(blpls, plnr) {
      // 过滤与当前pl相同的物料
      const [blpl] = blpls;
      // 分配数量
      blpl.ERFMG = blpl.PACMG;
      const items = this.goodsList.filter((v) => v.MATNR == blpls[0].MATNR);
      // 如果没有匹配到PL
      if (!items.length) return this.$u.toast("没有匹配到PL对应的物料！");
      // 保存已经扫描过的 pl
      this.scanPLs.push(plnr);
      /**
       * 如果超过两个相同的物料，就按照项次依次分配、拆分
       */
      if (items.length > 1) {
        while (blpl.ERFMG > 0) {
          let bdmng = 0;
          // 查询需求数量与pl数量总和不等的物料
          const item = items.find((v) => {
            const total = v.details.length
              ? v.details.reduce((acc, cur) => (acc + +cur.ERFMG).toFixed(3), 0)
              : 0;
            bdmng = (v.BDMNG - total).toFixed(3);
            return bdmng > 0;
          });
          const splitBlpl = this.$u.deepClone(blpl);
          // 如果需求数量 大于剩余的数量
          if (bdmng > blpl.ERFMG) {
            blpl.ERFMG = 0;
          } else {
            splitBlpl.ERFMG = bdmng;
            blpl.ERFMG = (blpl.ERFMG - bdmng).toFixed(3);
          }
          splitBlpl.PACMG = splitBlpl.ERFMG;
          item.details.push(splitBlpl);
        }
      } else {
        const [item] = items;
        item.details.push(blpl);
      }
    },
  },
};
</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>
