<template>
  <el-drawer v-loading="load" :title="data.length <= 1 ? '订单发货' : '订单发货（批量逐一发货）'" :visible.sync="drawer" @close="close"
    :direction="direction" size="50%">
    <div class="content">
      <div class="err" v-if="failOrder.length > 0 && data.length > 1">
        <span>发货失败订单:</span>
        <span class="error-page" v-for="item of failOrder" @click="exchangeTag(item)" :key="item">【{{ item + 1
          }}】</span>
      </div>
      <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 @editState="editState" @editResult="editResult" @emptyInventory="emptyInventory" 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="nextBtn" :class="{ 'stopBtn': stopHandle }" v-if="data.length > 1">{{ currentOrder
          + 1
          == data.length ? '确认' : '确认，下一单' }}</div>
        <div class="send-btn" @click="btn" :class="{ 'stopBtn': stopHandle }">一键发货</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 { queryPricePackage, addmultiple, getInventoryByStoreHouseIdAndSkuids } from '@/api/delivery'
import api from '@/api/currency'
import Format from '@/benyun/utils/dateFormat'

@Component({ components: { DeliveryGoodsInfo, DeliveryPrice } })
export default class BatchbyOneModal extends Vue {
  //是否库存不足
  isEmptyInventory: Boolean = false;
  drawer = false;
  direction = 'rtl'
  checked = false;
  data: Array<any> = [];
  currentOrder = 0; //当前显示订单
  isSuccess = false; //是否有成功订单
  stopHandle = false; //是否停止操作
  failOrder: Array<any> = []; //
  load = false;
  priceObj: any = {};
  currentPrice: any = {};
  warehouseData: Array<any> = [];
  setShow(v: boolean) {
    this.drawer = v;
    this.priceObj = {};
    this.currentPrice = {};
    this.isSuccess = false;
    this.stopHandle = false;
    this.currentOrder = 0;
    this.checked = false;
    this.failOrder = [];
  }
  close() {
    if (this.isSuccess) {
      this.$emit('handleSuccess');
    }
  }
  exchangeTag(v: number) {
    this.currentOrder = v;
    this.setInfo()
  }
  editResult(v: any) {
    if (this.currentOrder >= this.data.length) {
      this.data[this.currentOrder - 1] = v;
    } else {
      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() {
    if (this.data[this.currentOrder]) {
      (this.$refs.info as any).setValue(this.data[this.currentOrder]);
    }
  }
  setValue(data: Array<any>) {
    this.data = [];
    if (data && data.length > 0) {
      for (const item of data) {
        const requestId = new Date().getTime() + this.getUuid()
        let obj: any = {
          tmsTransportMethod: '零担',
          tmsBusinessMan: (this as any).$store.getters.userInfo.nickName,
          tmsBusinessPhone: (this as any).$store.getters.userInfo.phonenumber,
          requestId: requestId,
          omsOrderIds: item.id,
          weight: item.weight,
          tmsUnloadingProvince: item.receiverProvince,
          tmsUnloadingProvinceNo: item.receiverProvinceCode,
          tmsUnloadingCity: item.receiverCity,
          tmsUnloadingCityNo: item.receiverCityCode,
          tmsUnloadingRegion: item.receiverDistrict,
          tmsUnloadingRegionNo: item.receiverDistrictCode,
          tmsUnloadingStreet: item.receiverTown,
          tmsUnloadingStreetNo: item.receiverTownCode,
          tmsUnloadingAddress: item.receiverAddress,
          tmsUnloadingConsignor: item.receiverName,
          tmsUnloadingContacts: item.receiverMobile,
          wmsSendType: 'B2BCK',
          tmsArrivalDate: this.getTime(3600 * 1000 * 24 * 2),
          tmsDeliveryDate: this.getTime(3600 * 1000 * (24 * 2 + 2)),
        };

        obj.subItem = [];
        if (item.items && item.items.length > 0) {
          for (const i of item.items) {
            let total: any = 0;
            if (Number(i.qty) && Number(i.price) && i.isGift !== 1) {
              total = multiply(Number(i.qty), Number(i.price))
            }

            obj.subItem.push({
              isGift: i.isGift,
              barCode: i.barCode,
              requestId: requestId,
              omsOrderId: item.id,
              omsOrderItemId: i.itemId,
              // omsOrderItemSkuId:i.itemId,
              tmsGoodsModel: i.styleId,
              tmsGoodsCode: i.skuId,
              tmsQuantity: i.qty,
              remainAmount: 0,
              tmsGoodsTotalPrice: total,
              name: i.name,
              price: i.isGift === 1 ? 0 : i.price,
              weight: i.weight
            })
          }
        }
        this.data.push(obj)
      }
    } else {
      this.data = []
    }
    this.loadWarehouse()
    // this.$nextTick(()=>{
    //   (this.$refs.info as any).setValue(this.data[this.currentOrder]);
    //   this.drawer = false;
    //   (this.$refs.info as any).showModal = true;
    // })
  }
  loadWarehouse() {
    api.pageList({
      pageNo: 1,
      pageSize: 1000
    }, 'maindataStorehouse').then((res: any) => {
      this.warehouseData = res.data.records;
      if (this.warehouseData.length > 0) {
        for (const item of this.data) {
          item.tmsShipmentConsignor = this.warehouseData[0].shipper;
          item.tmsShipmentContacts = this.warehouseData[0].shipperPhone;
          item.tmsShipmentProvince = this.warehouseData[0].province;
          item.tmsShipmentProvinceNo = this.warehouseData[0].provinceCode;
          item.tmsShipmentCity = this.warehouseData[0].city;
          item.tmsShipmentCityNo = this.warehouseData[0].cityCode;
          item.tmsShipmentRegion = this.warehouseData[0].region;
          item.tmsShipmentRegionNo = this.warehouseData[0].regionCode;
          item.tmsShipmentStreetNo = this.warehouseData[0].streetCode;
          item.tmsShipmentStreet = this.warehouseData[0].street;
          item.tmsShipmentAddress = this.warehouseData[0].address;
          item.storeHouseId = this.warehouseData[0].id;
          item.storeHouseName = this.warehouseData[0].name;
        }
        (this.$refs.info as any).setValue(this.data[this.currentOrder]);
      }
    }).catch(() => { })
  }
  getTime(n: number) {
    const start = new Date();
    start.setTime(start.getTime() + n);
    const t = Format(new Date(start), 'yyyy-MM-dd HH:mm:ss');
    return t
  }
  getUuid() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  btn() {
    if (this.isEmptyInventory) {
      this.$message('订单商品暂无库存')
    }
    this.noSentOrder(true);
    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].tmsUnloadingAddress || !this.data[this.currentOrder].tmsUnloadingConsignor) {
      this.$message("订单信息不完善，请前往编辑！");
      return
    }
    // if(!this.currentPrice[this.data[this.currentOrder].omsOrderIds]){
    //   this.$message("请选择价格！");
    //   return
    // }
    if (this.data.length > 1) {
      let ids = '';
      for (const item of this.data) {
        if (!item.tmsShipmentConsignor || !item.tmsUnloadingAddress || !item.tmsUnloadingConsignor) {
          ids = ids ? ids + ',' + item.omsOrderIds : String(item.omsOrderIds)
        }
      }
      if (ids) {
        this.$confirm('订单' + ids + '未编辑，是否以第一条订单为基准', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.setOnEditOrderInfo(ids);
          this.sendGoods(this.data[this.currentOrder]);

        }).catch(() => { });
      } else {
        this.sendGoods(this.data[this.currentOrder]);
      }
    } else {
      if (this.data[0].isSuccess) {
        this.$message('订单：' + this.data[0].omsOrderIds + '已执行过发货操作！');
        return
      }
      this.sendGoods(this.data[0]);
    }
  }
  nextBtn() {
    if (this.currentOrder >= this.data.length) {
      this.$message('已经是最后一单！')
      return
    }
    if (this.isEmptyInventory) {
      this.$message('订单商品暂无库存')
    }
    // if(this.stopHandle){
    //   this.$message('库存不足！')
    //   return
    // }
    // if(!this.checked){
    //   this.$message('请阅读并同意运单协议！')
    //   return
    // }
    const _value = this.data[this.currentOrder];
    if (!_value.tmsBusinessMan || !_value.tmsBusinessPhone || !_value.tmsShipmentConsignor || !_value.tmsShipmentContacts || !_value.tmsUnloadingConsignor || !_value.tmsUnloadingContacts || !_value.tmsUnloadingProvince || !_value.tmsUnloadingAddress || !_value.storeHouseId) {
      this.$message("订单信息不完整，请编辑信息！");
      return
    }
    if (_value.tmsBusinessMan.length >= 10) {
      this.$message("业务员名称不能超过10个字符！");
      return
    }
    // if(!this.currentPrice[_value.omsOrderIds]){
    //   this.$message('请选择价格！')
    //   return
    // }
    if (_value.isSuccess) {
      this.$message('订单：' + _value.omsOrderIds + '已执行过发货操作！');
      return
    }
    this.sendGoods(_value, true);
  }
  //查库存
  getStoreCount(item: any, callback?: Function) {
    if (!item) {
      return
    }
    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
      }
      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.omsOrderIds = [item.omsOrderIds];
    // params.tmsMaterials=[];
    // if(item.subItem){
    //   for(const i of item.subItem){
    //     params.tmsMaterials.push({
    //       storeHouseId:item.storeHouseId,
    //       materialSkuId:i.omsOrderItemId
    //     })
    //   }
    // }
    delete params.subItem;
    this.load = true;
    const resHandle = (s: string, msg?: string) => {
      for (let it of this.data) {
        if (it.omsOrderIds == item.omsOrderIds) {
          it.state = s;
          if (msg) {
            it.msg = msg;
          } else {
            it.msg = '';
          }
          break;
        }
      }

      if (!isNext) {
        //寻找未发货的订单
        this.noSentOrder();
        //是否是最后一单
        if (this.currentOrder >= this.data.length) {
          if (this.failOrder.length == 0) {
            this.drawer = false;
          } else {
            (this.$refs.info as any).setValue(this.data[this.currentOrder - 1]);
          }

        } else {
          let _item: any = this.data[this.currentOrder];
          this.sendGoods(_item);
          // if(this.currentPrice[_item.omsOrderIds]){
          //   this.sendGoods(_item);
          // }
          // else{
          //   this.getPriceInfo(_item,this.sendGoods)
          //   // this.getStoreCount(_item,this.getPriceInfo);
          // }
        }
      } else {
        if (this.currentOrder < this.data.length - 1) {
          this.currentOrder++;
          this.setInfo();
        }
      }
      this.$forceUpdate();
    }
    //发货
    addmultiple(params).then((res: any) => {
      this.load = false;
      if (res.code == 200) {
        this.isSuccess = true;
        this.$message({
          message: '订单:' + item.omsOrderIds + '发货成功！',
          type: 'success'
        })
        let fLen = this.failOrder.indexOf(this.currentOrder);
        if (fLen >= 0) {
          this.failOrder.splice(fLen, 1);
        }
        resHandle('success')
      }
    }).catch((err: any) => {
      this.load = false;
      if (this.failOrder.indexOf(this.currentOrder) == -1) {
        this.failOrder.push(this.currentOrder);
      }
      resHandle('fail', err);
    })
  }
  //寻找未发货订单
  noSentOrder(isCkick?: boolean) {
    this.currentOrder = this.data.length;
    for (let i = 0; i < this.data.length; i++) {
      if (!this.data[i].state) {
        this.currentOrder = i;
        break
      }
    }
    if (isCkick && this.currentOrder == this.data.length && this.failOrder.length > 0) {
      this.currentOrder = this.failOrder[0];
    }
    // 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 = {};
    params.startStoreHouseId = data.storeHouseId;
    // params.startAddressCode = data.tmsShipmentCityNo + '00000';
    params.endAddressCode = data.tmsUnloadingCityNo + '00000';
    params.omsIds = [this.data[0].omsOrderIds];
    params.planType = data.tmsTransportMethod;
    this.load = true;
    queryPricePackage(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.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
  }
  emptyInventory(v: boolean) {
    console.info("无库存提示....")
    this.isEmptyInventory = v;
  }


}
</script>
<style lang="scss" scoped>
.content {
  width: 100%;
  box-sizing: border-box;
  padding: 0 16px;
  background-color: #FFF;

  .err {
    font-size: 14px;
    color: #F00;
    padding-bottom: 8px;
  }

  .error-page {
    cursor: pointer;
  }

  .order-top {
    padding-bottom: 16px;
    display: flex;
    justify-content: center;

    .item-page {
      height: 28px;
      width: 28px;
      background-color: #F3F3F3;
      color: #666;
      font-size: 14px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 5px;
      margin: 0 4px;
      cursor: pointer;
      font-weight: 700;
    }
  }
}

.deli-footer {
  height: 60px;
  width: 100%;
  box-shadow: 0 -5px 10px #EEE;
  padding: 0 16px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  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: 60px;
  width: 100%;
  margin-top: 16px;
}
</style>