<template>
  <!--放入弹层-->
  <uni-popup ref="putin">
    <view class="popup-content" v-if="warehouseInItem">
      <view style="padding: 10rpx">
        {{$t("可拆数据")}}：
        {{$t("箱数")}}:{{canSplitNum}}，
        {{$t('体积')}}：{{getWarehouseLeftData('volume')}}m³，
        {{$t('重量')}}：{{getWarehouseLeftData('weight')}}kg，
        {{$t('数量(个)')}}：{{getWarehouseLeftData('quantity')}}
      </view>
      <uni-card class="add-popup-card" v-for="(item, index) in list" :key="index">
        <view class="card-row">
          <uni-easyinput v-model="item.num" type="number" :placeholder="$t('箱数')" :clearable="false" @input="calc(item)"/>
          <switch :checked="item.specificationType === 1" @change="switchChange(item)" />
          <dict-tag :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" :value="item.specificationType + ''"/>
          <uni-easyinput v-model="item.weight" type="number" :placeholder="$t('重量')" :clearable="false"/>
          <text>KG</text>
          <uni-easyinput v-model="item.quantity" type="number" :placeholder="$t('个数')" :clearable="false"/>
          <text>{{$t('个')}}</text>
        </view>
        <view class="card-row">
          <uni-easyinput v-model="item.c" type="number" :placeholder="$t('长')" :clearable="false" @input="handleVolume(item)"/>
          <text>*</text>
          <uni-easyinput v-model="item.k" type="number" :placeholder="$t('宽')" :clearable="false" @input="handleVolume(item)"/>
          <text>*</text>
          <uni-easyinput v-model="item.g" type="number" :placeholder="$t('高')" :clearable="false" @input="handleVolume(item)"/>
          <text>=</text>
          <uni-easyinput v-model="item.volume" type="number" placeholder="" :clearable="false" />
          <text>CBM</text>
        </view>
        <view v-if="index" class="delete-btn" @tap="delRow(index)">{{$t('删除')}}</view>
        <view class="cu-form-group">
          <view class="title">{{$t('储位')}}</view>
          <view class="content" @tap="toLocation(index)" style="flex:1;justify-content: flex-end;">
            {{ item.orderLocationList && item.orderLocationList.length ? item.orderLocationList.map(v => v.code ||  v.areaName + (v.locationName || '')).join(',') : '' }}
            <uni-icons type="right" size="16"></uni-icons>
          </view>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('快递单号')}}</view>
          <view class="content">
            <easyinput v-model="item.expressNo"></easyinput>
          </view>
        </view>
      </uni-card>
      <view class="add-row-btn" @click="addRow">{{$t('增加一行')}}</view>
      <view class="flex">
        <!--<button size="mini" type="warn" @click="addRow">增加</button>-->
        <button size="mini" type="primary" @click="confirm">确定</button>
        <button size="mini" @click="$emit('close')">取消</button>
      </view>
    </view>
  </uni-popup>
</template>
<script>
import Decimal from "decimal.js";
import { alert, msg } from "@/util/tools";
import Easyinput from "@/components/easyinput/easyinput.vue";

