<template>
  <!-- 拆单弹窗 -->
  <view class="cu-modal animation-slide-bottom" :class="splitModal ? 'show' : ''" style="z-index: 900;">
    <view class="cu-dialog">
      <view class="cu-bar bg-white justify-end bottom-line">
        <view class="content title-bolder">{{$t('拆单信息')}}</view>
      </view>
      <scroll-view scroll-y="true" style="height: 400px">
        <view class="cu-form-group">
          <view class="title">{{$t('原订单号')}}</view>
          <view class="content">{{ detail.orderNo }}</view>
        </view>
        <view class="cu-form-group">
          <text class="title">{{$t('目的地')}}</text>
          <text class="content">{{ detail.destWarehouseName }}</text>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('总箱数')}}</view>
          <view class="content">{{ detail.num }}</view>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('总数量(个)')}}</view>
          <view class="content">{{ quantity }}</view>
        </view>
        <view class="cu-form-group">
          <text class="title">{{$t('可拆出箱数')}}</text>
          <text class="content">{{ detail.canSplitNum }}</text>
        </view>
        <view class="cu-form-group">
          <text class="title">{{$t('可拆出数量(个)')}}</text>
          <text class="content">{{ detail.calQuantity }}</text>
        </view>

        <view class="cu-card dynamic" v-for="(v, k) of productsData" :key="'productsData.' + k">
          <view class="cu-item shadow">
            <view class="cu-form-group" v-if="k == 0">
              <view class="title">{{ splitItem.orderNo }}</view>
            </view>
            <view class="cu-form-group">
              <view class="title">{{$t('品名')}}</view>
              <picker @change="bindPickerChange" :value="v.orderItemIndex" :range="canSplitOrderItems" :range-key='$l("prodTitle")' :data-index='k'>
                <view class="uni-input picker">{{v.title||$t('请选择')}}</view>
              </picker>
            </view>
            <view class="cu-form-group">
              <view class="title">{{$t('箱数')}}</view>
              <input class="text-right" type="number" v-model.number="productsData[k].splitNum" :placeholder="$t('输入箱数')" @input="calcAverg(productsData[k])" />
            </view>
            <view class="cu-form-group" v-if="quantityRequired">
              <view class="title">{{$t('数量(个)')}}</view>
              <input class="text-right" type="number" v-model.number="productsData[k].putQuantity" :placeholder="$t('输入数量(个)')" @input="checkInteger(productsData[k], 'putQuantity')" />
            </view>
            <view class="cu-form-group" v-if="v.orderItem">
              入仓方数：{{v.orderItem.warehouseInInfoVO.volume}}m³ 收费方数{{v.orderItem.chargeVolume}}m³
            </view>
            <view class="cu-form-group">
              <view class="title">{{$t('放入入仓方数')}}</view>
              <input class="text-right"
                     type="number"
                     v-model.number="productsData[k].volume"
                     @input="checkDecimal(productsData[k], 'volume', 0, v.orderItem ? v.orderItem.warehouseInInfoVO.volume : null)"
                     :placeholder="$t('请输入入仓方数')"
              />
            </view>
            <view class="cu-form-group">
              <view class="title">{{$t('放入收费方数')}}</view>
              <input class="text-right" type="number"
                     v-model.number="productsData[k].chargeVolume"
                     @input="checkDecimal(productsData[k], 'chargeVolume', 0, v.orderItem ? v.orderItem.chargeVolume : null)"
                     :placeholder="$t('请输入收费方数')"
              />
            </view>
            <view class="cu-form-group" v-if="v.orderItem">
              {{$t('入仓重量')}}：{{v.orderItem.warehouseInInfoVO.weight}}kg {{$t('收费重量')}}{{v.orderItem.chargeWeight}}kg
            </view>
            <view class="cu-form-group">
              <view class="title">{{$t('放入入仓重量')}}</view>
              <input class="text-right" type="number"
                     v-model.number="productsData[k].weight"
                     @input="checkDecimal(productsData[k], 'weight', 0, v.orderItem ? v.orderItem.warehouseInInfoVO.weight : null)"
                     :placeholder="$t('请输入入仓重量')"
              />
            </view>
            <view class="cu-form-group">
              <view class="title">{{$t('放入收费重量')}}</view>
              <input class="text-right"
                     type="number"
                     v-model.number="productsData[k].chargeWeight"
                     @input="checkDecimal(productsData[k], 'chargeWeight', 0, v.orderItem ? v.orderItem.chargeWeight : null)"
                     :placeholder="$t('请输入收费重量')"
              />
            </view>
            <view class="cu-form-group">
              <view class="flex justify-end" style="width: 100%;">
                <view class="action">
                  <uni-icons type="plus" color="green" :size="26" @tap="add(k)"></uni-icons>
                </view>
                <view class="action" v-if="k != 0">
                  <uni-icons type="minus" color="red" :size="26" @tap="del(k)"></uni-icons>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="cu-form-group">
          <view class="title">{{$t('已拆出箱数')}}</view>
          <view class="content">{{totalSplitNum}}</view>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('已拆出数量(个)')}}</view>
          <view class="content">{{totalQuantity}}</view>
        </view>

      </scroll-view>
      <view class="cu-bar bg-white justify-end top-line">
        <view class="action">
          <button class="cu-btn bg-blue" @tap="finishSplit()">{{$t('确认')}}</button>
          <button class="cu-btn bg-grey margin-left" @tap="showSplit(false)">{{$t('取消')}}</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import * as types from "../../../store/mutations-types.js";
