<template>
  <el-drawer v-loading="load" title="短驳生成单" :visible.sync="drawer" @close="close" :direction="direction" size="50%">
    <div class="content">
      <div class="order-top" v-if="data.length > 1">
        <el-pagination background :page-size="1" :current-page="currentOrder + 1" layout="prev, pager, next"
          @current-change="currentChange" :total="data.length">
        </el-pagination>
      </div>
      <deliveryGoodsInfo :hideOrderCode="true" @editState="editState" @editResult="editResult" @qtyChange="qtyChange"
        ref="info" />
      <!-- <deliveryPrice :data="priceObj[data[currentOrder].omsOrderIds]" ref="price" v-if="data[currentOrder] && priceObj[data[currentOrder].omsOrderIds]" 
      @prichChange="prichChange" :currentValue="currentPrice[data[currentOrder].omsOrderIds]" /> -->
    </div>
    <div class="space"></div>
    <div class="deli-footer">
      <div class="d-left">
        <!-- <div class="estimate-total">
          订单小计<span class="total">￥{{data[currentOrder] && currentPrice[data[currentOrder].omsOrderIds]?currentPrice[data[currentOrder].omsOrderIds].estimateFreight:'0.00'}}</span> 
        </div> -->
        <!-- <div class="agreement">
          <el-checkbox v-model="checked">已读并同意《XXX电子运单协议》</el-checkbox>
        </div> -->
      </div>
      <div class="btn-box">
        <div class="send-btn" @click="btn">提交</div>
      </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 { getShortBargePrice, WMSAddEntryOrder, getInventoryByStoreHouseIdAndSkuids } from '@/api/delivery'
import Format from '@/benyun/utils/dateFormat'

