<template>
  <div class="info">
    <div class="edit" v-if="!readOnly">
      <span @click="edit">发货设置</span>
    </div>
    <div class="g-box">
      <div class="info-row" v-if="!hideOrderCode">
        <div class="info-col">
          <span class="label">单号：</span>
          <span :title="value.omsOrderIds">{{ value.omsOrderIds }}</span>
        </div>
      </div>
      <!-- <div class="info-row">
        <div class="info-col col-width">
          <span class="label">订单类型：</span>
          <span :title="value.orderType">{{ value.orderType }}</span>
        </div>
      </div> -->
      <div class="info-row">
        <div class="info-col col-width">
          <span class="label">业务员：</span>
          <span :title="value.tmsBusinessMan">{{ value.tmsBusinessMan }}</span>
        </div>
        <div class="info-col col-width">
          <span class="label">业务员手机：</span>
          <span :title="value.tmsBusinessPhone">{{ value.tmsBusinessPhone }}</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-col">
          <span class="label">发货仓库：</span>
          <span :title="value.storeHouseName">{{ value.storeHouseName }}</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-col col-width" v-if="!sendState">
          <span class="label">发货状态：</span>
          <span v-if="value.state == 'success'">发货中</span>
          <span v-if="value.state == 'fail'" style="color: #F00;">发货失败</span>
        </div>
        <div class="info-col col-width">
          <span class="label">运输方式：</span>
          <span :title="value.tmsTransportMethod">{{ value.tmsTransportMethod }}</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-col">
          <span class="label">备注：</span>
          <span :title="value.tmsRemark">{{ value.tmsRemark }}</span>
        </div>
      </div>
      <div class="info-row" v-if="value.msg">
        <div class="info-col">
          <span class="label">信息：</span>
          <span :title="value.msg" style="color: #F00;">{{ value.msg }}</span>
        </div>
      </div>
    </div>
    <div class="g-box">
      <div class="info-row">
        <!-- <div class="info-col col-width">
          <span class="label">发货省：</span>
          <span :title="value.tmsShipmentProvince">{{ value.tmsShipmentProvince }}</span>
        </div> -->
        <div class="info-col col-width">
          <span class="label">收货省：</span>
          <span :title="value.tmsUnloadingProvince">{{ value.tmsUnloadingProvince }}</span>
        </div>
      </div>
      <div class="info-row">
        <!-- <div class="info-col col-width">
          <span class="label">发货市：</span>
          <span :title="value.tmsShipmentCity">{{ value.tmsShipmentCity }}</span>
        </div> -->
        <div class="info-col col-width">
          <span class="label">收货市：</span>
          <span :title="value.tmsUnloadingCity">{{ value.tmsUnloadingCity }}</span>
        </div>
      </div>
      <div class="info-row">
        <!-- <div class="info-col col-width">
          <span class="label">发货区（县）：</span>
          <span :title="value.tmsShipmentRegion">{{ value.tmsShipmentRegion }}</span>
        </div> -->
        <div class="info-col col-width">
          <span class="label">收货区（县）：</span>
          <span :title="value.tmsUnloadingRegion">{{ value.tmsUnloadingRegion }}</span>
        </div>
      </div>
      <div class="info-row">
        <!-- <div class="info-col col-width">
          <span class="label">发货街道：</span>
          <span :title="value.tmsShipmentStreet">{{ value.tmsShipmentStreet }}</span>
        </div> -->
        <div class="info-col col-width">
          <span class="label">收货街道：</span>
          <span :title="value.tmsUnloadingStreet">{{ value.tmsUnloadingStreet }}</span>
        </div>
      </div>
      <div class="info-row">
        <!-- <div class="info-col col-width">
          <span class="label">发货地址（详情）：</span>
          <span :title="value.tmsShipmentAddress">{{ value.tmsShipmentAddress }}</span>
        </div> -->
        <div class="info-col">
          <span class="label">收货地址（详情）：</span>
          <span :title="value.tmsUnloadingAddress">{{ value.tmsUnloadingAddress }}</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-col col-width">
          <span class="label">收货人：</span>
          <span :title="value.tmsUnloadingConsignor">{{ value.tmsUnloadingConsignor }}</span>
        </div>
        <div class="info-col col-width">
          <span class="label">发货人：</span>
          <span :title="value.tmsShipmentConsignor">{{ value.tmsShipmentConsignor }}</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-col col-width">
          <span class="label">收货人联系电话：</span>
          <span :title="value.tmsUnloadingContacts">{{ value.tmsUnloadingContacts }}</span>
        </div>
        <div class="info-col col-width">
          <span class="label">发货人联系电话：</span>
          <span :title="value.tmsShipmentContacts">{{ value.tmsShipmentContacts }}</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-col col-width">
          <span class="label">期望送达时间：</span>
          <span class="time">{{ value.tmsArrivalDate }}</span>
        </div>
        <div class="info-col col-width">
          <span class="label">期望提货时间：</span>
          <span class="time">{{ value.tmsDeliveryDate }}</span>
        </div>
      </div>
    </div>
    <div class="g-box">
      <div class="goods-top">
        <div class="g-label">物料信息</div>
        <div class="g-cont">
          <div class="g-total">
            <span class="name-label">重量合计(kg)：</span>
            <span class="total-num">{{ totalWeight }}</span>
          </div>
        </div>
      </div>
      <div class="table">
        <vxe-table border size="mini" align="center" header-cell-class-name="header-cell" :data="value.subItem">
          <vxe-column field="barCode" title="商品条码" width="130"></vxe-column>
          <vxe-column field="name" title="物料名称" width="260">
            <template #default="{ row }">
              {{ row.name }}
              <el-tag type="success" v-if="row.isGift == 1" size="mini">赠品</el-tag>
            </template>
          </vxe-column>
          <vxe-column field="weight" title="重量(g)"></vxe-column>
          <vxe-column field="price" title="单价"></vxe-column>
          <vxe-column field="tmsQuantity" title="数量"></vxe-column>
          <vxe-column field="remainAmount" title="库存"></vxe-column>
          <vxe-column field="tmsGoodsTotalPrice" title="小计"></vxe-column>
        </vxe-table>
      </div>
    </div>
    <vxe-modal v-model="showModal" id="deliverInfoEdit" width="900" height="80%" @show="show" @hide="hide" title="编辑"
      resize show-zoom transfer show-footer>
      <by-form :propConfig="config" v-if="showModal" ref="form" @formChange="formChange" />
      <template #footer>
        <div class="btn">
          <el-button plain size="small" @click="showModal = false">取消</el-button>
          <el-button type="primary" size="small" @click="btn">确定</el-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { add, multiply, subtract, divide } from '@/benyun/utils/accuracy'
