<template>
  <el-drawer
    v-loading="load"
    :title="'订单发货（共'+data.length+'单）'"
    :visible.sync="drawer"
    :direction="direction"
    size="50%">
    <div class="content">
      <div class="order-cont" v-if="data && data[0]">
        <div class="cont-left">
          <div class="order-code">订单号：{{data[0].id}}</div>
          <div class="order-other">
            <div class="receive-name">姓名：{{data[0].receiverName}}</div>
            <div class="address">目的地：<span>{{data[0].receiverProvince+'-'+data[0].receiverCity}}</span></div>
            <!-- <div class="time">预计送达：8月6日 12:00前</div> -->
          </div>
        </div>
        <!-- <i class="el-icon-arrow-right"></i> -->
      </div>
      <deliveryGoodsInfo :hideOrderCode="true" :sendState="true" @editState="editState" @editResult="editResult" ref="info" />
      <deliveryPrice v-if="priceData && priceData.length > 0" :data="priceData" :currentValue="currentPrice" @prichChange="prichChange" />
    </div>
    <div class="space"></div>
    <div class="deli-footer">
      <div class="d-left">
        <div class="estimate-total">
          预计总价<span class="total">￥{{currentPrice.estimateFreight?currentPrice.estimateFreight:'0.00'}}</span> 
          <!-- <span class="detail">明细></span> -->
        </div>
        <div class="agreement">
          <el-checkbox v-model="checked">已读并同意《XXX电子运单协议》</el-checkbox>
        </div>
      </div>
      <div class="send-btn" @click="btn">确认发货</div>
    </div>
  </el-drawer>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import DeliveryGoodsInfo from "./deliveryGoodsInfo.vue";
