<template>
  <view class="page">
    <StickyNavBar>
      <NavBar title="完工入库扫描"></NavBar>
      <FactorySelect
        v-model="LGOBE"
        @change="actionSheetCallback"
        :options="options"
      />

      <!-- <view class="selectSheet">
				<u-row >
					<u-col span="12">
						<u-picker v-model="depotShow" mode="selector" :default-selector="[0]" range-key="text" :range="depotLists" @confirm="actionSheetCallback"></u-picker>
						<u-input v-model="LGOBE" placeholder="请选择仓库别" :type="type" :border="border" @click="depotShow = true" />
					</u-col>
				</u-row>
			</view> -->
      <view class="btn">
        <uni-easyinput
          v-if="vuex_user_factory !== '1010'"
          prefixIcon="search"
          class="topSearch"
          :disabled="nlplaDisabled"
          v-model="nlpla"
          focus
          placeholder="请扫描库位"
          @change="handleInputNlpla"
        ></uni-easyinput>
        <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">{{ goodsList.length }}</text>
          <text class="line">|</text>
          总数量：
          <text class="blue">{{ totalNum }}</text>
        </view>
      </view>
    </StickyNavBar>
    <ContentLoadingMore class="cardbox" :list="goodsList">
      <view class="cardContent" v-for="(item, index) in goodsList">
        <scanningList
          :item="item"
          :idx="index"
          @deleGonds="deleGonds"
          :list="list"
        />
      </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 { parseTime } from "@/utils/ruoyi";
import scanningList from "./scanningList.vue";
import FactorySelect from "@/components/FactorySelect/FactorySelect.vue";

