<template>
  <!-- 拆单 -->
    <view class2="cu-dialog" v-if="parentOrder">
        <view class="cu-form-group">
          <view class="title">{{$t('原订单号')}}</view>
          <view class="content">{{ parentOrder.orderNo }}</view>
        </view>
        <view class="cu-form-group">
          <text class="title">{{$t('目的地')}}</text>
          <text class="content">{{ $l(parentOrder.logisticsInfoDto, 'destTitle') }}</text>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('总箱数')}}</view>
          <view class="content">{{ parentOrder.sumNum }}</view>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('总数量(个)')}}</view>
          <view class="content">{{ parentOrder.sumQuantity }}</view>
        </view>
        <view class="cu-form-group">
          <!--可拆出数量就是主单的数量-->
          <text class="title">{{$t('可拆出箱数')}}</text>
          <text class="content">{{ canSplitNum }}</text>
        </view>
        <!--老郑说退场拆单不考虑数量-->
        <!--<view class="cu-form-group">
          <text class="title">{{$t('可拆出数量(个)')}}</text>
          <text class="content">{{ detail.calQuantity }} // TODO 待确认</text>
        </view>-->

        <view class="cu-card dynamic" v-for="(v, k) of productsData" :key="'productsData.' + k">
          <view class="cu-item shadow" :class="{error: v.error}">
            <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 style="margin:30rpx; padding:10rpx; background: #eee;" v-if="v.orderItem">
              <view>{{$t('品名可拆数据')}}</view>
              <view>{{$t('箱数')}}：{{Math.min(getOrderItemLeftData(v.orderItem, 'num'), canSplitNum - totalSplitNum)}}</view>
              <view>{{$t('入仓方数')}}：{{getOrderItemLeftData(v.orderItem, 'volume')}}m³， {{$t('收费方数')}}:{{getOrderItemLeftData(v.orderItem, 'chargeVolume')}}m³</view>
              <view>{{$t('入仓重量')}}：{{getOrderItemLeftData(v.orderItem, 'weight')}}kg，{{$t('收费重量')}}:{{getOrderItemLeftData(v.orderItem, 'chargeWeight')}}kg</view>
              <view>{{$t('数量(个)')}}：{{getOrderItemLeftData(v.orderItem, 'quantity')}}，{{$t('订单剩余货值')}}:{{leftWorth}}{{$t('元')}}</view>
            </view>
            <view class="section-title">{{$t('可拆入仓记录')}}</view>
            <uni-card v-for="warehouseInItem in v.warehouseInList" :key="warehouseInItem.id">
              <view class="item-content noPadding">
                <view>
                  <view>{{$t('箱数')}}：{{ Math.min(getWarehouseLeftData(warehouseInItem, 'num'), canSplitNum - totalSplitNum) }}</view>
                  <view>{{$t('数量（个）')}}：{{getWarehouseLeftData(warehouseInItem, 'quantity')}}</view>
                </view>
                <view>
                  <view>{{$t('包装类型')}}：
                    <dict-tag :type="DICT_TYPE.ECW_PACKAGING_TYPE" :value="warehouseInItem.unit" />
                  </view>
                  <view>{{$t('入仓类型')}}：
                    <dict-tag :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" :value="warehouseInItem.specificationType" />
                  </view>
                </view>
                <view>
                  <view>{{$t('长')}}：{{warehouseInItem.boxGauge.split('*')[0]}}</view>
                  <view>{{$t('体积') + '(m³)'}}：{{getWarehouseLeftData(warehouseInItem, 'volume')}}</view>
                </view>
                <view>
                  <view>{{$t('宽')}}：{{warehouseInItem.boxGauge.split('*')[1]}}</view>
                  <view>{{$t('重量') + '(kg)'}}: {{getWarehouseLeftData(warehouseInItem, 'weight')}}</view>
                </view>
                <view>
                  <view>{{$t('高')}}: {{warehouseInItem.boxGauge.split('*')[2]}}</view>
                  <view>{{$t('快递单号')}}: {{warehouseInItem.expressNo}}</view>
                </view>
                <view>
                  <view>{{$t('首次入仓时间')}}：{{ warehouseInItem.inTime ? dayjs(warehouseInItem.inTime).format("YYYY-MM-DD HH:mm:ss") : warehouseInItem.inTime }}</view>
                </view>
                <view>
                  <view>{{$t('储位')}}: {{showLocationName(warehouseInItem.orderLocationBackVOList)}}</view>
                  <view>
                    <button
                      size="mini"
                      type="primary"
                      @click="putin(warehouseInItem, v)"
                      :disabled="totalSplitNum >= canSplitNum || Math.min(getWarehouseLeftData(warehouseInItem, 'num'), canSplitNum - totalSplitNum) <= 0">
                      放入
                    </button>
                  </view>
                </view>
              </view>
            </uni-card>
            <!--<picker  class="add-row-btn" :range="getOrderItemWarehouseIn(v.orderItemId)" @change="addRow(v, $event)" range-key="text">
              <uni-icons type="plus-filled" size="20" color="#eaeced"></uni-icons>
              {{$t('添加入仓记录')}}
            </picker>-->

            <!--已添加的拆出入仓记录-->
            <view class="flex align-center padding-lr-sm" v-if="v.orderItemId">
              <view class="left section-title" style="flex: 1">{{$t('品名累计放入数据')}}</view>
              <view class="right">
                <button v-if="v.specsRecordVOList && v.specsRecordVOList.length" size="mini" type="primary" @click="clearAll(v)">{{$t('清空放入数据')}}</button>
              </view>
            </view>
            <uni-card v-for="(warehouseInItem, index) in v.specsRecordVOList" :key="warehouseInItem.id">
              <view class="item-content noPadding">
                <view>
                  <view>{{$t('箱数')}}：{{ warehouseInItem.num }}</view>
                  <view>{{$t('数量（个）')}}：{{warehouseInItem.quantity}}</view>
                </view>
                <view>
                  <view>{{$t('包装类型')}}：
                    <dict-tag :type="DICT_TYPE.ECW_PACKAGING_TYPE" :value="warehouseInItem.unit" />
                  </view>
                  <view>{{$t('入仓类型')}}：
                    <dict-tag :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" :value="warehouseInItem.specificationType" />
                  </view>
                </view>
                <view>
                  <view>{{$t('长')}}：{{warehouseInItem.boxGauge.split('*')[0]}}</view>
                  <view>{{$t('体积') + '(m³)'}}：{{warehouseInItem.volume}}</view>
                </view>
                <view>
                  <view>{{$t('宽')}}：{{warehouseInItem.boxGauge.split('*')[1]}}</view>
                  <view>{{$t('重量') + '(kg)'}}: {{warehouseInItem.weight}}</view>
                </view>
                <view>
                  <view>{{$t('高')}}: {{warehouseInItem.boxGauge.split('*')[2]}}</view>
                  <view>{{$t('快递号')}}: {{warehouseInItem.expressNo}}</view>
                </view>
                <view>
                  <view>{{$t('储位')}}: {{showLocationName(warehouseInItem.orderLocationList)}}</view>
                  <view>
                    <button type="primary" size="mini" @click="delSpecsRecord(v, index)">删除</button>
                  </view>
                </view>
              </view>
            </uni-card>
            <view style="margin:30rpx; padding:10rpx;" v-if="v.orderItem">
              <view>{{$t('箱数')}}：{{getSplitTotal(v.specsRecordVOList, 'num')}}，{{$t('数量(个)')}}：{{getSplitTotal(v.specsRecordVOList, 'quantity')}}</view>
              <view>{{$t('入仓方数')}}：{{getSplitTotal(v.specsRecordVOList, 'volume')}}m³， {{$t('入仓重量')}}:{{getSplitTotal(v.specsRecordVOList, 'weight')}}kg</view>
              <view class="cu-form-group">
                <text class="title">{{$t('收费方数')}}</text>
                <text class="content">
                  <easyinput v-model="v.chargeVolume" :class="{error: v.errFields && v.errFields.indexOf('chargeVolume') > -1}"></easyinput>
                </text>
                <text>m³</text>
              </view>
              <view class="cu-form-group">
                <text class="title">{{$t('收费重量')}}</text>
                <text class="content">
                  <easyinput v-model="v.chargeWeight" :class="{error: v.errFields && v.errFields.indexOf('chargeWeight') > -1}"></easyinput>
                </text>
                <text>kg</text>
              </view>
              <view class="cu-form-group">
                <text class="title">{{$t('放入货值')}}</text>
                <text class="content">
                  <easyinput v-model="v.worth"></easyinput>
                </text>
                <text>{{$t('元')}}</text>
              </view>
              <view class="cu-form-group">
                <text class="title">{{$t('备注')}}</text>
                <text class="content">
                  <easyinput v-model="v.remark"></easyinput>
                </text>
              </view>
            </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>

      <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="back">{{$t('取消')}}</button>
        </view>
      </view>

      <putin
        ref="putin"
        :warehouse-in-item="currentPutin"
        :warehouseId="warehouseId"
        @close="closePutin"
        :max-num="curentMaxNum"
        @submit="handlePutin"></putin>
    </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 "../loading/api";