import DeliveryPrice from "./deliveryPrice.vue";
import { add,multiply,subtract,divide } from '@/benyun/utils/accuracy'
import { getMultipleToOnePrice,addMultipleToOne,getInventoryByStoreHouseIdAndSkuids } from  '@/api/delivery'
import Format from '@/benyun/utils/dateFormat'
@Component({components:{DeliveryGoodsInfo,DeliveryPrice}})
export default class CarpoolModal extends Vue {
  drawer=false;
  direction='rtl'
  checked=false;
  stopHandle=false;
  load=false;
  onAct='1';
  data:Array<any>=[];
  priceData:Array<any>=[]
  currentPrice:any={}
  value:any={};
  setShow(v:boolean){
    this.drawer=v;
    this.stopHandle = false;
    this.priceData=[];
    this.currentPrice={}
  }
  setValue(data:Array<any>){
    this.data =data;
    this.value={};
    this.value.tmsTransportMethod = '整车';
    // this.value.tmsBusinessMan = (this as any).$store.getters.userInfo.userName;
    // this.value.tmsBusinessPhone = (this as any).$store.getters.userInfo.phonenumber;
    this.value.subItem=[];
    this.value.tmsUnloadingProvince=data[0].receiverProvince;
    this.value.tmsUnloadingProvinceNo=data[0].receiverProvinceCode;
    this.value.tmsUnloadingCity=data[0].receiverCity;
    this.value.tmsUnloadingCityNo=data[0].receiverCityCode;
    this.value.tmsUnloadingRegion=data[0].receiverDistrict;
    this.value.tmsUnloadingRegionNo=data[0].receiverDistrictCode;
    this.value.tmsUnloadingStreet=data[0].receiverTown;
    this.value.tmsUnloadingStreetNo=data[0].receiverTownCode;
    this.value.tmsUnloadingAddress=data[0].receiverAddress;
    this.value.tmsUnloadingConsignor=data[0].receiverName;
    this.value.tmsUnloadingContacts=data[0].receiverMobile;
    this.checked = false;
    const requestId =  new Date().getTime() + this.getUuid();
    this.value.requestId = requestId;
    for(let item of data){     
      if(item.items){
        for(const i of item.items){
          let total:any = 0;
          if(Number(i.qty) && Number(i.price)){
            total = multiply(Number(i.qty),Number(i.price))
          }
          this.value.subItem.push({
            requestId:requestId,
            omsOrderId:item.id,
            omsOrderItemId:i.itemId,
            tmsGoodsModel:i.styleId,
            tmsGoodsCode:i.skuId,
            // omsOrderItemSkuId:i.itemId,
            tmsQuantity:Number(i.qty)?Number(i.qty):0,
            tmsGoodsTotalPrice:total,
            name:i.name,
            price:i.price,
            weight:i.weight
          })
        }
      }
    }
    this.$nextTick(()=>{
      (this.$refs.info as any).setValue(this.value);
      this.drawer = false;
      (this.$refs.info as any).showModal = true;
    })
  }
  getUuid(){
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  prichChange(index:number){
    this.currentPrice = this.priceData[index];
    this.$forceUpdate();
  }
  getPriceInfo(data:any){
    let params:any={};
    params.startStoreHouseId = data.storeHouseId;
    // params.startAddressCode = data.tmsShipmentCityNo + '00000';
    params.endAddressCode = data.tmsUnloadingCityNo + '00000';
    params.planType = data.tmsTransportMethod;
    params.omsIds=[];
    for(const item of this.data){
      params.omsIds.push(item.id);
    }
    this.load = true;
    getMultipleToOnePrice(params).then((res:any) => {
      this.load=false;
      let current:any=null;
      for(let item of res.data[0].data){
        let d = new Date().getTime() + item.duration*60*60*1000;
        item.endTime=Format(new Date(d),'MM月dd日 HH:mm');
        if(!current) current = item;
        if(Number(current.estimateFreight) > Number(item.estimateFreight)){
          current = item
        }
      }
      this.priceData = res.data[0].data;
      this.currentPrice = current;
    }).catch((err:any)=>{
      this.load = false;
    })
  }
  btn(){
    // if(this.stopHandle){
    //   this.$message('库存不足！')
    //   return
    // }
    if(!this.checked){
      this.$message('请阅读并同意运单协议！')
      return
    }
    if(!this.value.tmsBusinessMan || !this.value.tmsBusinessPhone || !this.value.tmsShipmentConsignor || !this.value.tmsShipmentContacts || !this.value.tmsUnloadingConsignor || !this.value.tmsUnloadingContacts || !this.value.tmsUnloadingProvince || !this.value.tmsUnloadingAddress || !this.value.storeHouseId){
      this.$message("请编辑订单信息");
      return
    }
    let params:any=(this as any).$lodash.cloneDeep(this.value);
    if(this.priceData){
      try{
        params.pricePlan = JSON.stringify(this.priceData)
      }catch(e){}
    }
    if(this.currentPrice){
      params.priceId = this.currentPrice.id;
    }
    params.omsOrderIds=[]
    for(const item of this.data){
      params.omsOrderIds.push(item.id);
    }
    params.tmsMaterials=[];
    if(this.value.subItem){
      for(const item of this.value.subItem){
        params.tmsMaterials.push({
          storeHouseId:this.value.storeHouseId,
          materialSkuId:item.omsOrderItemId,
          qty: item.tmsQuantity
        })
      }
    }
    delete params.subItem;
    this.load = true;
    addMultipleToOne(params).then((res:any) => {
      this.load = false;
      if(res.code == 200){
        this.$message({
          message:'订单发货成功！',
          type:'success'
        })
        this.$emit('handleSuccess');
        this.drawer=false;
      }
    }).catch(()=>{  
      this.load = false;
    })
  }
  //查库存
  getStoreCount(item:any,callback?:Function){
    let params:any={};
    params.storeHouseId = item.storeHouseId;
    params.skuIds=[]
    if(item.subItem){
      for(const i of item.subItem){
        if(params.skuIds.indexOf(i.omsOrderItemId) == -1){
          params.skuIds.push(i.omsOrderItemId)
        }
      }
    }
    this.load = true;
    getInventoryByStoreHouseIdAndSkuids(params).then((res:any) => {
      this.load = false;
      let m='';
      for(const i of item.subItem){
        for(const d of res.data){
          let s = Number(d.inventory) - Number(d.useInventory) - Number(i.tmsQuantity);
          if(i.omsOrderItemId == d.skuid && s < 0){
            m = m ? m + ',' + i.name : i.name;          
          }else{
            d.inventory = subtract(d.inventory, i.tmsQuantity);
          }
        }
      }
      if(m){
        this.$message({
          message:'商品“'+m+'”库存不足！',
          type:'error'
        })
        this.stopHandle = true;
        return
      }
    }).catch(()=>{
      this.load = false;
    })
  }
  editResult(v:any){
    this.value = v;
    this.getPriceInfo(v);
    // this.getStoreCount(v);
  }
  editState(v:boolean){
    this.drawer = v
  }
}
</script>

<style lang="scss" scoped>
.content{
  width: 100%;
  box-sizing: border-box;
  padding: 0 16px;
  background-color: #FFF;
  .order-cont{
    height: 60px;
    width: 100%;
    box-sizing: border-box;
    border:solid 1px #BBB;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
    margin-bottom: 16px;
    cursor: pointer;
    .cont-left{
      // width: calc(100% - 40px);
      width: 100%;
      .order-code{
        width: 100%;
        font-size: 14px;
        padding: 6px 0 4px;
      }
      .order-other{
        width: 100%;
        display: flex;
        font-size: 14px;
        .receive-name{
          width: 150px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .address{
          width: calc(100% - 150px);
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          span{
            color: #F00;
          }
        }
        // .time{
        //   width: calc(100% - 120px - 150px);
        // }
      }
    }
  }
  .order-cont:hover,.onAct{
    background-color: rgba(160,205,255,0.22);
  }
}
.deli-footer{
  height: 60px;
  width: 100%;
  padding: 0 16px;
  box-sizing: border-box;
  box-shadow: 0 -5px 10px #EEE;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: absolute;
  background-color: #FFF;
  left: 0;
  bottom: 0;
  z-index: 10;
  .d-left{
    width: 70%;
    .estimate-total{
      font-size: 14px;
      padding-bottom: 4px;
      .total{
        font-size: 16px;
        color: #F00;
      }
      .detail{
        color: #1684FC;
        padding-left: 16px;
        cursor: pointer;
      }
    }
  }
  .send-btn{
    width: 120px;
    height: 40px;
    line-height: 40px;
    border-radius: 8px;
    background: linear-gradient(129.2deg, rgba(22,132,252,1) 9.81%,rgba(93,167,249,1) 97.4%);
    color: rgba(255, 255, 255, 100);
    font-size: 14px;
    text-align: center;
    box-shadow: 0px 2px 6px 0px rgba(93, 167, 249, 100);
    cursor: pointer;
  }
}
.space{
  height: 60px;
  width: 100%;
  margin-top: 16px;
}
</style>