<template>
  <view class="lists page">
    <StickyNavBar class="listTitle">
      <NavBar title="销售拣货"></NavBar>
      <view class="headerTitle">
        <view class="items">交货单号：{{ vbeln }}</view>
        <view class="items">{{ saleInfo.KUNNR }} | {{ saleInfo.NAME1 }}</view>
        <view class="items">计划日期：{{ saleInfo.WADAT }}</view>
        <view class="items"
          >装箱数：{{ plslen }} / {{ Number(saleInfo.XSNUM) }}</view
        >
      </view>
      <view class="">
        <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="blue">{{ totalNum }}</text>
            <text class="line">/</text>
            <text class="">{{ goodsList.length }}</text>
          </view>
        </view>
      </view>
    </StickyNavBar>
    <ContentLoadingMore class="contentMore" :list="goodsList">
      <view class="cardbox">
        <view
          class="cardContent"
          v-for="(item, index) in goodsList"
          :key="item.PLNR"
        >
          <scanningList
            :item="item"
            :list="item.ZPLDT"
            @deleGonds="(idx) => deleGonds(item, idx)"
          />
        </view>
      </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 stockList from "./stockList.vue";
import { parseTime } from "@/utils/ruoyi";
export default {
  components: {
    StickyNavBar,
    ContentLoadingMore,
    BottomBtn,
    scanningList,
    stockList,
  },
  data() {
    return {
      value: "",
      type: "select",
      border: true,
      current: 0,
      status: "loadmore",
      btnArr: [
        {
          style: "",
          type: "primary",
          text: "保存",
          way: "goSave",
        },
        {
          style: "",
          type: "primary",
          text: "提交",
          way: "goSubmit",
        },
      ],
      isFocus: false,
      isDisabled: false,
      nlpla: "",
      wxparams: "",
      goodsList: [],
      pls: [], // 已经扫码的pl号
      resFlag: false,
    };
  },
  created() {},
  onLoad(option) {
    /**
     * 查询缓存中是否有单号，有单号读取扫描PL的数据
     */
    this.getInfo(option.order);
    this.vbeln = option.order;
  },
  computed: {
    totalNum() {
      const count = this.goodsList.filter((item) => item.checkedBox).length;
      return count || 0;
    },
    /**
     * 缓存的扫描过的pl条目
     */
    catchPL() {
      return this.vuex_sales_outbound[this.vbeln] || null;
    },
    plslen() {
      const codes = [];
      this.goodsList.forEach((cur) => {
        cur?.ZPLDT?.forEach((c) => {
          const code = c.ZCODE || c.PLNR;
          if (!codes.includes(code)) {
            codes.push(code);
          }
        });
      });
      return codes.length;
    },
    saleInfo() {
      return this.goodsList[0] || {};
    },
  },
  methods: {
    goSubmit() {
      if (!this.goodsList.length) return;
      if (this.resFlag) {
        return this.$u.toast("当前单据已经提交成功！无需继续提交！");
      }
      const flag = this.goodsList.every((ele) => {
        return (
          ele.sumNum == ele?.ZPLDT?.reduce((acc, cur) => acc + cur.PACMG, 0)
        );
      });

      if (!flag) {
        return this.$u.toast("请确认所有包装数量是否正确");
      }

      const params = this.goodsList.reduce((acc, cur, index) => {
        if (index == 0) {
          acc.push(JSON.parse(JSON.stringify(cur)));
        } else {
          const item = acc.find((v) => v.POSNR === cur.POSNR && v.ZSIZE == cur.ZSIZE);
          if (item) {
            item.ZPLDT.push(...cur.ZPLDT);
          } else {
            acc.push(JSON.parse(JSON.stringify(cur)));
          }
        }
        return acc;
      }, []);

      console.log(params, this.goodsList);

      // return

      this.$u.api.sapApi.sapPickingDn(params).then((res) => {
        this.loading = false;
        if (!Array.isArray(res)) {
          return;
        }
        const flag = res.some((item) => {
          const f = item.TYPE == "E";
          if (f) {
            this.$u.toast(item.MESSAGE);
          }
          return f;
        });
        if (!flag) {
          this.$u.toast("提交成功");
          // 如果有缓存PL，提交成功将要清楚当前缓存
          if (this.catchPL) {
            const sales_outbound = {
              ...this.vuex_sales_outbound,
            };
            delete sales_outbound[this.vbeln];
            this.$u.vuex("vuex_sales_outbound", sales_outbound);
          }
          setTimeout(() => {
            this.goBack();
          }, 1000);
        }
      });
    },
    goSave() {
      console.log(this.vuex_sales_outbound, "this.vuex_sales_outbound");
      // 缓存以单号为key，扫描的pl为value
      const pls = this.goodsList.reduce((acc, cur) => {
        cur.ZPLDT && acc.push(...cur.ZPLDT);
        return acc;
      }, []);
      const sales_outbound = {
        ...(this.vuex_sales_outbound || {}),
        [this.vbeln]: pls,
      };
      this.$u.vuex("vuex_sales_outbound", sales_outbound);
      this.$u.toast("保存成功！");
    },
    getInfo(VBELN) {
      this.$u.api.sapApi
        .sapSchDn({
          VBELN,
        })
        .then((res) => {
          this.initGoodsList(res.BKDT);
          console.log(this.catchPL, "this.catchPL");
          this.catchPL && this.setSalesBoundPL(this.catchPL);
        });
    },
    initGoodsList(arr) {
      // 有SIZE行就取ZINSNUM+ZLOSSC，没有SIZE行的就是取交货单行的LFIMG
      arr.forEach((ele) => {
        if (ele.ZSIZE.length) {
          this.goodsList.push(
            ...ele.ZSIZE.map((item) => {
              return {
                KDAUF: ele.KDAUF,
                KDPOS: ele.KDPOS,
                LFIMG: ele.LFIMG,
                MEINS: ele.MEINS,
                WERKS: ele.WERKS,
                ...item,
                KUNNR: ele.KUNNR,
                NAME1: ele.NAME1,
                WADAT: ele.WADAT,
                XSNUM: ele.XSNUM,
                MATNR: ele.MATNR,
                MAKTX: ele.MAKTX,
                sumNum: item.ZINSNUM + item.ZLOSSC,
              };
            })
          );
        } else {
          ele.ZSIZE = "";
          ele.sumNum = ele.LFIMG;
          // ele.ZINSNUM = ele.LFIMG;
          this.goodsList.push(ele);
          this.$u.toast(`物料编号：${ele.MATNR}--没有尺码信息`);
        }
      });
    },
    setSalesBoundPL(pls) {
      console.log(pls, "pls");
      // 循环BLPL合并相同的物料号和size
      pls.forEach((ele) => {
        if (!this.pls.includes(ele.PLNR) || !this.pls.includes(ele.ZCODE)) {
          ele.PLNR && this.pls.push(ele.PLNR);
          ele.ZCODE && this.pls.push(ele.ZCODE);
        }
        ele.TOMNG = ele.PACMG;
        const item = this.goodsList.find(
          (v) => v.ZSIZE == ele.ZSIZE && ele.MATNR == v.MATNR
        );
        ele.POSNR = item.POSNR
        if (item) {
          if (Reflect.has(item, "ZPLDT")) {
            item.ZPLDT.push(ele);
          } else {
            this.$set(item, "ZPLDT", [ele]);
          }
        }
      });
    },
    getPlnr(plnr) {
      const isBL = plnr.startsWith("B");
      let params = {
        ZCODE: isBL ? plnr : "",
        plnr: isBL ? "" : plnr,
        ztype: "005",
      };
      this.$u.api.sapApi.sapBlpl(params).then((res) => {
        if (res && res.MSG[0].TYPE === "S") {
          this.setSalesBoundPL(res.BLPL);
        } else {
          this.$u.toast(res.MSG[0].MESSAGE);
        }
        setTimeout(() => {
          this.isFocus = true;
          this.isDisabled = false;
          this.wxparams = "";
        }, 1000);
        this.loading = false;
      });
    },
    deleGonds(item, idx) {
      const currentPL = item.ZPLDT[idx];
      if (currentPL.ZCODE) {
        // 删除当前物料 与当前PL关联的所有BL
        item.ZPLDT = item.ZPLDT.filter((ele) => ele.ZCODE != currentPL.ZCODE);
        // 查询其他物料中是否有相同的ZCODE
        this.goodsList.forEach((ele) => {
          if (ele?.ZPLDT?.some((v) => v.ZCODE == currentPL.ZCODE)) {
            ele.ZPLDT = ele.ZPLDT.filter((v) => v.ZCODE != currentPL.ZCODE);
          }
        });
      } else {
        item.ZPLDT.splice(idx, 1);
      }
    },
    // 加载更多
    onReachBottom() {
      console.log("加载更多inventoryCounting");
    },
    getBtnHandle(row) {
      console.log("getBtnHandle", row);
      this[row.way]();
    },
    goBack() {
      console.log("进来");
      uni.navigateBack();
    },
    changeTab(index) {
      this.current = index;
    },
    handleInputNlpla(e) {},
    handleConfirm(e) {
      if (!e) return;
      this.isFocus = false;
      console.log(this.pls, "this.pls");
      if (this.pls.includes(e)) {
        return this.$u.toast("请勿重复扫描！");
      }
      this.getPlnr(e);
    },
  },
};
</script>

<style lang="scss">
.selectSheet {
  border-bottom: 1px solid #ccc;
}

/deep/ .u-sticky {
  top: 0 !important;
  background: #fff;
}

.tabTwo {
  /deep/ .u-sticky-wrap {
    height: 330rpx !important;
  }
}

.listTitle {
}

.contentMore {
  margin: 20rpx;
}

page {
  background: #f8f8f8;
}

.headerTitle {
  padding: 20rpx;
  font-weight: 600;

  .items {
    line-height: 40rpx;
  }
}

.btn {
  padding: 20rpx;
  background: #fff;

  .topSearch {
    margin-bottom: 20rpx;
  }
}

.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 - 410rpx);
  padding: 0rpx 20rpx;
  margin-top: 20rpx;
}

.cardContent {
  border-radius: 8px;
  background: #fff;
  margin-bottom: 20rpx;
}
</style>