@Component({ components: { DeliveryGoodsInfo, DeliveryPrice } })
export default class BatchbyOneModal extends Vue {
  drawer = false;
  direction = 'rtl'
  checked = false;
  data: Array<any> = [];
  currentOrder = 0;
  isSuccess = false;
  stopHandle = false;
  load = false;
  priceObj: any = {};
  currentPrice: any = {};
  setShow(v: boolean) {
    this.drawer = v;
    this.priceObj = {};
    this.currentPrice = {};
    this.isSuccess = false;
    this.stopHandle = false;
    this.currentOrder = 0;
    this.checked = false;
  }
  close() {
    if (this.isSuccess) {
      this.$emit('handleSuccess');
    }
  }
  editResult(v: any) {
    this.data[this.currentOrder] = v;
    this.getStoreCount(v);
    // this.getPriceInfo(v);
  }
  prichChange(index: number) {
    this.currentPrice[this.data[this.currentOrder].omsOrderIds] = this.priceObj[this.data[this.currentOrder].omsOrderIds][index];
    this.$forceUpdate();
  }
  currentChange(v: number) {
    this.currentOrder = v - 1;
    this.$forceUpdate();
    this.$nextTick(() => {
      this.setInfo();
    })
  }
  setInfo() {
    (this.$refs.info as any).setValue(this.data[this.currentOrder]);
  }
  setValue(data: Array<any>) {
    this.data = [];
    const requestId = new Date().getTime() + this.getUuid()
    let obj: any = {
      // tmsBusinessMan: (this as any).$store.getters.userInfo.userName,
      // tmsBusinessPhone: (this as any).$store.getters.userInfo.phonenumber,
      requestId: requestId
    };
    obj.subItem = [];
    for (const item of data) {
      obj.subItem.push({
        requestId: requestId,
        barCode: item.barCode,
        omsOrderItemId: item.id,
        tmsGoodsModel: item.itemNumber,
        tmsGoodsCode: item.skuCode,
        tmsQuantity: 1,
        tmsGoodsTotalPrice: item.price,
        name: item.skuTitle,
        price: item.price,
        weight: item.weight
      })
    }

    this.data.push(obj)


    this.$nextTick(() => {
      (this.$refs.info as any).setValue(this.data[this.currentOrder])
    })
  }
  getUuid() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  btn() {
    // this.noSentOrder();
    if (!this.data[this.currentOrder]) {
      this.$message('没有需要发货的订单！')
      return
    }
    if (this.stopHandle) {
      this.$message('库存不足！')
      return
    }
    // if(!this.checked){
    //   this.$message('请阅读并同意运单协议！')
    //   return
    // }
    if (!this.data[this.currentOrder].tmsShipmentConsignor || !this.data[this.currentOrder].tmsUnloadingConsignor || !this.data[this.currentOrder].out_storeHouseId) {
      this.$message("请编辑订单信息");
      return
    }
    // if(!this.currentPrice[this.data[this.currentOrder].omsOrderIds]){
    //   this.$message("请选择价格！");
    //   return
    // }
    this.sendGoods(this.data[0]);
  }
  nextBtn() {
    if (this.stopHandle) {
      this.$message('库存不足！')
      return
    }
    // if(!this.checked){
    //   this.$message('请阅读并同意运单协议！')
    //   return
    // }
    const _value = this.data[this.currentOrder];
    if (!_value.tmsShipmentAddress || !_value.tmsShipmentConsignor || !_value.tmsUnloadingAddress || !_value.tmsUnloadingConsignor) {
      this.$message("请编辑订单信息");
      return
    }
    // if(!this.currentPrice[_value.omsOrderIds]){
    //   this.$message('请选择价格！')
    //   return
    // }
    if (_value.isSuccess) {
      this.$message('订单：' + _value.omsOrderIds + '已执行过发货操作！');
      return
    }
    this.sendGoods(_value, true);
  }
  qtyChange(v: any) {
    this.data[this.currentOrder] = v;
    this.getStoreCount(v);
    // this.getPriceInfo(v);
  }
  //查库存
  getStoreCount(item: any, callback?: Function) {
    if (!item) {
      return
    }
    if (!item.out_storeHouseId || item.subItem.length == 0) {
      return
    }
    let params: any = {};
    params.storeHouseId = item.out_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
      } else {
        this.stopHandle = false
      }
      if (callback) callback(item, this.sendGoods)
    }).catch(() => {
      this.load = false;
    })
  }
  //发货
  sendGoods(item: any, isNext?: boolean) {
    if (!item) {
      this.$message('信息不存在！')
      return
    }

    let params: any = (this as any).$lodash.cloneDeep(item);
    // if(this.priceObj[item.omsOrderIds]){
    //   try{
    //     params.pricePlan = JSON.stringify(this.priceObj[item.omsOrderIds])
    //   }catch(e){}
    // }
    // if(this.currentPrice[item.omsOrderIds]){
    //   params.priceId = this.currentPrice[item.omsOrderIds].id;
    // }
    params.tmsMaterials = [];
    if (item.subItem) {
      let skuIds: Array<any> = [];
      for (const i of item.subItem) {
        let ind = skuIds.indexOf(item.omsOrderItemId)
        if (ind == -1) {
          skuIds.push(item.omsOrderItemId);
          params.tmsMaterials.push({
            qty: i.tmsQuantity,
            materialSkuId: i.omsOrderItemId,
            storeHouseId: item.out_storeHouseId,
            storingLocationId: item.entry_storeHouseId
          })
        } else {
          for (let paramsItem of params.tmsMaterials) {
            if (paramsItem.materialSkuId == i.omsOrderItemId) {
              paramsItem.qty = add(Number(paramsItem.qty), Number(i.tmsQuantity))
              break
            }
          }
        }

      }
    }
    delete params.subItem;
    this.load = true;
    WMSAddEntryOrder(params).then((res: any) => {
      this.load = false;
      if (res.code == 200) {
        this.isSuccess = true;
        this.$message({
          message: '操作成功！',
          type: 'success'
        })
        this.drawer = false;

        this.$forceUpdate();
      }
    }).catch(() => {
      this.load = false;
    })
  }
  //寻找未发货订单
  noSentOrder() {
    this.currentOrder = this.data.length;
    for (let i = 0; i < this.data.length; i++) {
      if (!this.data[i].isSuccess) {
        this.currentOrder = i;
        break
      }
    }
    // if(this.data[this.currentOrder]){
    this.setInfo();
    // } 
  }
  setOnEditOrderInfo(ids: string) {
    let _value = this.data[0]
    for (const item of this.data) {
      if (ids.indexOf(item.omsOrderIds) > -1 && !item.isSuccess) {
        item.orderType = _value.orderType;
        item.storeHouseId = _value.storeHouseId;
        item.tmsArrivalDate = _value.tmsArrivalDate;
        item.tmsDeliveryDate = _value.tmsDeliveryDate;
        item.tmsTransportMethod = _value.tmsTransportMethod;
        item.tmsBusinessMan = _value.tmsBusinessMan;
        item.tmsBusinessPhone = _value.tmsBusinessPhone;
        item.tmsShipmentConsignor = _value.tmsShipmentConsignor;
        item.tmsShipmentContacts = _value.tmsShipmentContacts;
        item.tmsShipmentProvince = _value.tmsShipmentProvince;
        item.tmsShipmentProvinceNo = _value.tmsShipmentProvinceNo;
        item.tmsShipmentCity = _value.tmsShipmentCity;
        item.tmsShipmentCityNo = _value.tmsShipmentCityNo;
        item.tmsShipmentRegion = _value.tmsShipmentRegion;
        item.tmsShipmentRegionNo = _value.tmsShipmentRegionNo;
        item.tmsShipmentStreetNo = _value.tmsShipmentStreetNo;
        item.tmsShipmentStreet = _value.tmsShipmentStreet;
        item.tmsShipmentAddress = _value.tmsShipmentAddress;
        item.tmsUnloadingConsignor = _value.tmsUnloadingConsignor;
        item.tmsUnloadingContacts = _value.tmsUnloadingContacts;
        item.tmsUnloadingProvince = _value.tmsUnloadingProvince;
        item.tmsUnloadingProvinceNo = _value.tmsUnloadingProvinceNo;
        item.tmsUnloadingCity = _value.tmsUnloadingCity;
        item.tmsUnloadingCityNo = _value.tmsUnloadingCityNo;
        item.tmsUnloadingRegion = _value.tmsUnloadingRegion;
        item.tmsUnloadingRegionNo = _value.tmsUnloadingRegionNo;
        item.tmsUnloadingStreetNo = _value.tmsUnloadingStreetNo;
        item.tmsUnloadingStreet = _value.tmsUnloadingStreet;
        item.tmsUnloadingAddress = _value.tmsUnloadingAddress;
      }
    }
  }
  //获取价格
  getPriceInfo(data: any, callback?: Function) {
    let params: any = {};
    if (!data.out_storeHouseId || !data.entry_storeHouseId || data.subItem.length == 0) {
      return
    }
    params.startStoreHouseId = data.out_storeHouseId;
    params.endStoreHouseId = data.entry_storeHouseId;
    params.materialInfos = []
    if (data.subItem) {
      for (const i of data.subItem) {
        params.materialInfos.push({
          skuId: i.omsOrderItemId,
          qty: i.tmsQuantity,
        })
      }
    }
    this.load = true;
    getShortBargePrice(params).then((res: any) => {
      // if(this.currentPrice && this.currentPrice[data.omsOrderIds]){
      //   delete this.currentPrice[data.omsOrderIds]
      // }

      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.priceObj[data.omsOrderIds] = res.data[0].data;
      this.currentPrice[data.omsOrderIds] = current;
      this.$forceUpdate();
      if (callback) {
        callback(data)
      }
    }).catch((err: any) => {
      this.load = false;
    })
  }
  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-top {
    padding-bottom: 16px;
    display: flex;
    justify-content: center;
  }
}

.deli-footer {
  height: 80px;
  width: 100%;
  box-shadow: 0 -5px 10px #EEE;
  padding: 0 16px 8px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  position: absolute;
  background-color: #FFF;
  left: 0;
  bottom: 0;
  z-index: 10;

  .d-left {
    width: 50%;

    .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;
    margin-left: 16px;
    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;
  }

  .stopBtn {
    opacity: 0.7;
  }

  .btn-box {
    width: 50%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}

.space {
  height: 80px;
  width: 100%;
  margin-top: 16px;
}
</style>