import api from "@/api/currency";
@Component
export default class DeliveryGoodsInfo extends Vue {
  @Prop()
  hideOrderCode?: Boolean
  @Prop()
  sendState?: Boolean
  @Prop()
  readOnly?: Boolean

  data: Array<any> = [];
  value: any = {};
  //是否通报库存不足
  isEmitInventory: Boolean = false;
  showModal = false;
  totalWeight: any = 0;
  config: any = {
    attr: {
      size: 'small',
      labelWidth: '120px',
      rules: {
        // orderType:[{
        //   required: true, message: '请选择订单类型！', trigger: 'change'
        // }],
        tmsBusinessMan: [
          { required: true, message: '业务员不能为空！', trigger: 'blur' },
          { min: 0, max: 10, message: '业务员名字不能超过10个字符！', trigger: 'blur' }
        ],
        tmsBusinessPhone: [{
          required: true, message: '业务员手机不能为空！', trigger: 'blur'
        }, {
          validator: this.validatePhone, trigger: 'blur'
        }],
        tmsShipmentConsignor: [{
          required: true, message: '发货人不能为空！', trigger: 'blur'
        }],
        tmsShipmentContacts: [{
          required: true, message: '发货人电话不能为空！', trigger: 'blur'
        }, {
          validator: this.validatePhone, trigger: 'blur'
        }],
        // tmsShipmentProvince:[{
        //   required: true, message: '请选择发货地址！', trigger: 'change'
        // }],
        // tmsShipmentAddress:[{
        //   required: true, message: '发货地址不能为空！', trigger: 'blur'
        // }],
        tmsUnloadingConsignor: [{
          required: true, message: '收货人不能为空！', trigger: 'blur'
        }],
        tmsUnloadingContacts: [{
          required: true, message: '收货人电话不能为空！', trigger: 'blur'
        }, {
          validator: this.validatePhone, trigger: 'blur'
        }],
        tmsUnloadingProvince: [{
          required: true, message: '请选择收货地址！', trigger: 'change'
        }],
        tmsUnloadingAddress: [{
          required: true, message: '收货地址不能为空！', trigger: 'blur'
        }],
        storeHouseId: [{
          required: true, message: '请选择仓库！', trigger: 'change'
        }],
        tmsArrivalDate: [{
          required: true, message: '期望送达时间不能为空！', trigger: 'blur'
        }],
        tmsDeliveryDate: [{
          required: true, message: '期望提货时间不能为空！', trigger: 'blur'
        }],
        // tmsTransportMethod: [{
        //   required: true, message: '运输方式不能为空！', trigger: 'change'
        // }],
        wmsSendType: [{
          required: true, message: '出库方式不能为空！', trigger: 'change'
        }]
      }
    },
    columns: [
      // [
      //   {
      //   label:'订单类型',
      //   prop:'orderType',
      //   component:'by-select',
      //   compConfig:{
      //     attr:{
      //       data: [{
      //         label:'B2C',
      //         value:'B2C'
      //       },{
      //         label:'B2B',
      //         value:'B2B'
      //       }],
      //       clearable:true
      //     }
      //   }
      // }
      // ],
      [{
        label: '业务员',
        prop: 'tmsBusinessMan',
        component: 'by-input',
        compConfig: {
          attr: {
            clearable: true
          }
        }
      }, {
        label: '业务员手机',
        prop: 'tmsBusinessPhone',
        component: 'by-input',
        compConfig: {
          attr: {
            clearable: true
          }
        }
      }],
      [{
        label: '仓库',
        prop: 'storeHouseId',
        component: 'warehouse',
        compConfig: {
          attr: {
            placeholder: '请选择仓库',
            clearable: true,
            defaultIndex: 0,
            retConfig: {
              tmsShipmentConsignor: 'shipper',
              tmsShipmentContacts: 'shipperPhone',
              tmsShipmentProvince: 'province',
              tmsShipmentProvinceNo: 'provinceCode',
              tmsShipmentCity: 'city',
              tmsShipmentCityNo: 'cityCode',
              tmsShipmentRegion: 'region',
              tmsShipmentRegionNo: 'regionCode',
              tmsShipmentStreetNo: 'streetCode',
              tmsShipmentStreet: 'street',
              tmsShipmentAddress: 'address',
              storeHouseId: 'id',
              storeHouseName: 'name'
            }
          }
        }
      }, {
        span: 12,
        label: '出库方式',
        prop: 'wmsSendType',
        component: 'by-select',
        compConfig: {
          attr: {
            // clearable:true,
            data: [
              // {
              //   label:'越库出库',
              //   value:'YKCK'
              // },
              {
                label: 'B2B出库',
                value: 'B2BCK'
              },
              // {
              //   label:'B2C出库',
              //   value:'B2CCK'
              // }
            ]
          }
        }
      }
        // ,{
        //   label:'运输方式',
        //   prop:'tmsTransportMethod',
        //   component:'by-select',
        //   compConfig:{
        //     attr:{
        //       clearable:true,
        //       data: [{
        //         label:'整车',
        //         value:'整车'
        //       },{
        //         label:'零担',
        //         value:'零担'
        //       },{
        //         label:'短驳',
        //         value:'短驳'
        //       }]
        //     }
        //   }
        // }
      ],
      [{
        label: '发货人',
        prop: 'tmsShipmentConsignor',
        component: 'by-input',
        compConfig: {
          attr: {
            clearable: true
          }
        }
      }, {
        label: '发货人电话',
        prop: 'tmsShipmentContacts',
        component: 'by-input',
        compConfig: {
          attr: {
            clearable: true
          }
        }
      }],
      // [{
      //   labelWidth:'120px',
      //   label:'发货地址选择',
      //   prop:'tmsShipmentProvince',
      //   component:'by-area',
      //   compConfig:{
      //     attr:{
      //       province:'tmsShipmentProvince', //省
      //       provinceCode:'tmsShipmentProvinceNo', //省编码
      //       city:'tmsShipmentCity',   //市
      //       cityCode:'tmsShipmentCityNo',  //市编码
      //       county:'tmsShipmentRegion',  //县/区
      //       countyCode:'tmsShipmentRegionNo',   //县/区编码
      //       townCode:'tmsShipmentStreetNo',
      //       town:'tmsShipmentStreet',
      //       broadcastConfig:{
      //         name: 'warehouseChange',
      //         // dataHandle: (data:any) => {
      //         //   let v = (this as any).$lodash.cloneDeep(data)
      //         //   delete v.storeHouseId
      //         //   return v
      //         // }
      //       }
      //     }
      //   }
      // }],
      // [{
      //   label:'发货地址',
      //   prop:'tmsShipmentAddress',
      //   component:'by-input',
      //   compConfig:{
      //     attr:{
      //       clearable:true
      //     }
      //   }
      // }],
      [{
        label: '收货人',
        prop: 'tmsUnloadingConsignor',
        component: 'by-input',
        compConfig: {
          attr: {
            clearable: true
          }
        }
      }, {
        label: '收货人电话',
        prop: 'tmsUnloadingContacts',
        component: 'by-input',
        compConfig: {
          attr: {
            clearable: true
          }
        }
      }],
      [{
        labelWidth: '120px',
        label: '收货地址选择',
        prop: 'tmsUnloadingProvince',
        component: 'by-area',
        compConfig: {
          attr: {
            province: 'tmsUnloadingProvince', //省
            provinceCode: 'tmsUnloadingProvinceNo', //省编码
            city: 'tmsUnloadingCity',   //市
            cityCode: 'tmsUnloadingCityNo',  //市编码
            county: 'tmsUnloadingRegion',  //县/区
            countyCode: 'tmsUnloadingRegionNo',   //县/区编码
            townCode: 'tmsUnloadingStreetNo',
            town: 'tmsUnloadingStreet'
          }
        }
      }],
      [{
        label: '收货人地址',
        prop: 'tmsUnloadingAddress',
        component: 'by-input',
        compConfig: {
          attr: {
            clearable: true
          }
        }
      }],
      [{
        label: '期望送达时间',
        prop: 'tmsArrivalDate',
        component: 'byDatePicker',
        compConfig: {
          attr: {
            clearable: true,
            type: 'datetime'
          }
        }
      }, {
        label: '期望提货时间',
        prop: 'tmsDeliveryDate',
        component: 'byDatePicker',
        compConfig: {
          attr: {
            clearable: true,
            type: 'datetime'
          }
        }
      }],
      [{
        label: '备注',
        prop: 'tmsRemark',
        component: 'by-input',
        compConfig: {
          attr: {
            clearable: true
          }
        }
      }]
    ]
  }
  validatePhone(rule: any, value: any, callback: any) {
    if (value) {
      if (!/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)) {
        callback(new Error('手机号格式不正确！'));
      } else {
        callback();
      }

    } else {
      callback();
    }
  }

  //获得库存
  async getInventory() {

    let items: any = [];
    for (const item of this.value.subItem) {
      items.push(item.barCode)
    }
    if (this.value.subItem.length) {
      const res = await api.getJZJInventory({ wareHouseCode: '', items: items })
      this.$emit('emptyInventory', false);
      if (res.data.code != 200) {
        this.$emit('emptyInventory', true);
        return;
      }
      //将获得的库存设置到this.value.subItem的remainAmount中
      for (let i = 0; i < this.value.subItem.length; i++) {
        for (let j = 0; j < res.data.items.length; j++) {
          if (this.value.subItem[i].barCode == res.data.items[j].barCode) {
            this.value.subItem[i].remainAmount = res.data.items[j].remainAmount
          }
        }
        if (Number(this.value.subItem[0].remainAmount) <= 0) {
          //库存不足
          this.$emit('emptyInventory', true);
        }
      }

    }
  }


  setValue(v: any, isLoadInventory: boolean = true) {
    console.info('setValue', v)
    this.value = v ? v : {};
    this.value.wmsSendType = 'B2BCK'
    this.totalWeight = 0;
    if (v.weight) {
      this.totalWeight = divide(v.weight, 1000)?.toFixed(3)
    }
    if (isLoadInventory) {
      this.getInventory();
    }

    // this.totalWeight = divide(v.weight,1000);
    // if(this.value.subItem && this.value.subItem.length > 0){
    //   for(const item of this.value.subItem){
    //     if(Number(item.weight)){
    //       let totalWeight = multiply(Number(item.weight),Number(item.tmsQuantity))
    //       this.totalWeight = add(this.totalWeight,totalWeight);
    //     }
    //   }
    //   this.totalWeight = divide(this.totalWeight,1000);
    // }
  }
  hide() {
    this.$emit('editState', true)
  }
  show() {
    // this.value.tmsBusinessMan = (this as any).$store.getters.userInfo.userName;
    // this.value.tmsBusinessPhone = (this as any).$store.getters.userInfo.phonenumber;
    this.$nextTick(() => {
      if (this.$refs.form) {
        (this.$refs.form as any).clearValue();
        (this.$refs.form as any).setValue(this.value);
      }
    })
  }
  edit() {
    this.showModal = true;
    this.$emit('editState', false)
  }
  formChange(parames: any) {
    let data = (this.$refs.form as any).getValue();
    if (data['tmsArrivalDate'] && data['tmsDeliveryDate']) {
      if (data['tmsArrivalDate'] > data['tmsDeliveryDate']) {
        this.$message({
          message: '期望送达时间不能大于期望提货时间',
          type: 'warning'
        })
        if (parames.code == 'tmsArrivalDate') {
          data['tmsArrivalDate'] = ''
        }
        if (parames.code == 'tmsDeliveryDate') {
          data['tmsDeliveryDate'] = ''
        }
        // (this.$refs.form as any).clearValue();
        (this.$refs.form as any).setValue(data);
      }
    }
  }
  btn() {
    if (this.$refs.form) {
      (this.$refs.form as any).validate().then(() => {
        this.value = (this.$refs.form as any).getValue();
        if (!this.value.tmsShipmentCity) {
          this.$message({
            message: '请选择发货城市！',
            type: 'warning'
          })
          return
        }
        if (!this.value.tmsShipmentRegion) {
          this.$message({
            message: '请选择发货区/县！',
            type: 'warning'
          })
          return
        }
        if (!this.value.tmsUnloadingCity) {
          this.$message({
            message: '请选择收货城市！',
            type: 'warning'
          })
          return
        }
        if (!this.value.tmsUnloadingRegion) {
          this.$message({
            message: '请选择收货区/县！',
            type: 'warning'
          })
          return
        }
        this.showModal = false;
        this.$emit('editState', true);
        this.$emit('editResult', this.value);
      }).catch(() => { })
    }
  }
}
</script>
<style lang="scss" scoped>
.info {
  width: 100%;

  .edit {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-bottom: 8px;

    span {
      color: rgb(0, 119, 255);
      font-size: 14px;
      cursor: pointer;
    }
  }

  .g-box {
    width: 100%;
    background-color: rgba(160, 205, 255, 0.22);
    margin-bottom: 16px;
    padding: 16px;
    box-sizing: border-box;

    .info-row {
      width: 100%;
      display: flex;
      padding-bottom: 16px;

      .info-col {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        span {
          font-size: 14px;
        }

        .label {
          color: #666;
        }

        .time {
          color: #F00;
        }
      }

      .col-width {
        width: 50%;
      }
    }

    .info-row:last-child {
      padding: 0;
    }

    .goods-top {
      padding-bottom: 8px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .g-label {
        font-size: 14px;
      }

      .g-cont {
        width: 60%;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .g-total {
          padding-left: 8px;
          font-size: 12px;

          .name-label {
            color: #999;
          }
        }
      }
    }

    .table {
      width: 100%;
    }
  }

  .btn {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
<style lang="scss">
.header-cell {
  background-color: rgba(160, 205, 255, 0.48);
}
</style>