<template>
  <!-- 放入弹层 -->
  <el-dialog :title="$t('入仓记录放入确认')" :visible="show" :before-close="closeDialog" :close-on-click-modal="false" width="1500px" :append-to-body="appendToBody">
    <el-card>
      <div slot="header">{{$t('可拆出入仓记录')}}</div>
      <el-table :data="[warehouseRecord]">
        <el-table-column :label="$t('箱数')" prop="cartonsNum">
          <template slot-scope="{row}">{{Math.min(row.cartonsNum, maxNum)}}</template>
        </el-table-column>
        <el-table-column :label="$t('入仓类型')" prop="specificationType">
          <template slot-scope="{row}">
            <dict-tag :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" :value="row.specificationType" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('包装类型')" prop="unit">
          <template slot-scope="{row}">
            <dict-tag :type="DICT_TYPE.ECW_PACKAGING_TYPE" :value="row.unit" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('长')" prop="boxGauge">
          <template slot-scope="{row}">
            {{row.boxGauge.split('*')[0]}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('宽')" prop="boxGauge" >
          <template slot-scope="{row}">
            {{row.boxGauge.split('*')[1]}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('高')" prop="boxGauge" >
          <template slot-scope="{row}">
            {{row.boxGauge.split('*')[2]}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('体积') + '(m³)'" prop="volume" />
        <el-table-column :label="$t('重量') + '(kg)'" prop="weight" />
        <el-table-column :label="$t('数量（个）')" prop="quantityAll" />
        <el-table-column :label="$t('入仓快递单号')" prop="expressNo" />
        <el-table-column :label="$t('首次入仓时间')" prop="inTime" >
          <template slot-scope="{row}">{{row.inTime|parseTime}}</template>
        </el-table-column>
        <el-table-column :label="$t('储位')" prop="orderLocationBackVOList" >
          <template slot-scope="{row}">
            {{getLocationName(row.orderLocationBackVOList)}}
          </template>
        </el-table-column>
      </el-table>
      <div>
        {{$t('可拆')}}：
        {{maxSplitNum}}{{$t('箱')}}，
        {{$t('体积')}}：{{leftData('volume')}}m³，
        {{$t('重量')}}：{{leftData('weight')}}kg，
        {{$t('数量')}}：{{leftData('quantity')}}{{$t('个')}}
      </div>
    </el-card>
    <el-card class="box-card mt-10">
      <div slot="header" class="clearfix">
        <span>{{ $t('新入仓记录') }}</span>
        <el-button style="float: right;margin-left: 15px" size="mini" type="primary" icon="el-icon-minus" circle @click="deleteRow" :disabled="form.list.length <= 1"></el-button>
        <el-button style="float: right" size="mini" type="primary" icon="el-icon-plus" circle @click="addRow"></el-button>
      </div>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
      <el-table
        :data="form.list"
        style="width: 100%">
        <el-table-column :label="$t('箱数')" width="200px">
          <template v-slot:header>
            <span style="color: red">*</span>{{ $t('箱数') }}
          </template>
          <template v-slot="{row,$index}">
            <el-form-item class="flex" label-width="0"
                          :prop="`list.${$index}.num`"
                          :rules="{required: true, message: $t('不能为空'), trigger: 'blur'}">
              <!--需求方要求输入后马上计算其他数据，el组件无法绑定keyup事件，所以用原生的input-->
              <!--<el-input-number controls-position="right" :min="0" class="w-75 tight" v-model="row.num" :max="warehouseRecord.cartonsNum" @keyup.native="calc(row)"></el-input-number>-->
              <input class="input" v-model="row.num" type="number" @keyup="calc(row)" @change="calc(row)" :min="1" :max="maxSplitNum"></input>
              <dict-selector class="w-75" :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" v-model="row.specificationType" defaultable></dict-selector>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('包装类型')" width="100px">
          <template v-slot:header>
            <span style="color: red">*</span>{{ $t('包装类型') }}
          </template>
          <template v-slot="{row,$index}">
            <el-form-item  label-width="0">
              <dict-selector :type="DICT_TYPE.ECW_PACKAGING_TYPE" v-model="row.unit" defaultable></dict-selector>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="长(cm)">
          <template v-slot:header>
            <span>{{ $t('长') }}</span>(cm)
          </template>
          <template v-slot="{row,$index}">
            <el-form-item  label-width="0">
              <input class="input" v-model="row.boxGauge1" type="number" @keyup="calcVolume(row)" @change="calcVolume(row)" :min="0"></input>
              <!--<el-input-number controls-position="right" :min="0" class="w-100 tight"  v-model="row.boxGauge1" @blur="calcVolume(row)"/>-->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="宽(cm)">
          <template v-slot:header>
            <span>{{ $t('宽') }}</span>(cm)
          </template>
          <template v-slot="{row,$index}">
            <el-form-item  label-width="0">
              <input class="input" v-model="row.boxGauge2" type="number" @keyup="calcVolume(row)" @change="calcVolume(row)" :min="0"></input>
              <!--<el-input-number controls-position="right" :min="0" class="w-100 tight" v-model="row.boxGauge2" @blur="calcVolume(row)" />-->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="高(cm)">
          <template v-slot:header>
            <span>{{ $t('高') }}</span>(cm)
          </template>
          <template v-slot="{row,$index}">
            <el-form-item  label-width="0">
              <input class="input" v-model="row.boxGauge3" type="number" @keyup="calcVolume(row)" @change="calcVolume(row)" :min="0"></input>
              <!--<el-input-number controls-position="right" :min="0" class="w-100 tight" v-model="row.boxGauge3" @blur="calcVolume(row)"/>-->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="入仓体积(m³)">
          <template v-slot:header>
            <span style="color: red">*</span> <span>{{ $t('体积') }}</span>(m³)
          </template>
          <template v-slot="{row,$index}">
            <el-form-item label-width="0"
                          :prop="`list.${$index}.volume`"
                          :rules="{required: true, message: $t('不能为空'), trigger: 'blur'}">
              <el-input-number controls-position="right" :min="0.01" :max="warehouseRecord.volume" class="w-100 tight" v-model="row.volume"/>
            </el-form-item>
          </template>
        </el-table-column>
        <!--<el-table-column label="收费体积(m³)">
          <template v-slot:header>
            <span style="color: red">*</span> <span>{{ $t('收费体积') }}</span>(m³)
          </template>
          <template v-slot="{row,$index}">
            <el-form-item label-width="0"
                          :prop="`list.${$index}.chargeVolume`"
                          :rules="{required: true, message: $t('不能为空'), trigger: 'blur'}">
              <el-input-number controls-position="right" :min="0" class="w-100 tight" v-model="row.chargeVolume"/>
            </el-form-item>
          </template>
        </el-table-column>-->
        <el-table-column label="入仓重量(Kg)">
          <template v-slot:header>
            <span style="color: red">*</span> <span>{{ $t('入仓重量') }}</span>(Kg)
          </template>
          <template v-slot="{row,$index}">
            <el-form-item label-width="0"
                          :prop="`list.${$index}.weight`"
                          :rules="{required: true, message: $t('不能为空'), trigger: 'blur'}">
              <el-input-number controls-position="right" :min="0.01" :max="warehouseRecord.weight" class="w-75 tight" v-model="row.weight"/>
            </el-form-item>
          </template>
        </el-table-column>
        <!--<el-table-column label="收费重量(Kg)">
          <template v-slot:header>
            <span style="color: red">*</span> <span>{{ $t('收费重量') }}</span>(Kg)
          </template>
          <template v-slot="{row,$index}">
            <el-form-item label-width="0"
                          :prop="`list.${$index}.chargeWeight`"
                          :rules="{required: true, message: $t('不能为空'), trigger: 'blur'}">
              <el-input-number controls-position="right" :min="0" class="w-75 tight" v-model="row.chargeWeight" type="number"/>
            </el-form-item>
          </template>
        </el-table-column>-->
        <el-table-column :label="$t('数量')" width="130px">
          <template v-slot="{row,$index}">
            <el-form-item label-width="0"
                          :prop="`list.${$index}.quantity`"
                          :rules="{required: false, message: $t('不能为空'), trigger: 'blur'}">
              <el-input-number controls-position="right" :min="0" :max="warehouseRecord.quantityAll > 0 ? warehouseRecord.quantityAll : null" class="w-75 tight" v-model.number="row.quantity" />{{ $t('个') }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('快递单号')">
          <template v-slot="{row,$index}">
            <el-form-item label-width="0">
              <el-input v-model="row.expressNo"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('储位')" prop="orderLocationBackVOList">
          <template v-slot="{ row, column, $index }">
            <!--<el-button type="primary" size="mini" @click="showLocation(row, $index)">{{ $t('选择储位') }}</el-button>-->
            <warehouse-area-select
              v-model="row.orderLocationList"
              :warehouse-id="warehouseId"
            ></warehouse-area-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')">
          <template v-slot="{ row, column, $index}">
            <el-popconfirm
              v-if="$index > 0"
              :title="$t('确定要删除该行入仓记录吗？')"
              @confirm="deleteRow($index)"
            >
              <template v-slot:reference>
                <el-button size="mini" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      </el-form>
    </el-card>
    <div slot="footer">
      <el-button type="primary" @click="submit">{{ $t('确定') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import WarehouseAreaSelect from "@/components/WarehouseAreaSelect/index.vue";
import {parseTime} from '@/utils/ruoyi'
import Decimal from 'decimal.js'
import Template from "@/views/cms/template/index.vue";
export default {
  name: "Putin",
  filters:{parseTime},
  components: {Template, WarehouseAreaSelect},
  props:{
    warehouseRecord:Object,
    appendToBody: Boolean,
    // 仓库ID，选择储位要用到
    warehouseId: Number,
    // 数量是否必须
    quantityshow: Boolean,
    // 最大可拆箱数，装柜拆单用
    maxNum: Number,
  },
  data(){
    return {
      show: false,
      // 拆出的入仓记录
      form:{
        list:[]
      }
    }
  },
  computed:{
    // 计算当前添加的多条入仓记录总拆出数据
    splitTotal(){
      return field => {
        let total = new Decimal(0)
        this.form.list.forEach(item => {
          total = total.plus(new Decimal(item[field] || 0))
        })
        return total.toNumber()
      }
    },
    // 计算此入仓记录全部拆出的数量,包含其他拆单订单的
    totalSplitSum(){
      return field => {
        let total = new Decimal(0)
        if(this.warehouseRecord.specsRecordVOList && this.warehouseRecord.specsRecordVOList.length){
          this.warehouseRecord.specsRecordVOList.forEach(item => {
            total = total.plus(new Decimal(item[field] || 0))
          })
        }
        return total.plus(new Decimal(this.splitTotal('num'))).toNumber()
      }
    },
    // 剩余数据
    leftData(){
      return (field, containNew = false) => {
        // 入仓记录跟拆单记录的箱数字段不同，要做特殊处理
        let warehouseField = field
        if(field == 'num') warehouseField = 'cartonsNum'
        if(field == 'quantity') warehouseField = 'quantityAll'
        let left = new Decimal(this.warehouseRecord[warehouseField] || 0)
        // 累减已拆记录
        if(this.warehouseRecord.specsRecordVOList && this.warehouseRecord.specsRecordVOList.length){
          this.warehouseRecord.specsRecordVOList.forEach(item => {
            left = left.minus(new Decimal(item[field] || 0))
          })
        }
        // 如果是包含新数据（本次放入数据）
        if(containNew){
          // 累减本页添加的入仓记录
          this.form.list.forEach(item => {
            left = left.minus(new Decimal(item[field] || 0))
          })
        }

        return left.toNumber()
      }
    },
    // 可拆箱数
    maxSplitNum(){
      return Math.min(this.maxNum, this.leftData('num'))
    }
  },
  mounted() {
    this.show = true
    this.$nextTick(this.addRow)
  },
  methods:{
    // 添加一行
    addRow(){
      let { specificationType, boxGauge1, boxGauge2, boxGauge3, expressNo, unit } = this.warehouseRecord
      let num = Math.min(this.leftData('num', true), this.maxSplitNum)
      let orderLocationList = this.warehouseRecord.orderLocationBackVOList
      if(this.form.list.length){
        orderLocationList = this.form.list[this.form.list.length - 1].orderLocationList
      }
      // 根据入仓记录添加一行
      let row = {
        warehouseInId: this.warehouseRecord.id,
        specificationType, boxGauge1, boxGauge2, boxGauge3, expressNo,unit,
        volume: 0,
        weight: 0,
        num: num,
        quantity: 0,
        orderLocationList
      }
      // 如果拆完了则剩下的全部放入，否则按照比例计算
      this.$nextTick(() =>{
        if(this.leftData('num', true) <= 0 ) {
          row.volume = this.leftData('volume', true)
          row.weight = this.leftData('weight', true)
          row.quantity = this.leftData('quantity', true)
        }else{
          // 按照比例计算重量体积和数量
          this.calc(row)
        }
      })

      this.form.list.push(row)
    },
    // 删除一行，可选参数index表上行号，参数不是数字则删除最后一行
    deleteRow(index){
      const spliceIndex = typeof index !== 'number' ? this.list - 1 : index
      this.form.list.splice(spliceIndex, 1)
    },
    // 计算体积
    calcVolume(row){
      // 改了规格后按照规格计算体积
      this.$set(row, 'calcVolumeByBoxGauge', 1)

      let volume = Decimal(row.boxGauge1 || 0)
        .times(Decimal(row.boxGauge2 || 0))
        .times(Decimal(row.boxGauge3 || 0)).div(1000000)
      // 如果是箱的单位要乘以箱数
      if(+row.specificationType === 1) {
        volume = volume.times(Decimal(row.num || 0))
      }

      // 最低0.01
      volume = Math.max(0.01, volume.toNumber().toFixed(2))
      this.$set(row, 'volume', volume)
    },
    // 获取储位名称
    getLocationName(locationArr){
      if(!locationArr || !locationArr.length) return ''
      let arr = []
      locationArr.forEach(item => {
        arr.push(`${item.areaName || ''}${item.locationName || ''}`)
      })
      return Array.from(new Set(arr)).join(",")
    },
    // 根据箱数计算体积，重量,数量
    calc(row){
      const rate = row.num / this.warehouseRecord.cartonsNum

      row.volume = (this.warehouseRecord.volume * rate).toFixed(2)
      row.weight = (this.warehouseRecord.weight * rate).toFixed(2)
      row.quantity = (this.warehouseRecord.quantityAll * rate).toFixed(0)

      // 如果是按照规格计算体积，则重新计算
      if(row.calcVolumeByBoxGauge){
        this.calcVolume(row)
      }
    },
    closeDialog(){
      this.show = false
      this.$emit('close');
    },
    submit(){
      this.$refs.form.validate(valid => {
        if(!valid){
          return false
        }

        if(this.splitTotal('num') > this.maxSplitNum){
          return this.$message.error("拆出箱数不能大于可拆箱数")
        }
        if(this.splitTotal('volume') > this.leftData('volume')){
          return this.$message.error("拆出体积不能大于剩余体积")
        }
        if(this.splitTotal('weight') > this.leftData('weight')){
          return this.$message.error("拆出重量不能大于剩余重量")
        }
        if(this.splitTotal('quantity') > this.leftData('quantity')){
          return this.$message.error("拆出数量不能大于剩余数量")
        }
        // 如果全拆（拆出箱数 == 原入仓箱数），则体积重量也需要全拆
        if(this.splitTotal('num') === this.warehouseRecord.cartonsNum){
          if(this.splitTotal('volume') !== this.warehouseRecord.volume){
            return this.$message.error("全拆拆出体积必须等于原入仓体积")
          }
          if(this.splitTotal('weight') !== this.warehouseRecord.weight){
            return this.$message.error("全拆拆出重量必须等于原入仓体积")
          }
        }
        this.$emit('submit', this.form.list)
      })

    }
  }
}
</script>

<style scoped>
.input{

  border: 1px solid #DCDFE6;
  padding: 5px 6px;
  border-radius: 5px;

}
</style>