import { getOrder, quantityRequired } from "@/pages/tally/api";
import {partRefundSplitList} from "@/pages/ExitWarehouse/api";
import { getOrderWarehouseIn } from "@/pages/warehousing/api";
import { alert, confirm, msg } from "@/util/tools";
import Decimal from 'decimal.js';
import Putin from "@/pages/ExitWarehouse/components/putin.vue";
import Easyinput from "@/components/easyinput/easyinput.vue";
export default {
  mixins: [mixins],
  components: {
    Easyinput,
    Putin,
    uniIcons,
  },
  data() {
    return {
      // 是否装柜拆单，如果为false则表示退场入仓拆单
      isLoadingSplit: true,
      // 主单Id
      parentOrderId: 0,
      // 出货id
      shipmentId: 0,
      // 原单（父订单）
      parentOrder: null,
      // 可拆单数量，退场拆单的时候就是入仓数量，02订单要拆出来的箱数，装柜拆单就是未装数量（预装数量 - 已装数量）
      canSplitNum: 0,
      /* 拆单显示 */
      splitModal: false,
      /* 订单信息 */
      detail: {},
      /* 拆单放入商品项数据，默认给一个 */
      productsData: [{
        specsRecordVOList:[]
      }],
      /* 品名选中坐标 */
      productsPickerIndex: [],

      // 拆单列表
      splitList: [],
      preInstallOrder: null, // 预装订单信息
      quantityRequired: false, // 数量是否必填
      unitTitle: this.$t('箱'), // 单位（箱/整版）
      // 入仓记录
      warehouseInList: [],
      // 当前放入的入仓记录
      currentPutin: null,
      // 当前放入的品名
      currentPutinProduct: null,
      // 当前放入的入仓记录
      currentPutInSpecsRecordVOList: []
    };
  },
  computed: {
    // 子单
    splitItem(){
      if(!this.splitList) return {}
      return this.splitList.find(item => !item.isMaster) || {}
    },
    // 主单
    mainOrder(){
      if(!this.splitList) return {}
      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.parentOrder) return []
      return this.parentOrder.orderItemVOList.filter(item => !!item.warehouseInInfoVO)
    },

    /* 拆箱总数 */
    totalSplitNum() {
      let _total = 0;
      this.productsData.forEach((v) => {
        let recordTotal = this.calcTotal(v.specsRecordVOList, "num")
        _total += Number(recordTotal) || 0;
      });
      return _total;
    },
    totalQuantity() {
      let _quantity = 0;
      this.productsData.forEach((v) => {
        let recordTotal = this.calcTotal(v.specsRecordVOList, "quantity")
        _quantity += Number(recordTotal || 0);
      });
      return _quantity;
    },
    isChinese() {
      return uni.getLocale() === "zh-Hans";
    },
    // 根据orderItemId获取入仓记录
    getOrderItemWarehouseIn(){
      return orderItemId => {
        const list = this.warehouseInList.find(item => item.orderItemId == orderItemId)?.orderWarehouseInBackItemDoList || []
        return list.map(item => {
          let [c, k, g] = item.boxGauge.split('*')
          let labelArr = [
            this.$t('{num}箱', { num: item.num }),
            this.$l(this.getDictDatas(this.DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE).find(dict => dict.value == item.specificationType), 'label'),
            this.$t('长{c}cm', { c }),
            this.$t('宽{k}cm', { k }),
            this.$t('高{g}cm', { g }),
            this.$t('方数{volume}m³', { volume: item.volume }),
            this.$t('重量{weight}kg', { weight: item.weight })
          ]
          if(item.quantityAll){
            labelArr.push(this.$t('数量{n}', {n: item.quantityAll}))
          }
          if(item.expressNo){
            labelArr.push(this.$t('快递{expressNo}', {expressNo: item.expressNo}))
          }
          if(item.orderLocationBackVOList && item.orderLocationBackVOList.length){
            labelArr.push(this.$t('储位{location}', {
              location: item.orderLocationBackVOList.map(v => v.code ||  v.areaName + (v.locationName || '')).join(',')
            }))
          }
          item.c = c
          item.k = k
          item.g = g
          item.text = labelArr.join(',')
          return item
        })
      }
    },
    // 根据入仓记录获得拆出入仓记录
    getWarehouseInspecsRecordVOList(){
      return warehouseInId => {
        let specsRecordVOList = []
        // 这里是拆单已放入的
        this.productsData.forEach(productItem => {
          productItem.specsRecordVOList.forEach(specs => {
            if (specs.warehouseInId === warehouseInId) {
              specsRecordVOList.push(specs)
            }
          })
        })

        // 这里是正在操作放入，但是还没确定提交的
        this.currentPutInSpecsRecordVOList.forEach(item => {
          if(item.warehouseInId == warehouseInId)specsRecordVOList.push(item)
        })
        return specsRecordVOList
      }
    },
    // 根据入仓ID获取拆出总数据
    getWarehouseInSplitData(){
      return (warehouseInId, field) => {
        let total = new Decimal(0)
        this.getWarehouseInspecsRecordVOList(warehouseInId).forEach(item => {
          total = total.plus(new Decimal(item[field] || 0))
        })
        return total.toNumber()
      }
    },
    // 获取入仓记录的剩余数据
    getWarehouseLeftData(){
      return (warehouseRecord, field) => {
        let warehouseInField = field
        if(field === 'num') warehouseInField = 'cartonsNum'
        if(field === 'quantity') warehouseInField = 'quantityAll'
        let total = new Decimal(warehouseRecord[ warehouseInField ] || 0)
        console.log('this.getWarehouseInspecsRecordVOList(warehouseRecord.id)', this.getWarehouseInspecsRecordVOList(warehouseRecord.id))
        this.getWarehouseInspecsRecordVOList(warehouseRecord.id).forEach(item => {
          total = total.minus(new Decimal(item[field] || 0))
        })
        return total.toNumber()
      }
    },
    // 计算品名剩余数据
    getOrderItemLeftData(){
      return (orderItem, field) => {
        let warehouseInField = field
        if(field === 'num') warehouseInField = 'cartonsNum'
        if(field === 'quantity') warehouseInField = 'quantityAll'
        // 体积，重量，箱数在入仓对象里，收费方数和收费重量，货值在orderItem对象里
        let total = new Decimal(orderItem.warehouseInInfoVO[warehouseInField] || orderItem[field] || 0)
        // 全部品名的拆出记录累减
        this.productsData.forEach(product => {
          // 同一品名则累减
          if(product.orderItemId === orderItem.orderItemId){
            // 收费方数，收费重量，货值在product对象里
            if(field === 'worth' || field === 'chargeWeight' || field === 'chargeVolume'){
              total = total.minus(new Decimal(product[field] || 0))
            }else{
              product.specsRecordVOList && product.specsRecordVOList.forEach(specs => {
                total = total.minus(new Decimal(specs[field] || 0))
              })
            }
          }
        })
        return total.toNumber()
      }
    },
    // 根据拆出的入仓记录计算总数
    getSplitTotal(){
      return (specsRecordList, field) => {
        let total = new Decimal(0)
        specsRecordList.forEach(item => {
          total = total.plus(new Decimal(item[field] || 0))
        })
        return total.toNumber()
      }
    },
    // 订单当前所在仓库
    warehouseId(){
      return this.parentOrder.adjustToDestWarehouseId || this.parentOrder.logisticsInfoDto.startWarehouseId
    },
    // 当前放入操作最大可拆箱数
    curentMaxNum(){
      if(!this.currentPutin) return 0
      console.log('this.getWarehouseLeftData(this.currentPutin, \'num\')', this.getWarehouseLeftData(this.currentPutin, 'num'))
      return Math.min(this.canSplitNum - this.totalSplitNum, this.getWarehouseLeftData(this.currentPutin, 'num'))
    },
    // 订单剩余可拆货值
    leftWorth(){
      if(!this.parentOrder?.costVO?.totalWorth)return 0;
      let worth = new Decimal(this.parentOrder.costVO.totalWorth)
      this.productsData.forEach(item =>{
        worth = worth.minus(new Decimal(item.worth || 0))
      })
      return worth.toNumber()
    },
  },
  onLoad(query){
    // 标记是否装柜拆单，如果不是则表示退场入仓拆单
    this.isLoadingSplit = query.fr === 'loading'

    uni.setNavigationBarTitle({
      title: this.isLoadingSplit ? this.$t("装柜拆单") : this.$t("退场入仓拆单")
    })

    this.parentOrderId = +query.orderId
    this.canSplitNum = +query.canSplitNum
    this.shipmentId = +query.shipmentId

    this.loadData()

    // 获取入仓记录
    getOrderWarehouseIn(query.orderId).then(data => {
      this.warehouseInList = data
    })
  },
  methods: {
    // 加载数据
    loadData(){
      // 原单信息
      getOrder(this.parentOrderId).then(res => {
        this.parentOrder = res
        // 获取数量是否必填
        this.getQuantityRequired()
      })
      const data = {
        orderId: this.parentOrderId,
        shipmentId: this.shipmentId,
      }
      if(this.isLoadingSplit) {
        // 装柜拆单列表
        splitList(data).then(data => this.splitList = data)
      }else{
        // 退场入仓拆单列表
        partRefundSplitList(data).then(res => {
          this.splitList = res
        })
      }
    },
    // 限制正整数
    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
      }
    },
    // 根据路线获取数量是否必须
    getQuantityRequired(){
      quantityRequired(this.parentOrder.lineId).then(data => {
        this.quantityRequired = data
      })
    },
    /* 拆单 */
    finishSplit() {
      // 按品名汇总重量体积数量
      this.productsData.forEach(product => {
        product.num = this.getSplitTotal(product.specsRecordVOList, 'num')
        product.weight = this.getSplitTotal(product.specsRecordVOList, 'weight')
        product.volume = this.getSplitTotal(product.specsRecordVOList, 'volume')
        product.quantity = this.getSplitTotal(product.specsRecordVOList, 'quantity')
      })
      if (!this.checkProductsData()) {
        return false;
      }
      // 退场拆单的时候 总拆出箱数必须是退场入场箱数
      if (!this.isLoadingSplit && this.totalSplitNum !== this.canSplitNum) {
        this.$store.dispatch(types.SHOW_TOAST, {
          msg: this.$t("拆出总箱数必须是退场入仓箱数"),
        });
        return false;
      }else{
        // 装柜拆单只要不超就行
        if(this.totalSplitNum > this.canSplitNum){
          return msg(this.$t("最大可拆箱数{num}", {num: this.canSplitNum}))
        }
      }
      confirm(this.$t("确定拆单吗？拆单一经确定将不可逆"), this.$t("提示")).then(() =>{
        let splitItemList = [];
        this.productsData.forEach((item) => {
          item.specsRecordVOList.forEach(record => {
            record.boxGauge = `${record.c}*${record.k}*${record.g}`
          })
          let splitItem = {
            num: this.calcTotal(item.specsRecordVOList, 'num'),
            orderItemId: item.orderItemId,
            orderSplitId: this.splitItem.id,
            volume: this.calcTotal(item.specsRecordVOList, 'volume'),
            weight: this.calcTotal(item.specsRecordVOList, 'weight'),
            chargeVolume: item.chargeVolume,
            chargeWeight: item.chargeWeight,
            worth: item.worth || 0,
            specsRecordVOList: item.specsRecordVOList,
            shipmentSplit: !!this.shipmentId
          }
          if(this.quantityRequired){
            splitItem.quantity = this.calcTotal(item.specsRecordVOList, 'quantity')
          }
          splitItemList.push(splitItem);
        });
        // 添加拆单项放入
        return createSplitItem({ splitItemList })
      }).then(() => {
        return createApproval({
          applyReason: this.$t("拆单审核"),
          approvalStatus: 0,
          // 装柜拆单是8，退场入仓拆单是10
          approvalType: this.$route.query.fr === 'loading' ? 8 : 10,
          orderId: this.parentOrderId,
          shipmentId: this.shipmentId,
        })
      }).then(() => {
        uni.showModal({
          title: this.$t("拆单申请提交成功"),
          content: this.$t(
            "你的拆单审核已提交成功，请耐心等待后台审核"
          ),
          cancelText: this.$t("返回"),
          confirmText: this.$t("去入仓"),
          success: (e) => {
            if (e.confirm) {
              uni.redirectTo({
                url: "../warehousing/list?orderNo=" + this.parentOrder.orderNo + "&shipmentId=" + this.shipmentId
              });
            } else {
              // 返回上一页
              uni.navigateBack()
            }
          },
        });
      })
    },
    /* 删除品名 */
    del(k) {
      this.productsData.splice(k, 1);
    },
    /* 添加品名 */
    add() {
      this.productsData.push({
        splitNum: "",
        title_zh: "",
        keys: "",
        putQuantity: '',
        specsRecordVOList:[]
      });
    },
    /* 产品选择 */
    async bindPickerChange(e) {
      console.log('bindChange', e)
      let index = e.detail.value //  这个是商品的下标
      let productDataIndex = e.currentTarget.dataset.index; // 这个是拆单项的下标
      let selectedItem = this.canSplitOrderItems[index];

      // 把这个品名的入仓记录筛选胡来
      const warehouseInList = this.warehouseInList.find(item => item.orderItemId == selectedItem.orderItemId)?.orderWarehouseInBackItemDoList || []

      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], 'warehouseInList', warehouseInList)

      // 切换品名后，他的放入记录要清空
      this.$set(this.productsData[productDataIndex], 'specsRecordVOList', [])
      this.calcDefaultData(this.productsData[productDataIndex])
    },
    /* 产品数据验证 */
    checkProductsData() {
      const empty = []
      const  fields = {
        'chargeVolume': this.$t('收费体积'),
        'chargeWeight': this.$t('收费重量')
      }
      this.productsData.forEach((v, index) => {
        this.$set(v, 'error', 0)
        if(!v.orderItemId){
          this.$set(v, 'error', 1)
          empty.push(this.$t(`第{index}项未选择商品`, {index: index+1}))
          return
        }
        if(!v.specsRecordVOList || !v.specsRecordVOList.length){
          this.$set(v, 'error', 1)
          empty.push(this.$t(`第{index}项未放入`, {index: index+1}))
        }
        v.errFields = []
        Object.keys(fields).forEach(key => {
          if(!v[key]){
            v.errFields.push(key)
            empty.push(`${v.title} ${fields[key]} 未填写`)
          }
        })
        this.$set(v, 'errFields', v.errFields)
      });
      this.$forceUpdate()
      if(empty.length){
        alert(empty.join("\n"))
        return false
      }
      return true
    },
    /*unitChage(value) {
      this.unitTitle = this.danweiRange.find(v => v.value === value)?.text || this.$t('箱')
    },*/

    /*// 计算体积
    handleVolume(item) {
      this.$nextTick(() => {
        const { c, k, g, specificationType, num } = item
        if (c && k && g&& specificationType && num) {
          let volume = (((specificationType === 1 || specificationType === '1') ? num : 1) * (c * k * g) / 1000000)
          volume = Math.max(volume, 0.01).toFixed(2)
          this.$set(item, 'volume', volume)
          this.$set(item, 'chargeVolume', volume)
        } else {
          this.$set(item, 'volume', 0)
          this.$set(item, 'chargeVolume', 0)
        }
        this.$forceUpdate()
      })
    },*/
    /*// 切换单位
    switchChange(item, index){
      if (item.specificationType === 1){
        this.$set(item, 'specificationType', 2)
      }else {
        this.$set(item, 'specificationType', 1)
      }
      this.handleVolume(item)
    },*/
    // 从入仓记录汇总数据
    calcTotal(records, field){
      return records.reduce((total, item) => {
        return total + Number(item[field] || 0)
      }, 0)
    },
    // 储位选择回调，因为回调页面的方法，需要通过页面中转来触发组件事件
    setRecordlocation(locationList, extra){
      this.$refs.putin && this.$refs.putin.setRecordlocation(locationList, extra)
    },
    // 从warehouseInInfo中提取储位信息
    showLocationName(orderLocationBackVOList){
      if(!orderLocationBackVOList) return ''
      let locations = []
      orderLocationBackVOList.forEach(item => {
        let locationName = (item.areaName || '') + (item.locationName || '')
        if(!locationName && item.code){
          locationName = item.code
        }
        locations.push(locationName)
      })
      return locations.join(',')
    },
    putin(warehouseInItem,product){
      // 携带拆出的入仓记录
      warehouseInItem.specsRecordVOList = this.getWarehouseInspecsRecordVOList(warehouseInItem.id)
      // 当前放入的入仓记录
      this.currentPutin = warehouseInItem
      // 当前放入的品名
      this.currentPutinProduct = product
      this.$nextTick(this.$refs.putin.open)
    },
    closePutin(){
      this.currentPutin = null
      this.currentPutinProduct = null
      this.$refs.putin.close()
    },
    // 放入回调
    handlePutin(list){
      const product = this.currentPutinProduct
      if(!product.specsRecordVOList){
        product.specsRecordVOList = []
      }
      if(!list || !list.length) return false
      list.forEach(item => {
        product.specsRecordVOList.push({
          ...item,
          warehouseInId: this.currentPutin.id,
          boxGauge: `${item.c||''}*${item.k||''}*${item.g||''}`,
        })
      })

      this.calcDefaultData(product)

      this.closePutin()
    },
    // 计算品名的默认收费方数和收费重量、货值
    calcDefaultData(product){
      // 清空本品名下的收费数据和货值，方便重新计算
      this.$set(product, 'chargeVolume', 0)
      this.$set(product, 'chargeWeight', 0)
      this.$set(product, 'worth', 0)

      this.$nextTick(() => {
        console.log('orderItemLeftData num', this.getOrderItemLeftData(product.orderItem, 'num'))
        console.log('orderItemLeftData chargeWeight', this.getOrderItemLeftData(product.orderItem, 'chargeWeight'))
        // 如果箱数拆完，则收费体积重量货值默认取品名的全部数据，否则按照比例计算
        if(this.getOrderItemLeftData(product.orderItem, 'num') === 0){
          this.$set(product, 'chargeVolume', this.getOrderItemLeftData(product.orderItem, 'chargeVolume'))
          this.$set(product, 'chargeWeight', this.getOrderItemLeftData(product.orderItem, 'chargeWeight'))
          // this.$set(product, 'worth', this.getOrderItemLeftData(product.orderItem, 'worth'))
        }else{
          // 计算默认的收费方数和收费重量
          const rate = this.calcTotal(product.specsRecordVOList, 'num') / product.orderItem.warehouseInInfoVO.cartonsNum
          /*
          * 1 普货 2 重货 3 泡货
          * 普货 收费数据=入仓数据
          * 泡货 收费方数=入仓方数 收费重量 = 品名收费重量*比例
          * 重货 收费方数=品名收费方数*比例 收费重量 = 入仓重量
          * */
          const chargeVolume = product.orderItem.itemType === 2 ? (product.orderItem.chargeVolume*rate).toFixed(2) : this.getSplitTotal(product.specsRecordVOList, 'volume')
          const chargeWeight = product.orderItem.itemType === 3 ? (product.orderItem.chargeWeight*rate).toFixed(2) : this.getSplitTotal(product.specsRecordVOList, 'weight')

          this.$set(product, 'chargeVolume', chargeVolume)
          this.$set(product, 'chargeWeight', chargeWeight)
        }

        let num = this.getSplitTotal(product.specsRecordVOList, 'num')
        let worth = this.parentOrder.costVO.totalWorth * num/this.parentOrder.sumNum
        this.$set(product, 'worth', worth.toFixed(2))
      })
    },
    // 删除拆出记录
    delSpecsRecord(product, index){
      product.specsRecordVOList.splice(index, 1)
      this.calcDefaultData(product)
    },
    // 清空入仓记录
    clearAll(product){
      confirm(this.$t('确定要清空么？'), this.$t('提示')).then(res => {
        product.specsRecordVOList = []
        this.calcDefaultData(product)
      })
    },
    back(){
      uni.navigateBack()
    }
  },
};
</script>