export default {
  components: {
    StickyNavBar,
    ContentLoadingMore,
    BottomBtn,
    scanningList,
  },
  data() {
    return {
      number: 0,
      show: true,
      nlpla: "",
      wxparams: "",
      nlplaDisabled: false,
      warehouseCode: "",
      btnArr: [
        {
          style: "",
          type: "warning",
          text: "返回",
          way: "goBack",
        },
        {
          style: "",
          type: "primary",
          text: "提交",
          way: "goSubmit",
        },
      ],
      goodsList: [],
      isFocus: false,
      isDisabled: false,
      depotShow: false,
      depotLists: [],
      LGOBE: "",
      LGORT: "",
      type: "select",
      border: true,
      list: [],
      options: [
        {
          WERKS: "1000",
          LGORT: "S000",
          LGOBE: "发运仓",
          label: "S000-发运仓",
          value: "S000",
        },
      ],
    };
  },
  created() {
    // 二维码包含：10位物料号（右对齐不足补充为0）物料号12位生产单号（右对齐不足补充为0），
    // 10位批次号（右对齐不足补充为0），8位数量（100000.0）（右对齐不足补充为0）
    // this.getPlnr('006000000100100000000300000501001');
  },
  computed: {
    totalNum() {
      let num = 0;
      this.list.forEach((ele) => {
        num += ele.totalQuantity;
      });
      return num;
    },
  },
  methods: {
    // 点击actionSheet回调
    actionSheetCallback(item) {
      this.LGORT = item?.LGORT || "";
    },
    deleGonds(idx) {
      this.goodsList.splice(idx, 1);
    },
    getBtnHandle(row) {
      this[row.way]();
    },
    goBack() {
      uni.navigateBack();
    },
    goSubmit() {
      if (!this.goodsList.length) return;

      let params = [];
      //   this.list.forEach((ele) => {
      //     item.push({
      //       AUFNR: ele.workorderNo,
      //       PLNR: ele.qrcode,
      //       MATNR: ele.sapItemCode,
      //       WERKS: this.vuex_user_factory,
      //       LGORT: this.LGORT,
      //       PACKNR: ele.qrcode,
      //       ZSIZE: ele.standardSize,
      //       ZINSTNUM: ele.clientCmd,
      //       BRGEW: ele.grossWeight,
      //       NTGEW: ele.netWeight,
      //       GEWEI: ele.unitOfMeasure,
      //       INSNAM: ele.checkBy,
      //       TOMNG: ele.totalQuantity,
      //       ZMNGO: ele.quantity,
      //       ZMNGL: ele.lossNum,
      //       NLPLA: ele.NLPLA,
      //     });
      //   });
      const items = this.list.reduce(
        (pre, cur) => {
          pre.item.push({
            AUFNR: cur.workorderNo,
            PLNR: cur.qrcode,
            MATNR: cur.sapItemCode,
            WERKS: this.vuex_user_factory,
            LGORT: this.LGORT,
            PACKNR: cur.qrcode,
            ZSIZE: cur.standardSize,
            ZINSTNUM: cur.clientCmd,
            BRGEW: cur.grossWeight,
            NTGEW: cur.netWeight,
            GEWEI: cur.unitOfMeasure,
            INSNAM: cur.checkBy,
            TOMNG: cur.totalQuantity,
            ZMNGO: cur.quantity,
            ZMNGL: cur.lossNum,
            ZSAMNUM: cur.sampleNum,
            NLPLA: cur.NLPLA,
            ZCODE: cur.blQrcode,
          });
          // 装箱信息
          if (pre.zcode.findIndex((v) => v.ZCODE == cur.blQrcode) == -1) {
            pre.zcode.push({
              ZCODE: cur.blQrcode,
              ZXSPE: cur.packageStandard,
              ZXVOLUM: cur.packVolume,
              ZXNTGEW: cur.boxWeight,
              NTGEW: cur.netWeight,
              BRGEW: cur.grossWeight,
              ZXTEXT: cur.remark,
              KUNNR: cur.clientCode,
              ZPRINT: cur.templateStandard,
              ZPRNTDA: cur.printDate,
              ZPRNTTI: cur.printTime,
              ZPRNTER: cur.printBy,
              UNAME: cur.createBy,
              DATUM: cur.createDate,
              UZEIT: cur.createTime,
            });
          }
          return pre;
        },
        { item: [], zcode: [] }
      );
      params.push({
        lfsnr: this.goodsList[0].workorderNo,
        // BLDAT: 20240420,
        // BUDAT: 20240420,
        BLDAT: parseTime(new Date(), "{y}{m}{d}"),
        BUDAT: parseTime(new Date(), "{y}{m}{d}"),
        ...items,
      });
      this.$u.api.sapApi.sapOrder(params).then((res) => {
        this.loading = false;
        if (!Array.isArray(res)) {
          return;
        }
        if (res.every((item) => item.TYPE === "S")) {
          this.goodsList = [];
          this.LGOBE = "";
          this.LGORT = "";
          this.nlpla = "";
          this.wxparams = "";
          this.$u.toast("提交成功");
        }
        const foundObject = res.find((item) => item.TYPE === "E");
        if (foundObject && foundObject.MESSAGE) {
          this.$u.toast(foundObject.MESSAGE);
        }
      });
    },
    handleConfirm(e) {
      e && this.getPlnr(e);
    },
    handleInputNlpla(e) {
      console.log(`output->e`, e);
      this.nlplaDisabled = !!e;
    },
    reset() {
      setTimeout(() => {
        this.wxparams = "";
        this.isFocus = true;
        this.isDisabled = false;
      }, 1000);
    },
    getPlnr(qrcode) {
      this.isDisabled = true;
      this.isFocus = false;
      if (!this.nlpla && this.vuex_user_factory !== "1010") {
        this.$u.toast("请先扫描仓位");
        this.reset();
        return;
      }
      // if(!this.nlpla){
      // 	this.$u.toast('请先扫描仓位');
      // 	this.reset()
      // 	return
      // }
      this.$u.api.mesApi
        .pdaFindPackageLinkInfo({
          qrcode,
        })
        .then((res) => {
          if (res && res.code == 200) {
            // if (this.goodsList.some((item) => item.workorderNo !== res.data[0].workorderNo)) {
            // 	this.$u.toast('请扫描同一个工单');
            // 	this.reset()
            // 	return
            // }
            if (this.goodsList.some((item) => item.qrcode === qrcode)) {
              this.$u.toast("已经存在当前条码");
              this.reset();
              return;
            }
            res.data.forEach((ele) => {
              this.nlpla && (ele.NLPLA = this.nlpla?.trim());
            });
            this.list = this.list.concat(res.data);

            const result = res.data.filter((item, index, self) => {
              return self.findIndex((t) => t.qrcode === item.qrcode) === index;
            });
            this.goodsList = this.goodsList.concat(result);
            this.reset();
          } else {
            this.reset();
            this.$u.toast(res.msg);
          }
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.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: #000;
    font-size: 28rpx;
    font-weight: 500;
    word-break: break-all;
  }
}
.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;
}
.selectSheet {
  padding: 20rpx 10rpx;
  padding-bottom: 0;
  background: #fff;
}
</style>