import mixins from "../../../mixins/mixin.js";
import { uniIcons } from "@dcloudio/uni-ui";
import {
  quantitycheck,
  splitList,
  createSplitItem,
  createApproval,
} from "../api";
import { getOrder, quantityRequired } from "@/pages/tally/api";

export default {
  mixins: [mixins],
  props: ["shipmentId"],
  components: {
    uniIcons,
  },
  data() {
    return {
      /* 拆单显示 */
      splitModal: false,
      /* 订单信息 */
      detail: {},
      /* 拆单数据 */
      productsData: [],
      /* 品名选中坐标 */
      productsPickerIndex: [],
      order: null, // 订单信息
      // 拆单列表
      splitList: [],
      preInstallOrder: null, // 预装订单信息
      quantityRequired: false, // 数量是否必填
    };
  },
  computed: {
    // 子单
    splitItem(){
      return this.splitList.find(item => !item.isMaster) || {}
    },
    // 主单
    mainOrder(){
      return this.splitList.find(item => item.isMaster) || {}
    },
    // 主单商品项
    mainOrderItems(){
      return this.mainOrder?.orderSplitItemBackVOList || []
    },
    // 主单的总数量
    quantity(){
      return this.mainOrderItems.reduce((total, item) => total + Number(item.quantity), 0)
    },
    // 预装的商品项
    products(){
      return this.preInstallOrder.goodsList || []
    },
    // 可以拆的商品项,未入库的不可拆
    canSplitOrderItems(){
      if(!this.order) return []
      return this.order.orderItemVOList.filter(item => !!item.warehouseInInfoVO)
    },

    /* 拆箱总数 */
    totalSplitNum() {
      let _total = 0;
      this.productsData.forEach((v) => {
        _total += Number(v.splitNum);
      });
      return _total;
    },
    totalQuantity() {
      let _quantity = 0;
      this.productsData.forEach((v) => {
        _quantity += Number(v.putQuantity ?? 0);
      });
      return _quantity;
    },
    isChinese() {
      return uni.getLocale() === "zh-Hans";
    },

  },
  methods: {
    // 限制正整数
    checkInteger(obj, field){
      obj[field] = obj[field].toString().replace(/[^\d]/g, '')
    },
    // 检查小数
    checkDecimal(obj, field, min = null, max = null){
      let val = obj[field]
      if(min !== null && min !== undefined && val < min){
        obj[field] = min
      }
      if(max !== null && max !== undefined && val > max){
        obj[field] = max
      }
    },
    // 根据箱数计算体积重量平均数
    calcAverg(productDataItem){
      // 数量的整数格式校验
      this.checkInteger(productDataItem, 'splitNum')
      // 如果数量超过了入仓箱数,则取入仓箱数
      productDataItem.splitNum = Math.min(productDataItem.splitNum, productDataItem.orderItem.warehouseInInfoVO.cartonsNum)

      // 计算数量占 商品项入仓箱数的比例
      const rate = productDataItem.splitNum / productDataItem.orderItem.warehouseInInfoVO.cartonsNum

      /*// 根据比例计算默认的体积重量和数量
      const volume = Math.min(this.preInstallOrder.volume * rate, productDataItem.orderItem.warehouseInInfoVO.volume)
      const weight = Math.min(this.preInstallOrder.weight * rate, productDataItem.orderItem.warehouseInInfoVO.weight)*/

      this.$set(productDataItem, 'volume',        (rate * productDataItem.orderItem.warehouseInInfoVO.volume).toFixed(2))
      this.$set(productDataItem, 'weight',        (rate * productDataItem.orderItem.warehouseInInfoVO.weight).toFixed(2))
      this.$set(productDataItem, 'putQuantity',   parseInt(rate * productDataItem.orderItem.chargeQuantity) || 1)
      this.$set(productDataItem, 'chargeVolume',  (rate * productDataItem.orderItem.chargeVolume).toFixed(2))
      this.$set(productDataItem, 'chargeWeight',  (rate * productDataItem.orderItem.chargeWeight).toFixed(2))
    },
    /*查询订单信息*/
    getOrder(orderId){
      getOrder(orderId).then(data => {
        this.order = data
      })
    },
    // 根据路线获取数量是否必须
    getQuantityRequired(){
      quantityRequired(this.order.lineId).then(data => {
        this.quantityRequired = data
      })
    },
    /* 打开拆单 */
    showSplit(show, order) {
      this.splitModal = show;
      if (show) {
        this.productsPickerIndex = [];
        /*this.products = [];*/
        this.productsData = [
          {
            splitNum: "",
            title_zh: "",
            keys: "",
            putQuantity: ""
          },
        ];
        this.preInstallOrder = order

        // 查询订单详情
        this.getOrder(order.orderId)

        splitList({
          orderId: order.orderId,
          shipmentId: this.shipmentId,
        }).then((res) => {
          this.splitList = res
          // 此订单的可拆箱数 = preInstallOrder.num 是计划箱数(预装) - preInstallOrder.installNum 已装箱数
          let canSplitNum = this.preInstallOrder.num - this.preInstallOrder.installNum
          // 可拆数量（按照比例计算）
          let avgQua = Math.round(this.quantity * canSplitNum / this.preInstallOrder.num)

          // 可拆出箱数=计划数量-实装
          this.detail = {
            ...this.preInstallOrder,
            canSplitNum,
            calQuantity: avgQua,
          };
        });
      }
    },
    /* 拆单 */
    finishSplit() {
      if (!this.checkProductsData()) {
        return false;
      }
      if (this.totalSplitNum > this.detail.canSplitNum) {
        this.$store.dispatch(types.SHOW_TOAST, {
          msg: this.$t("已拆出箱数不能大于可拆出箱数"),
        });
        return false;
      }
      uni.showModal({
        content: this.$t("确定拆单吗？拆单一经确定将不可逆"),
        success: (e) => {
          if (e.confirm) {
            let splitItemList = [];
            this.productsData.forEach((item) => {
              const splitIndex = splitItemList.findIndex(
                (sItem) => sItem.orderItemId === item.keys
              );
              if (~splitIndex) {
                let oldNum = splitItemList[splitIndex].num;
                splitItemList[splitIndex].num = oldNum + Number(item.splitNum);
              } else {
                let splitItem = {
                  num: item.splitNum,
                  orderItemId: item.orderItemId,
                  orderSplitId: this.splitItem.id,
                  volume: item.volume,
                  weight: item.weight,
                  chargeVolume: item.chargeVolume,
                  chargeWeight: item.chargeWeight
                }
                if(this.quantityRequired){
                  splitItem.quantity = item.putQuantity
                }
                splitItemList.push(splitItem);
              }
            });
            // 添加拆单项放入
            createSplitItem({ splitItemList }).then((data) => {
              // 创建拆单审核
              createApproval({
                applyReason: this.$t("拆单审核"),
                approvalStatus: 0,
                approvalType: 8,
                orderId: this.detail.orderId,
                shipmentId: this.shipmentId,
              }).then((res) => {
                uni.showModal({
                  title: this.$t("拆单申请提交成功"),
                  content: this.$t(
                    "你的拆单审核已提交成功，请耐心等待后台审核"
                  ),
                  cancelText: this.$t("返回"),
                  confirmText: this.$t("去入仓"),
                  success: (e) => {
                    if (e.confirm) {
                      let numbers = this.detail.orderNo;
                      uni.navigateTo({
                        url:
                          "../warehousing/list?orderNo=" +
                          numbers +
                          "&shipmentId=" +
                          this.shipmentId,
                      });
                    } else {
                      this.showSplit(false);
                      this.$emit("reload");
                    }
                  },
                });
              });
            });
          }
        },
      });
    },
    /* 删除 */
    del(k) {
      this.productsData.splice(k, 1);
    },
    /* 添加 */
    add() {
      this.productsData.push({
        splitNum: "",
        title_zh: "",
        keys: "",
        putQuantity: ''
      });
    },
    /* 产品选择 */
    async bindPickerChange(e) {
      console.log('bindChange', e)
      let index = e.detail.value //  这个是商品的下标
      let productDataIndex = e.currentTarget.dataset.index; // 这个是拆单项的下标
      let selectedItem = this.canSplitOrderItems[index];
      // 从订单信息中查询出商品项信息，需要从此数据取出收费数据
      /*let orderItem = this.order.orderItemVOList.find(item => item.orderItemId == selectedItem.orderItemId)
      if(!orderItem){
        return uni.showToast({title: '获取商品项信息失败'})
      }*/
      this.$set(this.productsData[productDataIndex], 'orderItemIndex', index)
      this.$set(this.productsData[productDataIndex], 'orderItemId', selectedItem.orderItemId)
      this.$set(this.productsData[productDataIndex], 'title', this.$l(selectedItem, 'prodTitle'))

      // 将商品项信息保存到拆单项，方便后续取值操作
      this.$set(this.productsData[productDataIndex], 'orderItem', selectedItem)
      // 默认的拆单箱数，在商品箱数 和 剩余可拆箱数（订单可拆箱数 - 已拆箱数） 中取最小值
      this.$set(this.productsData[productDataIndex], 'splitNum', Math.min(this.detail.canSplitNum - this.totalSplitNum, selectedItem.num))

      // 按照比例计算默认的数量，体积，重量
      this.calcAverg(this.productsData[productDataIndex])
    },
    /* 产品数据验证 */
    checkProductsData() {
      let flag = true;
      this.productsData.forEach((v) => {
        if (!flag) {
          return false;
        }
        if (!v.orderItemId) {
          flag = false;
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: this.$t("请选择商品"),
          });
        } else if (!v.splitNum) {
          flag = false;
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: this.$t("请填写箱数"),
          });
        } else if (this.splitItem && !v.putQuantity) {
          flag = false;
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: "请填写数量(个)",
          });
        }
      });
      return flag;
    },
  },
};
</script>

<style lang="scss" scoped>
.justify-end {
  justify-content: flex-end;
}
.action {
  padding-left: 10upx;
}
.content {
  &.title-bolder {
    color: #333333;
    font-weight: bolder;
  }
}
</style>

