<template>
  <view class="mainBox">
    <uni-nav-bar fixed="true" statusBar="true" :title="`批次号信息`">
      <template slot="left">
        <u-button
          size="small"
          class="u-reset-button"
          @click="cancel"
          text="取消"
        ></u-button
      ></template>
      <!--右菜单-->
      <template slot="right">
        <u-button
          type="success"
          size="small"
          class="u-reset-button"
          @click="handleSave"
          text="保存"
        ></u-button>
      </template>
    </uni-nav-bar>
    <view class="wrapper">
      <u-form
        labelPosition="left"
        :model="warehousingMaterialList[curIndex]"
        ref="lisrFormRef"
        labelWidth="350"
        :rules="rules"
        errorType="none"
        labelAlign="left"
        :labelStyle="{
          fontSize: '24rpx',
        }"
      >
        <view class="title"
          >{{ baseInfo.assetName }}&nbsp;&nbsp;{{ baseInfo.assetCode }}</view
        >
        <view class="cell">
          <u-form-item
            style="width: 100%"
            required
            label="包装数量"
            prop="outInNum"
          >
            <u-input
              disableColor="#ffffff"
              type="number"
              @change="unpdateMaterialCode"
              placeholder="请输入"
              v-model="warehousingMaterialList[curIndex].outInNum"
          /></u-form-item>
        </view>
        <view class="cell">
          <u-form-item
            style="width: 100%"
            required
            label="批次号"
            prop="batchNum"
          >
            <u-input
              @change="unpdateMaterialCode"
              disableColor="#ffffff"
              type="text"
              placeholder="请输入"
              v-model="warehousingMaterialList[curIndex].batchNum"
          /></u-form-item>
        </view>
        <view class="cell">
          <u-form-item
            required
            style="width: 100%"
            label="最小单元"
            prop="measurementUnit"
          >
            <u-input
              disableColor="#ffffff"
              @change="unpdateMaterialCode"
              type="number"
              placeholder="请输入"
              v-model="warehousingMaterialList[curIndex].measurementUnit"
            >
              <template slot="suffix"
                >{{ baseInfo.unit }} /{{ baseInfo.minPackUnit }}</template
              ></u-input
            ></u-form-item
          >
        </view>
        <view class="cell" v-if="assetType == 3">
          <u-form-item style="width: 100%" label="质检单">
            <UploadFileNew
              v-model="warehousingMaterialList[curIndex].contentImage"
              fileMediatype="image"
              mode="grid"
              disable-preview
              limit="1"
              :imageStyles="{
                width: 80,
                height: 40,
                border: 'none',
              }"
            >
              上传图片
            </UploadFileNew></u-form-item
          >
        </view>
        <view
          class="cell"
          :key="warehousingMaterialList[curIndex].cargoSpaceCode"
        >
          <u-form-item
            required
            style="width: 100%"
            label="货位"
            labelWidth="250"
            prop="cargoSpaceCode"
            :key="forceUpdate"
          >
            <view
              class="cargoSpaceCode text-primary"
              @click="handleWarehouseChoose"
              :key="warehousingMaterialList[curIndex].cargoSpaceCode"
              >{{
                warehousingMaterialList[curIndex].cargoSpaceCode
                  ? `${warehousingMaterialList[curIndex].warehouseName}-${warehousingMaterialList[curIndex].areaName}-${warehousingMaterialList[curIndex].shelfCode}-${warehousingMaterialList[curIndex].cargoSpaceCode}`
                  : "仓库-库位-货架-货位"
              }}</view
            >
          </u-form-item>
        </view>
      </u-form>
      <view class="bucket-wrapper" :key="forceUpdate">
        <view class="operation">
          <!-- <u-button type="success" size="small" @click="getMaterialCode"
            >生成明细</u-button
          > -->
          <text class="text-primary" @click="chooseAssets" v-if="bizScene == 5"
            >选择资产编号</text
          >
          <text
            class="text-primary"
            @click="setDate"
            v-if="
              bizScene != 5 &&
              warehousingMaterialList[curIndex].warehouseLedgerDetails &&
              warehousingMaterialList[curIndex].warehouseLedgerDetails.length
            "
            >批量设置日期</text
          >
        </view>
        <view class="self-table">
          <view class="self-tr">
            <view class="th check" v-if="bizScene != 5"
              ><checkbox
                @click="checkAll = !checkAll"
                :checked="checkAll"
              ></checkbox
            ></view>
            <view class="th code"
              >{{ getDictValue("物品类型", baseInfo.assetType) }}编码</view
            >
            <view class="th num">包装编码</view>
            <view class="th date-picker"
              ><uni-data-select
                style="width: 100rpx"
                :localdata="[
                  { value: 'manufactureTime', text: '生产日期' },
                  { value: 'procurementTime', text: '采购日期' },
                ]"
                :clear="false"
                :disabled="bizScene == 5"
                v-model="curDateType"
            /></view>
          </view>
          <checkbox-group @change="selectionChange" v-if="!showLoading">
            <view
              class="self-tr bg"
              v-for="(item, index) in (
                warehousingMaterialList[curIndex].warehouseLedgerDetails || []
              ).slice(0, page * 15)"
              :key="index"
            >
              <view class="th check" v-if="bizScene != 5"
                ><checkbox
                  :value="index + ''"
                  :checked="selection.find((i) => i == index) !== undefined"
                ></checkbox
              ></view>
              <view class="th code">{{ item.onlyCode }}</view>
              <view class="th num">{{ item.num }}</view>
              <view class="th date-picker"
                ><template v-if="bizScene == 5">
                  {{ item[curDateType] }}
                </template>
                <uni-datetime-picker
                  v-else
                  type="datetime"
                  :key="forceUpdate"
                  v-model="item[curDateType]"
                  @change="() => handleDateChange(item)"
              /></view>
            </view>
            <u-loadmore
              fontSize="32"
              iconSize="36"
              v-if="warehousingMaterialList[curIndex].warehouseLedgerDetails"
              :status="loadingMore"
            />
          </checkbox-group>
          <u-loading-icon text="更新中" textSize="30" v-else></u-loading-icon>
        </view>
      </view>
    </view>
    <u-popup :show="popupShow" mode="center">
      <view class="time-container">
        <view class="title">选择时间</view>
        <uni-datetime-picker type="datetime" v-model="batchTime" />
      </view>
      <view class="time-footer">
        <u-button @click="popupShow = false">取消</u-button>
        <u-button type="success" @click="confirm">确认</u-button>
      </view>
    </u-popup>
    <WarehouseChoose ref="warehouseChooseRef" />
    <ReturnSelect ref="returnSelectRef" />
  </view>
