<template>
  <view class="lists">
    <StickyNavBar :class="{ meteringTab: current !== 0 }">
      <NavBar title="装箱"></NavBar>
      <view class="selectSheet">
        <u-tabs
          :list="list"
          :is-scroll="false"
          :current="current"
          @change="changeTab"
        ></u-tabs>
      </view>
      <view class="" v-if="current === 0">
        <view class="btn">
          <view class="boxSelect">
            <u-picker
              v-model="show"
              mode="selector"
              :default-selector="[0]"
              range-key="text"
              :range="actionSheetList"
              @confirm="actionSheetCallback"
            ></u-picker>
            <u-input
              v-model="form.ZZXFS"
              placeholder="请选择装箱方式"
              type="select"
              :border="true"
              @click="show = true"
            />
          </view>
          <uni-easyinput
            prefixIcon="search"
            class="topSearch"
            v-model="blNum"
            :disabled="form.ZZXFS == 'PL' || isEdit"
            focus
            placeholder="请扫描箱码"
            @change="handleInputNlpla"
          ></uni-easyinput>
          <uni-easyinput
            prefixIcon="search"
            :disabled="checkedBox"
            v-model="wxparams"
            :focus="isFocus"
            placeholder="请扫描产品包装条码/外箱码"
            @confirm="handleConfirm"
          ></uni-easyinput>
          <checkbox-group style="margin-top: 10rpx" @change="checkedChange">
            <checkbox value="r1" :checked="checkedBox" />是否审核
          </checkbox-group>
        </view>
        <view class="total">
          <view class="left">明细</view>
          <view class="right">
            数量：
            <text class="">{{ goodsList.length }}</text>
          </view>
        </view>
      </view>
    </StickyNavBar>
    <relationships
      v-show="current === 0"
      :list="goodsList"
      :isEdit="isEdit"
      @deleGonds="deleGonds"
    />
    <metering
      v-show="current === 1"
      :form="form"
      :isBL="isBL"
      :isEdit="isEdit"
      v-model="checkedBox"
      @plinput="changePLBLForm"
    />
    <unpacking v-show="current === 2" />
    <BottomBtn
      :btnArr="btnArr"
      @getBtnHandle="getBtnHandle"
      v-if="current !== 2"
    ></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 relationships from "./relationships.vue";