export default{
  components: { Easyinput },
  props:{
    // 仓库ID，选择储位需要
    warehouseId: Number,
    // 入仓记录
    warehouseInItem: Object,
    // 最大可拆箱数
    maxNum: Number
  },
  data(){
    return {
      // 入仓记录
      list:[]
    }
  },
  computed:{
    // 获取入仓记录的剩余数据, contain表示是否包含本页的数据
    getWarehouseLeftData(){
      return (field, contain = false) => {
        let warehouseInField = field
        if(field === 'num') warehouseInField = 'cartonsNum'
        if(field === 'quantity') warehouseInField = 'quantityAll'
        let total = new Decimal(this.warehouseInItem[ warehouseInField ] || 0)

        // 对已添加的记录累减
        this.warehouseInItem.specsRecordVOList.forEach(item => {
          total = total.minus(new Decimal(item[field] || 0))
        })
        // 对本页的数据累减
        if(contain){
          this.list.forEach(item => {
            total = total.minus(new Decimal(item[field] || 0))
          })
        }

        return total.toNumber()
      }
    },
    // 计算本页面拆出的总数
    getSplitTotal() {
      return field => {
        let total = new Decimal(0)
        this.list.forEach(item => {
          total = total.plus(new Decimal(item[field] || 0))
        })
        return total.toNumber()
      }
    },
    // 可拆箱数
    canSplitNum(){
      return Math.min(this.getWarehouseLeftData('num'), this.maxNum)
    }
  },
  methods:{
    addRow(){
      if(this.canSplitNum - this.getSplitTotal('num') <=0 ){
        return msg(this.$t('已达到最大可拆箱数'))
      }
      let orderLocationList = this.warehouseInItem.orderLocationBackVOList
      if(this.list.length){
        orderLocationList = this.list[this.list.length - 1].orderLocationList
      }
      const [c,k,g] = this.warehouseInItem.boxGauge.split('*')
      const row = {
        specificationType: this.warehouseInItem.specificationType,
        num: this.canSplitNum - this.getSplitTotal('num'),
        volume: this.getWarehouseLeftData('volume', true),
        weight: this.getWarehouseLeftData('weight', true),
        quantity: this.getWarehouseLeftData('quantity', true),
        c, k, g,
        expressNo: this.warehouseInItem.expressNo,
        unit: this.warehouseInItem.unit,
        orderLocationList
      }
      // 根据规则计算体积重量和数量
      this.calc(row)
      // 添加一条默认数据
      this.list.push(row)
    },
    confirm(){
      // 检查空值
      let fields = {
        'num': this.$t('箱数'), 'weight': this.$t('重量'), 'volume': this.$t('体积'), 'c':this.$t('长'), 'k': this.$t('宽'), 'g': this.$t('高')
      }
      let errors = []
      this.list.forEach((item, index) => {
        Object.keys(fields).forEach(field => {
          if(!item[field]){
            errors.push(this.$t(`第{index}行{field}不能为空`, {
              index: index + 1,
              field: fields[field]
            }))
          }
        })
      })
      if(errors.length){
        return alert(errors.join("\n"), this.$t("提示"))
      }

      // 计算拆出数据不能超过可拆数据
      if(this.getSplitTotal('num') > this.canSplitNum){
        return msg(this.$t("拆出箱数不能超过可拆箱数"))
      }
      if(this.getSplitTotal('volume') > this.getWarehouseLeftData('volume')){
        return msg(this.$t("拆出体积不能超过可拆体积"))
      }
      if(this.getSplitTotal('weight') > this.getWarehouseLeftData('weight')){
        return msg(this.$t("拆出重量不能超过可拆重量"))
      }

      this.$emit('submit', this.list)
    },
    open(){
      this.$refs.putin.open()
      this.list = []
      this.$nextTick(this.addRow)
    },
    close(){
      this.$refs.putin.close()
    },
    // 根据规则计算体积重量和数量
    calc(item){
      this.$nextTick(() => {
        // 计算重量
        const rate = new Decimal(item.num || 0).div(this.warehouseInItem.cartonsNum)
        console.log(item, {rate})
        item.weight = rate.times(this.warehouseInItem.weight).toNumber().toFixed(2)
        item.quantity = rate.times(this.warehouseInItem.quantityAll || 0).toNumber().toFixed(0)
        item.volume = rate.times(this.warehouseInItem.volume).toNumber().toFixed(2)

        // 如果标记了按照规格计算体积，则重新计算体积
        if(item.calcVolumeByBoxGauge){
          this.handleVolume(item)
        }
      })
    },
    // 计算体积
    handleVolume(item) {
      this.$nextTick(() => {
        // 标记按照规格计算体积
        this.$set(item, 'calcVolumeByBoxGauge', 1)
        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)
          console.log({volume}, num)
          this.$set(item, 'volume', volume)
        } else {
          this.$set(item, 'volume', 0)
        }
        this.$forceUpdate()
      })
    },
    switchChange(item){
      this.$set(item, 'specificationType', item.specificationType === 1 ? 2 : 1)
      console.log(item)
      this.handleVolume(item)
    },
    // 跳转储位选择
    toLocation(index){
      const warehouseId = this.warehouseId
      if(!warehouseId){
        return uni.showToast({title: this.$t('获取仓库信息失败')})
      }
      const item = this.list[index]

      let url = `../warehousing/location?warehouseId=${warehouseId}&orderId=&locationList=${JSON.stringify(item.orderLocationList || [])}&extra=${index}&callback=setRecordlocation`
      uni.navigateTo({
        url: url
      });
    },
    // 储位选择回调，通过宿主页面中转事件
    setRecordlocation(locationList, extra){
      this.$set(this.list[extra], 'orderLocationList', locationList || [])
    },
    // 从warehouseInInfo中提取储位信息
    showLocationName(orderLocationBackVOList){
      if(!orderLocationBackVOList) return ''
      let locations = []
      orderLocationBackVOList.forEach(item => {
        locations.push(item.areaName + (item.locationName || ''))
      })
      return locations.join(',')
    },
    delRow(index){
      this.list.splice(index, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
.popup-content{
  background: #FFFFFF;
  padding: 40rpx 0;
  border-radius: 10rpx;
  max-height: 80vh;
  width: 80vw;
  overflow-y: 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;
  }
}
.card-row{
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  text{
    margin:0 10rpx;
  }
}
.delete-btn {
  width: 72px;
  line-height: 30px;
  border: 0.5px solid #007aff;
  text-align: center;
  border-radius: 15px;
  color: #007aff;
  margin-left: auto;
}
.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;
  }
}
</style>