<style lang="scss" scoped>
.error{
  border: 1px solid red;
}
.justify-end {
  justify-content: flex-end;
}
.action {
  padding-left: 10upx;
}
.content {
  &.title-bolder {
    color: #333333;
    font-weight: bolder;
  }
}
.card-row{
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  text{
    margin:0 10rpx;
  }
}
/*.add-row-btn {
  border: 0.5px solid #eee;
  text-align: center;
  line-height: 30px;
  border-radius: 5px;
  margin:15px;
  ::v-deep .uni-icons {
    vertical-align: bottom;
    margin-right: 8px;
  }
}*/
/*.delete-btn {
  width: 72px;
  line-height: 30px;
  border: 0.5px solid #007aff;
  text-align: center;
  border-radius: 15px;
  color: #007aff;
  margin-left: auto;
}*/
.item-content {
  text-align: left;
  padding: 10px 20px 0px 20px;

  &.noPadding {
    padding: 0;
  }

  > view {
    display: flex;
    padding: 4px 0;

    > view {
      flex: 1;
      word-break: break-all;
      padding-left: 4px;
    }
  }
  .flex{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left{
      flex: 1;
    }
  }
  .btn{
    background-color: rgb(47, 77, 174);
    color: #fff;
    border-radius: 5rpx;
    padding: 5rpx 10rpx;
    margin-left: 10px;
  }
}
.section-title{
  font-size: 30rpx;
  font-weight: bold;
  padding: 20rpx;
}
</style>