import metering from "./metering.vue";
import unpacking from "./unpacking.vue";
import { parseTime } from "@/utils/ruoyi";
import { requestMock } from "./mock";
export default {
  components: {
    StickyNavBar,
    ContentLoadingMore,
    BottomBtn,
    relationships,
    metering,
    unpacking,
  },
  data() {
    return {
      type: "select",
      show: false,
      border: true,
      // 是否编辑状态
      isEdit: false,
      isBL: false,
      list: [
        {
          name: "装箱关联",
        },
        {
          name: "计量称重",
        },
        {
          name: "解除装箱",
        },
      ],
      current: 0,
      checkedBox: false,
      status: "loadmore",
      btnArr: [
        {
          style: "",
          type: "warning",
          text: "返回",
          way: "goBack",
        },
        {
          style: "",
          type: "primary",
          text: "重置",
          way: "resetState",
        },
        {
          style: "",
          type: "primary",
          text: "提交",
          way: "goSubmit",
        },
      ],
      // 扫描的PL
      wxparams: "",
      // 扫描的BL
      blNum: "",
      isFocus: false,
      isDisabled: false,
      actionSheetList: [
        {
          text: "BL+PL",
        },
        {
          text: "PL",
        },
      ],
      form: {
        ZZXFS: "BL+PL",
        ZXSPE: "", //箱规格（cm）
        ZXVOLUM: "", //体积(m132)
        ZXNTGEW: "", //箱重（kg）
        NTGEW: "", //净重（kg）
        BRGEW: "", //毛重(kg)
        LONG: "", //长
        WIDE: "", //宽
        HIGH: "", //高
        UPDKZ: "I",
        DATUM: "", //扫描日期
        UZEIT: "", //扫描时间
        UNAME: "admin", //扫描人
        ZXTEXT: "",
        ZTEXT: "",
      },
      upForm: {},
      goodsList: [],
    };
  },
  computed: {},
  methods: {
    /**
     * 重置
     */
    resetState() {
      this.goodsList = [];
      this.blNum = "";
      this.wxparams = "";
      this.form = {
        ZZXFS: "BL+PL",
        PLNR: "",
        ZCODE: "",
        ZXSPE: "", //箱规格（cm）
        ZXVOLUM: "", //体积(m132)
        ZXNTGEW: "", //箱重（kg）
        NTGEW: "", //净重（kg）
        BRGEW: "", //毛重(kg)
        LONG: "", //长
        WIDE: "", //宽
        HIGH: "", //高
        UPDKZ: "I",
        DATUM: "", //扫描日期
        UZEIT: "", //扫描时间
        UNAME: "admin", //扫描人
        ZXTEXT: "",
        ZTEXT: "",
      };
      this.isBL = false;
      this.isEdit = false;
    },
    checkedChange() {
      this.checkedBox = !this.checkedBox;
    },
    searchCaseInfo(blpl, isMeter = false) {
      // 判空
      if (!blpl) return;
      // 是否BL
      const isBL = blpl.startsWith("BL");
      this.isBL = isBL;
      if (isBL) {
        this.blNum = blpl;
      }

      // 验证是否有重复
      if (this.goodsList.find((v) => v.PLNR == blpl || v.ZCODE == blpl)) {
        // this.$u.toast("请勿重复扫描！");
        return this.reset();
      }
      // 查询是否装箱
      const params = {
        ZCODE: isBL ? blpl : "",
        PLNR: isBL ? "" : blpl,
      };
      this.$u.api.sapApi.sapCaseInfo(params).then(({ DATA: res }) => {
        if (isMeter && !res.length) {
          this.$u.toast("当前条码未装箱，请先进行装箱！");
        } else if (isMeter && res.length) {
          // 如果扫码有数据，判断是否有称重信息
          console.log("-------object--------", this.upForm);
          const itm = res[0];
          const keys = ["LONG", "WIDE", "HIGH", "BRGEW", "ZXNTGEW"];
          if (!keys.some((v) => !!itm[v])) {
            keys.forEach((v) => (itm[v] = this.upForm[v]));
          }
        }

        // 如果已经装箱
        if (res.length) {
          this.isEdit = true;
          // 扫描的PL
          if (!isBL) {
            const [plInfo] = res;
            this.blNum = plInfo.ZCODE;
            // 如果有规格，需要解析出长宽高
            if (/^\d+\*\d+\*\d+$/.test(plInfo.ZXSPE)) {
              const [LONG, WIDE, HIGH] = plInfo.ZXSPE.split("*");
              plInfo.LONG = LONG;
              plInfo.WIDE = WIDE;
              plInfo.HIGH = HIGH;
            }
            this.goodsList.push({ ...plInfo, UPDKZ: "U" });
          } else {
            this.goodsList = res.map((v) => {
              // 如果有规格，需要解析出长宽高
              if (/^\d+\*\d+\*\d+$/.test(v.ZXSPE)) {
                const [LONG, WIDE, HIGH] = v.ZXSPE.split("*");
                v.LONG = LONG;
                v.WIDE = WIDE;
                v.HIGH = HIGH;
              }
              v.UPDKZ = "U";
              return v;
            });
          }

          this.checkedBox = res[0].ZSTATUS == "Y";
          this.form = this.goodsList[0];
        } else {
          if (!isBL) {
            console.log("没有装箱的PL");
            const plInfo = { PLNR: blpl, ZZXFS: this.form.ZZXFS, UPDKZ: "I" };
            // 获取已经扫描过的最后一个PL信息，如果存在需要他的称重信息
            const lastPLInfo = this.goodsList[this.goodsList.length - 1];
            console.log("lastPLInfo", lastPLInfo);
            const weightInfo = {
              ZXVOLUM: "",
              ZXNTGEW: "",
              NTGEW: "",
              BRGEW: "",
              LONG: "",
              WIDE: "",
              HIGH: "",
            };
            if (lastPLInfo) {
              weightInfo.ZXVOLUM = lastPLInfo.ZXVOLUM;
              weightInfo.ZXNTGEW = lastPLInfo.ZXNTGEW;
              weightInfo.NTGEW = lastPLInfo.NTGEW;
              weightInfo.BRGEW = lastPLInfo.BRGEW;
              weightInfo.LONG = lastPLInfo.LONG;
              weightInfo.WIDE = lastPLInfo.WIDE;
              weightInfo.HIGH = lastPLInfo.HIGH;
            }
            this.goodsList.push({ ...plInfo, ...weightInfo });
          } else {
            console.log("执行-----", this.isEdit);
            this.isEdit = false;
          }
          console.log("goodsList", this.goodsList, this.isEdit);
        }
      });
    },
    goSubmit() {
      if (this.goodsList.length === 0) {
        this.$u.toast("暂无提交数据");
        return;
      }

      if (!this.blNum && this.form.ZZXFS === "BL+PL") {
        this.$u.toast("请扫描箱码");
        return;
      }
      // 是否超过45kg
      let BRGEW = this.form.BRGEW;
      // if (this.form.ZZXFS === "BL+PL") {
      //   BRGEW = ;
      // } else {
      //   console.log(this.goodsList, "---------2222");
      //   this.goodsList.reduce((acc, cur) => acc + +cur.BRGEW, 0);
      // }
      if (BRGEW > 45) {
        uni.showModal({
          title: "提示",
          content: "毛重超过45KG，是否继续提交？",
          success: (res) => {
            if (res.confirm) {
              console.log("用户点击确定");
              this.subRequest();
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      } else {
        this.subRequest();
      }
    },
    // 请求发送
    subRequest() {
      const arr = [];
      const baseParams = {
        ZZXFS: this.form.ZZXFS,
        WERKS: this.vuex_user_factory, // 工厂
        ZXSPE: this.form.LONG + "*" + this.form.WIDE + "*" + this.form.HIGH, // 规格
        ZXVOLUM: (
          (+this.form.LONG * +this.form.WIDE * +this.form.HIGH) /
          1000000
        ).toFixed(6), // 体积
        NTGEW: (+this.form.BRGEW - this.form.ZXNTGEW).toFixed(2), // 净重
        DATUM: parseTime(new Date(), "{y}{m}{d}"),
        UZEIT: parseTime(new Date(), "{h}{i}{s}"),
        ZSTATUS: this.checkedBox ? "Y" : "N",
      };
      if (this.form.ZZXFS != "PL" && this.isEdit) {
        // 只传一条数据
        const editItem = this.goodsList[0];
        const addItems = this.goodsList.filter((v) => v.UPDKZ == "I");
        // 添加修改
        arr.push({ ...editItem, PLNR: "", ...baseParams });
        // 添加新增的数据
        arr.push(
          ...addItems.map((v) =>
            Object.assign(v, baseParams, {
              UNAME: this.vuex_user.userName,
              ZCODE: this.blNum,
            })
          )
        );
      } else if (this.form.ZZXFS == "BL+PL" && !this.isEdit) {
        console.log('新增-----');
        this.goodsList.forEach((ele) => {
          arr.push({
            ...ele,
            ...this.form,
            ...baseParams,
            PLNR: ele.PLNR,
            ZCODE: this.blNum,
            UNAME: this.vuex_user.userName,
          });
        });
        console.log(arr, 'arr0------');
      } else {
        this.goodsList.forEach((ele) => {
          arr.push({
            ...ele,
            ZCODE: this.blNum,
            PLNR: this.isEdit ? "" : ele.PLNR,
            UNAME: this.vuex_user.userName,
            ...baseParams,
          });
        });
      }
      this.$u.api.sapApi.sapCasePlnr(arr).then((res) => {
        if (!Array.isArray(res)) {
          return;
        }
        if (res.every((item) => item.TYPE === "S")) {
          this.$u.toast(res[0].MESSAGE);
          this.upForm = { ...this.form };
          this.$nextTick(() => {
            this.resetState();
          });
        }
        const foundObject = res.find((item) => item.TYPE === "E");
        if (foundObject && foundObject.MESSAGE) {
          this.$u.toast(foundObject.MESSAGE);
        }
      });
    },
    // 重置数据
    resetData() {
      this.$nextTick(() => {
        this.goodsList = [];
        this.form.brgew = "";
        this.current = 0;
      });
    },
    // 删除
    deleGonds(idx) {
      this.goodsList.splice(idx, 1);
    },
    /**
     * 扫描BL
     * 查询是否已经有装箱，有装箱情况只能做修改称重操作
     * @param {*} e
     */
    handleInputNlpla(e) {
      this.searchCaseInfo(e);
    },
    changePLBLForm(blpl) {
      console.log("changePLBLForm", "00000");
      const info = this.goodsList.find((v) => v.PLNR == blpl);
      if (info) {
        this.form = info;
      }
      this.searchCaseInfo(blpl, true);
    },
    reset() {
      setTimeout(() => {
        this.isFocus = true;
        this.isDisabled = false;
        this.wxparams = "";
      }, 1000);
    },
    handleConfirm(e) {
      this.isFocus = false;
      this.isDisabled = true;
      if (this.goodsList.some((item) => item === e)) {
        this.$u.toast("已经存在当前条码");
        this.reset();
        return;
      }
      this.searchCaseInfo(e);
      this.reset();
      return;
      e && this.goodsList.push(e);
      this.reset();
    },
    // 点击actionSheet回调
    actionSheetCallback(index) {
      this.form.ZZXFS = this.actionSheetList[index].text;
      if (this.form.ZZXFS === "PL") {
        this.blNum = "";
      }
    },
    // 加载更多
    onReachBottom() {
      console.log("加载更多inventoryCounting");
    },
    getBtnHandle(row) {
      console.log("getBtnHandle", row);
      this[row.way]();
    },
    goBack() {
      console.log("返回了");
      uni.navigateBack();
    },
    changeTab(index) {
      /**
       * 当装箱方式为PL时，如果有多个未装箱的，必须先提交装箱关联，才能进行称重
       */

      /**
       * 当称重切换装箱关联时
       * ...
       * 当装箱关联切换称重且有装箱关联数据时
       * 1、装箱方式为BL+PL时
       * -称重中应显当前BL的称重信息
       * 2、装箱方式为 PL 时
       * -如果只有一条PL时可以直接为当前PL进行称重
       * -如果有多条PL时，必须提交装箱关联才能称重
       */
      if (index == 1) {
        if (this.form.ZZXFS == "PL" && this.goodsList.length > 1) {
          return this.$u.toast("请先提交多个装箱关联！");
        } else if (this.goodsList.length == 1 || this.form.ZZXFS == "BL+PL") {
          this.form = this.goodsList[0] || this.form;
        }
      }
      this.current = index;
    },
  },
};
</script>

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

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

.contentMore {
  margin: 20rpx;
}

page {
  background: #f8f8f8;
}

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

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

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

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

.total {
  background: #fff;
  color: #000;
  padding: 0rpx 40rpx;
  display: flex;
  justify-content: space-between;
  font-size: 32rpx;

  .line {
    margin: 0px 10rpx;
  }
}

.meteringTab {
  // height: 200rpx;
  /deep/.u-sticky-wrap {
    height: 170rpx !important;
  }
}

.topSearch {
  margin-bottom: 20rpx;
}
</style>