</template>

<script>
import ReturnSelect from "./components/ReturnSelect";
import WarehouseChoose from "@/components/WarehouseChoose";
import { warehousingType, tableContentData } from "../enum.js";
import UploadFileNew from "@/components/UploadFileNew";
import { post, postJ, get } from "@/utils/api.js";
import dictMixins from "@/mixins/dictMixins";

let timer = null;
let lastNum = 0;
export default {
  mixins: [dictMixins],
  components: {
    WarehouseChoose,
    ReturnSelect,
    UploadFileNew,
  },
  data() {
    return {
      popupShow: false,
      forceUpdate: false,
      batchTime: "",
      curDateType: "manufactureTime",
      baseInfo: {},
      bizScene: "",
      assetType: "",
      curIndex: "",
      rules: {
        cargoSpaceCode: {
          type: "string",
          required: true,
          trigger: ["blur", "change"],
        },
        measurementUnit: {
          type: "string",
          required: true,
          trigger: ["blur", "change"],
        },
        outInNum: {
          type: "string",
          required: true,
          trigger: ["blur", "change"],
        },
        batchNum: {
          type: "string",
          required: true,
          trigger: ["blur", "change"],
        },
      },
      selection: [],
      isScan: false,
      showLoading: false,
      page: 1,
    };
  },
  //加载更多
  onReachBottom() {
    console.log("onReachBottom");
    this.page++;
  },
  //选择的列表长度
  computed: {
    loadingMore() {
      return this.page * 15 <
        this.warehousingMaterialList[this.curIndex].warehouseLedgerDetails
          .length
        ? "loading"
        : "nomore";
    },
    checkAll: {
      set(val) {
        if (val) {
          this.selection =
            this.warehousingMaterialList[
              this.curIndex
            ]?.warehouseLedgerDetails?.map((i, index) => index + "") || [];
        } else {
          this.selection = [];
        }
      },
      get() {
        return !!(
          this.selection.length &&
          this.selection.length ==
            this.warehousingMaterialList[this.curIndex]?.warehouseLedgerDetails
              ?.length
        );
      },
    },
  },
  onUnload() {
    clearTimeout(timer);
  },
  onLoad({ bizScene, assetType, index, isScan }) {
    this.requestDict("物品类型");

    lastNum = 0;
    this.bizScene = bizScene;
    this.isScan = isScan === "true";
    if (this.isScan) {
      this.bizScene = 5;
    }
    this.assetType = assetType;
    this.curIndex = index;
    this.baseInfo = uni.getStorageSync("inputData") || {};
    this.warehousingMaterialList =
      uni.getStorageSync("warehousingMaterialList") || [];

    if (
      this.warehousingMaterialList[this.curIndex]?.warehouseLedgerDetails
        ?.length
    ) {
      this.curDateType = this.warehousingMaterialList[this.curIndex]
        ?.warehouseLedgerDetails[0].procurementTime
        ? "procurementTime"
        : "manufactureTime";
    }
  },
  methods: {
    handleDateChange(item) {
      // 组件补时分秒
      this.$nextTick(() => {
        if (item[this.curDateType] && item[this.curDateType].length < 19) {
          item[this.curDateType] =
            item[this.curDateType].split(" ")[0] + " 00:00:00";
        }

        console.log(item, item[this.curDateType]);
        this.forceUpdate = !this.forceUpdate;
      });
    },
    cancel() {
      if (this.isScan) {
        // 扫码取消删除
        this.warehousingMaterialList.splice(this.curIndex, 1);
      } else {
        this.warehousingMaterialList[this.curIndex].warehouseLedgerDetails = [];
      }
      uni.navigateBack({
        delta: 1,
      });
    },
    handleSave() {
      if (
        !this.warehousingMaterialList[this.curIndex]?.warehouseLedgerDetails
          ?.length
      ) {
        uni.showToast({
          title: "请完善必填信息",
          icon: "none",
        });
        return;
      }
      const fileds = [`cargoSpaceCode`, `batchNum`];

      if (this.bizScene != 5) {
        fileds.push(...[`outInNum`, `measurementUnit`]);
      } else if (
        this.warehousingMaterialList.some(
          (i) => !i.selfWarehouseLedgerDetails?.length
        )
      ) {
        uni.showToast({
          title: "请选择资产编号！",
          icon: "none",
        });
        return;
      }
      Promise.all(
        fileds.map(
          (item) =>
            new Promise(async (resolve, rej) => {
              this.$refs.lisrFormRef.validateField(item, (err) => {
                if (err?.length) {
                  rej(err);
                } else {
                  resolve();
                }
              });
            })
        )
      )
        .then(async (res) => {
          uni.showLoading({
            mask: true,
          });
          // 清空另一个时间
          this.warehousingMaterialList[
            this.curIndex
          ].warehouseLedgerDetails.map((item) => {
            item[
              this.curDateType == "manufactureTime"
                ? "procurementTime"
                : "manufactureTime"
            ] = "";
          });

          uni.hideLoading();

          uni.$emit("batchNumBack", this.warehousingMaterialList);
          uni.navigateBack({
            delta: 1,
          });
        })
        .catch((err) => {
          uni.showToast({
            icon: "error",
            title: "请完善必填项！",
          });
        });
    },
    // 选择资产编号
    chooseAssets() {
      const row = this.warehousingMaterialList[this.curIndex];
      this.$refs.returnSelectRef.open(row, (res) => {
        this.unpdateMaterialCode();
        row.outInNum = res.length;

        this.$set(
          row,
          "selfWarehouseLedgerDetails",
          res.map((i) => {
            delete i.updateTime;
            delete i.createTime;
            return i;
          })
        );
      });
    },
    confirm() {
      if (!this.batchTime) {
        uni.showToast({
          title: "请选择时间",
          icon: "none",
        });
        return;
      }

      this.warehousingMaterialList[
        this.curIndex
      ]?.warehouseLedgerDetails.forEach((item, index) => {
        if (!!this.selection.find((i) => i == index)) {
          if (this.batchTime && this.batchTime.length < 19) {
            this.batchTime = this.batchTime.split(" ")[0] + " 00:00:00";
          }
          item[this.curDateType] = this.batchTime;
        }
      });
      this.popupShow = false;
    },
    setDate() {
      if (!this.selection.length) {
        uni.showToast({
          title: "请选择明细",
          icon: "none",
        });
        return;
      }
      this.popupShow = true;
    },
    selectionChange(val) {
      console.log(val.detail.value);
      this.selection = val.detail.value;
    },
    //获取仓库信息
    handleWarehouseChoose() {
      this.$refs.warehouseChooseRef.open(null, (res) => {
        for (const key in res) {
          this.$set(this.warehousingMaterialList[this.curIndex], key, res[key]);
        }
        this.unpdateMaterialCode();
        this.forceUpdate = !this.forceUpdate;
      });
    },
    //跳转回添加页面
    jumpAdd() {
      uni.$emit(
        "setSelectList",
        this.listData.filter((item) => item.checked)
      );
      uni.navigateBack();
    },
    //返回添加页
    backAdd() {
      uni.navigateBack();
    },
    // 更新条码信息
    unpdateMaterialCode() {
      console.log("unpdateMaterialCode");
      clearTimeout(timer);
      timer = setTimeout(() => {
        this.getMaterialCode();
      }, 500);
    },
    // 入库明细生成条码信息
    async getMaterialCode() {
      console.log("getMaterialCode");
      const fileds = [`cargoSpaceCode`, `batchNum`];

      if (this.bizScene != 5) {
        fileds.push(...[`outInNum`, `measurementUnit`]);
      } else if (
        this.warehousingMaterialList.some(
          (i) => !i.selfWarehouseLedgerDetails?.length
        )
      ) {
        // uni.showToast({
        //   title: '请选择资产编号！',
        //   icon: 'none'
        // })
        return;
      }
      Promise.all(
        fileds.map(
          (item) =>
            new Promise(async (resolve, rej) => {
              this.$refs.lisrFormRef.validateField(item, (err) => {
                if (err?.length) {
                  rej(err);
                } else {
                  resolve();
                }
              });
            })
        )
      )
        .then(async (res) => {
          this.showLoading = true;
          lastNum++;
          this.$set(
            this.warehousingMaterialList[this.curIndex],
            "isSave",
            true
          );
          if (this.bizScene != 5) {
            await this.createMaterialCode(
              this.warehousingMaterialList[this.curIndex],
              lastNum
            );
          } else {
            // 退还
            await this.createMaterialCodeReturn(
              this.warehousingMaterialList[this.curIndex],
              lastNum
            );
          }

          this.showLoading = false;
        })
        .catch((err) => {
          // uni.showToast({
          //   icon: 'error',
          //   title: '请填入必填项！'
          // })
        });
    },
    // 入库明细生成条码信息
    async createMaterialCode(row, curNum) {
      // 添加相同物品重新更新明细 原料编码
      const list = this.warehousingMaterialList.filter(
        (i) =>
          i.assetCode === row.assetCode &&
          i.batchNum === row.batchNum &&
          i.isSave
      );

      const num = list.reduce((num, pre, index) => {
        num += row.isUnpack ? pre.outInNum * pre.measurementUnit : pre.outInNum;
        return num;
      }, 0);

      const res = await postJ(this.apiUrl + "/outInWarehouse/getAssetNum", {
        batchNum: row.batchNum,
        assetCode: row.assetCode,
        num,
      });
      if (res?.success && lastNum === curNum) {
        list.forEach((item) => {
          let len = item.isUnpack
            ? item.outInNum * item.measurementUnit
            : +item.outInNum;

          this.$set(
            item,
            "warehouseLedgerDetails",
            Array.from(new Array(len), (val, idx) => {
              return {
                ...item,
                onlyCode: res.data.shift().onlyCode,
                bizStatus: 1,
                contentImage: [],
              };
            })
          );
        });
      }

      // 添加相同物品，重复批次号 重新更新明细 包装编码
      const batchList = this.warehousingMaterialList.filter(
        (i) => i.batchNum == row.batchNum && i.isSave
      );
      if (batchList.length) {
        const num = batchList.reduce((num, pre) => {
          num += +pre.outInNum;
          return num;
        }, 0);
        const res1 = await postJ(this.apiUrl + "/outInWarehouse/getAssetNum", {
          batchNum: row.batchNum,
          num,
        });
        if (res1?.success && lastNum === curNum) {
          batchList.forEach((item) => {
            let num = res1.data.shift()?.num;
            let measurementUnit = item.measurementUnit;

            if (item.warehouseLedgerDetails?.length) {
              item.warehouseLedgerDetails.forEach((i, index) => {
                this.$set(i, "num", num);
                if (!item.isUnpack) {
                  if (index < item.warehouseLedgerDetails.length - 1) {
                    num = res1.data.shift()?.num;
                  }
                } else {
                  // 拆包的包装编码一致
                  measurementUnit--;
                  if (
                    measurementUnit === 0 &&
                    index < item.warehouseLedgerDetails.length - 1
                  ) {
                    measurementUnit = item.measurementUnit;
                    num = res1.data.shift()?.num;
                  }
                }
              });
            }
          });
        }
      }
      this.page = 1;

      this.forceUpdate = !this.forceUpdate;
    },
    // 入库明细生成条码信息 退还
    async createMaterialCodeReturn(row, curNum) {
      // 添加相同物品重新更新明细 原料编码
      const list = this.warehousingMaterialList.filter(
        (i) => i.assetCode === row.assetCode && i.batchNum === row.batchNum
      );
      // 退还
      const res = await postJ(this.apiUrl + "/outInWarehouse/getAssetNum", {
        batchNum: row.batchNum,
        num: list.reduce((num, pre) => {
          num += pre.selfWarehouseLedgerDetails.length;
          return num;
        }, 0),
      });
      if (res?.success && lastNum === curNum) {
        list.forEach((item) => {
          let num = res.data.shift().num;
          let measurementUnit = item.measurementUnit;
          if (item.warehouseLedgerDetails?.length) {
            item.warehouseLedgerDetails.forEach((i) => {
              Object.assign(i, {
                num,
                batchNum: item.batchNum,
                cargoSpaceCode: item.cargoSpaceCode, //货位编码
                cargoSpaceId: item.cargoSpaceId, //货位id
                shelfId: item.shelfId, //货架id
                shelfCode: item.shelfCode, //货架名称
                areaId: item.areaId, //库区id
                areaName: item.areaName, //库区名称
                warehouseId: item.warehouseId, //仓库id
                warehouseName: item.warehouseName, //仓库名称
              });

              if (!item.isUnpack) {
                // 拆包的包装编码一致
                num = res.data.shift()?.num;
              } else {
                measurementUnit--;
                if (measurementUnit === 0) {
                  measurementUnit = item.measurementUnit;
                  num = res1.data.shift()?.num;
                }
              }
            });
          } else {
            this.$set(
              item,
              "warehouseLedgerDetails",
              item.selfWarehouseLedgerDetails.map((val, idx) => {
                let obj = {
                  ...val,
                  bizStatus: 1,
                  batchNum: item.batchNum,
                  measurementUnit: item.measurementUnit,
                  cargoSpaceCode: item.cargoSpaceCode, //货位编码
                  cargoSpaceId: item.cargoSpaceId, //货位id
                  shelfId: item.shelfId, //货架id
                  shelfCode: item.shelfCode, //货架名称
                  areaId: item.areaId, //库区id
                  areaName: item.areaName, //库区名称
                  warehouseId: item.warehouseId, //仓库id
                  warehouseName: item.warehouseName, //仓库名称
                  materialId: item.materialId,
                  num,
                };
                if (!item.isUnpack) {
                  // 拆包的包装编码一致
                  num = res.data.shift()?.num;
                } else {
                  measurementUnit--;
                  if (measurementUnit === 0) {
                    measurementUnit = item.measurementUnit;
                    num = res1.data.shift()?.num;
                  }
                }
                return obj;
              })
            );
          }
        });
        this.forceUpdate = !this.forceUpdate;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.mainBox {
  .time-container {
    padding: 20rpx 60rpx 40rpx;
    margin-bottom: 60rpx;

    .title {
      font-size: 32rpx;
      text-align: center;
      margin-bottom: 30rpx;
    }
  }
  .time-footer {
    display: flex;
    justify-content: space-between;
  }
  .wrapper {
    padding-top: 10px;
    position: relative;

    .operation {
      display: flex;
      justify-content: flex-end;
      padding: 0 10rpx;
      text {
        padding: 10rpx;
      }

      .u-button {
        width: 200rpx;
        margin: 0 !important;
      }
    }
    .self-table {
      width: 100%;
      .self-tr {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10rpx 10rpx;
        font-size: 28rpx;
        box-sizing: border-box;
        min-height: 100rpx;

        &.bg {
          background-color: rgba(245, 245, 245, 1);
          border-bottom: 1rpx solid rgba(0, 0, 0, 0.2);
        }
        .check {
          width: 80rpx;
          text-align: center;
        }
        .code {
          width: 28%;
          word-break: break-all;
        }
        .num {
          width: 18%;
          text-align: center;
        }
        .date-picker {
          flex: 1;

          /deep/.uni-date,
          .uni-stat__select {
            width: 100% !important;

            .uni-icons {
              display: none;
            }
            .uni-date-x {
              padding: 0 10rpx !important;
            }
            .uni-date__x-input {
              font-size: 28rpx;
              padding: 0 !important;
            }
          }
        }
      }
    }
    .title {
      padding-left: 20rpx;
      margin-bottom: 20rpx;
    }
    .cell {
      display: flex;
      padding: 0 20rpx;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;
      .label {
        font-size: 28rpx;
        font-weight: bold;
      }
      .cargoSpaceCode {
        width: 100%;
        padding: 10rpx 0;
        text-align: right;
      }
      .uni-easyinput {
        border: 1rpx solid #ccc;
      }
      /deep/.u-form-item {
        .u-form-item__body__left {
          font-weight: bold;
          color: #333;
        }
        .u-form-item__body__left__content__label {
          font-size: 28rpx !important;
        }
        .u-form-item__body {
          padding: 0 !important;
        }
      }
      .u-input {
        border: 1rpx solid rgba(222, 222, 222, 1) !important;
      }
    }

    .bucket-col {
      display: flex;
      padding: 20rpx 20rpx;
      background-color: #f5f5f5;
      justify-content: space-between;
      align-items: center;
      font-size: 28rpx;

      /deep/.date {
        color: #aaaaaa;
        display: flex;
        align-items: center;
        .name {
          margin-right: 20rpx;
        }

        .uni-date__x-input {
          height: 60rpx;
          width: 180rpx;
        }
      }
    }
  }
}
</style>
