<template>
  <div style="padding: 0 20px">
    <h1>{{type == 1 ? '调拨出仓' :'调拨到仓'}}</h1>
    <el-divider content-position="left">
      订单信息
    </el-divider>
    <ordeDetailsForm :details="orderDetails"></ordeDetailsForm>
    <el-divider content-position="left">
      货物信息
    </el-divider>
    <el-table :show-summary="true" :summary-method="totalFn" :data="orderItemVOList">
      <el-table-column width="80" type="index" label="序号"></el-table-column>
      <el-table-column label="品名">
        <template v-slot="{row}">
          <div>{{ row.prodTitleZh }}</div>
          <div>{{ row.prodTitleEn }}</div>
        </template>
      </el-table-column>
      <el-table-column label="填单货物属性">
        <template v-slot="{row}">
        <div>品牌：{{ row.brand }}</div><div>箱数：{{row.num}}</div><div>体积：{{ row.volume }}m³</div><div>重量{{row.weight}}Kg</div>
        </template>
      </el-table-column>
      <el-table-column label="入库货物属性">
        <template v-slot="{row}">
          <div v-for="(item,index) in row.orderWarehouseInBackItemDoList" :key="index">
            <div>规格：{{item.boxGauge}}</div>
            <div style="display: flex;justify-content: space-between;">
              <div>品牌：{{row.brand}}</div>
              <div>箱数：{{item.cartonsNum}}</div>
              <div>体积：{{item.volume}} CMB</div>
              <div>重量：{{item.weight}}KG</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="最后操作时间">
           <template v-slot="{row}">
             {{parseTime(row.updateTime)}}
           </template>
      </el-table-column>
      <el-table-column label="状态">
        <template v-slot="{row}">
          {{calculationStatus(row.cartonsNumDiff)}}
        </template>
      </el-table-column>
    </el-table>
    <el-divider content-position="left" v-if="type == 2">
      调仓明细
    </el-divider>
    <el-table :data="warehouseList" v-if="type == 2">
      <el-table-column label="调仓编号" prop="id"></el-table-column>
      <el-table-column label="调出仓库" prop="warehouseOutName" ></el-table-column>
      <el-table-column label="调入仓库" prop="warehouseInName"></el-table-column>
      <el-table-column label="申请人" prop="creatorName"></el-table-column>
      <el-table-column label="申请时间">
        <template v-slot="{row}">
         {{parseTime(row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template v-slot="{row}">
            {{STATUS[row.status]}}
        </template>
      </el-table-column>
    </el-table>
    <el-descriptions style="margin-top: 20px" :column="4" border>
      <el-descriptions-item label="集运仓库">{{ warehouseDetails && warehouseDetails.warehouseOutName  ?  warehouseDetails.warehouseOutName : '' }}</el-descriptions-item>
      <el-descriptions-item label="储位">
         <div v-for="item in storageSpaceList"  style="display: flex;"><div>{{item.warehouseName ? item.warehouseName : ''}}</div><div>{{item.warehouseName ? item.regionName :''}} 区</div> <div>{{item.code}}</div></div>
      </el-descriptions-item>
      <el-descriptions-item v-if="type == 2" label="选择储位">
        <div @click="areaVisible = true" style="color: #0a84ff;cursor: pointer;">选择储位</div>
      </el-descriptions-item>
      <el-descriptions-item label="调拨目标仓">{{ warehouseDetails && warehouseDetails.warehouseInName ? warehouseDetails.warehouseInName : '' }}</el-descriptions-item>
      <el-descriptions-item label="物流公司">
        <el-select :disabled="type == 2" v-model="params.logisticsCompany" >
          <el-option v-for="(item,index) in expressList " :key="index"  :value="item.id" :label="item.companyZh"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="物流单号">
        <el-input :disabled="type == 2" v-model="params.logisticsNo"></el-input>
      </el-descriptions-item>
      <el-descriptions-item label="联系电话">
        <el-input :disabled="type == 2" v-model="params.phone"></el-input>
      </el-descriptions-item>
      <el-descriptions-item label="出仓日期" >
        <el-date-picker
          :disabled="type == 2"
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="params.deliveryDate"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item label="到仓日期" v-if="type == 2">
        <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="params.arrivalDate"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-descriptions-item>
    </el-descriptions>
    <el-divider content-position="left">
      出仓影像
    </el-divider>
    <image-and-video-upload   :fileSize="50" :isShowTip="true" v-model="params.urls" ></image-and-video-upload>
    <el-form>
      <el-form-item label="备注">
        <el-input v-model="params.deliveryRemark" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 30px; text-align: center;">
      <el-button v-if="type == 1" @click="submit" size="medium">确认出仓</el-button>
      <el-button v-else @click="submit2(true)" size="medium" >确认到仓</el-button>
      <el-button v-if="type == 2" @click="escapeBol = true;">转异</el-button>
      <el-button v-if="type == 1" size="medium" @click="cancellationOfOrder">取消调仓</el-button>
      <el-button size="medium" @click="$tab.closeOpenPage({path:'/order/order'})">返回</el-button>
    </div>
    <warehouse-location ref="area" :city-id="warehouseInShi"  :visible.sync="areaVisible" v-model="params.orderLocationCreateReqVOList" :warehouse-id="warehouseDetails.warehouseInId" :order-id="Number(orderId)"></warehouse-location>
    <el-dialog :title="'订单转异'" center :visible.sync="escapeBol">
      <el-form label-position="top" label-width="200">
        <el-form-item label="原因类型">
          <dict-selector v-model="params.manualExceptionType" form-type="checkbox" :type="DICT_TYPE.MANUAL_EXCEPTION_TYPE" multiple ></dict-selector>
        </el-form-item>
        <el-form-item required label="附件">
          <image-upload v-model="params.exceptionUrls"></image-upload>
        </el-form-item>
        <el-form-item label="详细信息">
          <el-input v-model="params.descZh" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button  type="primary" @click="submit2(false)">确认并完成入仓</el-button>
        <el-button @click="escapeBol = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ordeDetailsForm from "@/views/ecw/order/components/ordeDetailsForm";
import {
  cancelAdjust,
  getAdjustInfo,
  getOrder, getOrderWarehouseIn, listByOrderId,
  orderWarehouseInGetAdjustInfo,
  orderWarehousePicturePage, warehouseAdjustArrived,
  warehouseAdjustSendOut
} from "@/api/ecw/order";
import Template from "@/views/cms/template";
import {DICT_TYPE} from '@/utils/dict';
import ImageAndVideoUpload from "@/components/ImageAndVideoUpload/index";
import {getSupplierPage} from "@/api/ecw/supplier";
import {getByWarehouseId} from "@/api/ecw/warehouseArea";
import {adjustLastWithStatus, warehouseApprovalCancel} from "@/api/ecw/batchSingleApplication";
import warehouseLocation from "@/views/ecw/order/components/warehouseLocation";
import imageUpload from "@/components/ImageUpload";
let STATUS = {1:'申请中', 2:'通过', 3:'不通过', 4:'已取消', 5:'已出仓',6:'已到仓'}
export default {
  name: "transferWarehousing",
  components: {
    ImageAndVideoUpload,
    Template,
    ordeDetailsForm,
    warehouseLocation,
    imageUpload
  },
  props: {
    orderId: [String, Number],
    type: [String],
  },
  data() {
    return {
      areaVisible:false,
      escapeBol:false,
      STATUS,
      orderDetails: {},
      DICT_TYPE,
      warehouseDetails: {},
      warehouseList:[],
      params: {
        deliveryDate: "",
        deliveryRemark: "",
        id: undefined,
        logisticsCompany:undefined,
        logisticsNo: "",
        phone: "",
        urls: [],
        arrivalDate:'',
        orderLocationCreateReqVOList:[],
        manualExceptionType:0,
        descZh:'',
        exceptionUrls:[]
      },
      warehouseInShi:0,
      expressList:[],
      storageSpaceList:[],
      applyStatus:{},
      orderItemVOList:[]

    }
  },
  computed:{
    exWarehouse(){
      return {
        deliveryDate: this.params.deliveryDate,
        deliveryRemark: this.params.deliveryRemark,
        id: this.params.id,
        logisticsCompany: this.params.logisticsCompany,
        logisticsNo:this.params.logisticsNo,
        phone: this.params.logisticsNo,
        urls: this.params.urls,
      }
      },
    toWarehouseAbnormal(){
      return {
        arrivalDate: this.params.arrivalDate,
        arrivalRemark: this.params.arrivalRemark,
        descZh: this.params.descZh,
        id: this.params.id,
        manualExceptionType:this.params.manualExceptionType,
        orderLocationCreateReqVOList: this.params.orderLocationCreateReqVOList,
        urls: this.params.urls,
        exceptionUrls:this.params.exceptionUrls.split(','),

      }
    },
    toWarehouse(){
      return {
        arrivalDate: this.params.arrivalDate,
        arrivalRemark: this.params.arrivalRemark,
        id: this.params.id,
        urls: this.params.urls,

      }
    },
    calculationStatus(){
      return (val)=>{
        if(val > 0){
          return `多${val}箱`
        }else if(val < 0){
           return `少${Math.abs(val)}箱`
        }else {
          return '准确到齐 '
        }
      }
    }
  },
  created() {
    if(this.type == 1){
      adjustLastWithStatus({orderId:this.orderId,lang:0}).then(r =>{
        this.applyStatus = r.data})
    }
    getSupplierPage({ pageNo: 1, pageSize: 10000}).then(r => {
     this.expressList = r.data.list;
    })
    getOrder(this.orderId).then(r => {
      if (r.code === 0) {
        this.orderDetails = r.data;
      }
    })
    if(this.type == 2){
      getAdjustInfo({orderId:this.orderId,lang:0}).then(r => {
        this.warehouseList = r.data
      })
    }
    orderWarehouseInGetAdjustInfo({orderId: this.orderId, lang: 0}).then(r => {
      this.warehouseDetails = r.data[r.data.length - 1]
      listByOrderId({orderId:this.orderId}).then(res => {
        if(res.code === 0){
          getByWarehouseId().then(r =>{
            let obj = [];
            res.data.forEach(item => {
              r.data.forEach(itemm => {
                if(item.wareId === itemm.id){
                  itemm.children.forEach(itemmm => {
                   if(itemmm.id === item.areaId){
                     if(itemmm.positionList.length > 0){
                       itemmm.positionList.forEach(ic =>{
                         if(ic.children.length > 0){
                           ic.children.forEach(icc => {
                             if(icc.id === item.locationId){
                               obj.push({
                                 warehouseName:itemm.name,
                                 regionName:itemmm.name,
                                 code:icc.code
                               })
                             }
                           })
                         }
                       })
                     }
                   }
                  })
                }
              })
            })
            console.log(obj)
            this.storageSpaceList = obj;
          })
        }
      })
      this.warehouseInShi = this.warehouseDetails.warehouseInShi || ''
      this.params.phone = this.warehouseDetails.phone || '';
      this.params.logisticsNo = this.warehouseDetails.logisticsNo;
      this.params.id = this.warehouseDetails.id;
      this.params.deliveryDate = new Date(this.warehouseDetails.deliveryDate);
      this.params.logisticsCompany = this.warehouseDetails.logisticsCompany ? parseInt(this.warehouseDetails.logisticsCompany) :undefined;
      orderWarehousePicturePage({rows:100,bizId:this.params.id,type:this.type == 1 ? 2 : 3 }).then(r => {
        if(r.code === 0){
          this.params.urls = r.data.list.map(e => e.url);
        }
      })
    })
    getOrderWarehouseIn(this.orderId).then(r => {
      if(r.code === 0){
        this.orderItemVOList = r.data;
      }
    })
  },
  methods:{
    submit(){
      warehouseAdjustSendOut(this.exWarehouse).then(
        r => {
          if(r.code === 0){
            this.$message.success('调拨出仓成功');
            this.$tab.closeOpenPage({path:'/order/order'})
          }
        }
      )
    },
    submit2(val){
      warehouseAdjustArrived(val ? this.toWarehouse : this.toWarehouseAbnormal).then(r => {
          if(r.code === 0){
            this.$message.success('调到仓成功');
            this.$tab.closeOpenPage({path:'/order/order'})
          }
      })
    },
    totalFn({ columns, data }){
      //  体积，数量，重量 W:入仓
      let volume = 0,num = 0,weight = 0;
      let Wvolume = 0 ,Wnum = 0,Wweight = 0;
       data.forEach(i => {
         volume += Number(i.volume)
         num += Number(i.num)
         weight += Number(i.weight)
        i.orderWarehouseInBackItemDoList.forEach(m => {
          Wvolume += Number(m.volume || 0)
          Wnum += Number(m.cartonsNum || 0)
          Wweight += Number(m.weight || 0)
        })
       })
      let text = `下单统计：${num}箱 ${volume}m³ ${weight}Kg`
      let text2 =` 入仓统计：${Wnum}箱 ${Wvolume}m³ ${Wweight}Kg`
      return ['合计：',text,text2]
    },
    cancellationOfOrder(){
      this.$prompt('请输入取消调仓原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        cancelAdjust({
          orderId: this.orderId,
          reason: value,
        }).then(r => {
          console.log(r,'r');
          if(r.code === 0){
            this.$message({
              type: 'info',
              message: '取消调仓成功'
            });
            this.$tab.closeOpenPage({path:'/order/order'})
          }
        })
      }).catch(() => {
      });
    },
  },
  watch:{
    'params.orderLocationCreateReqVOList'(val){
      console.log(val,'123')
      getByWarehouseId().then(r =>{
        console.log(r,'仓库')
        let obj = [];
        val.forEach(item => {
          r.data.forEach(itemm => {
            if(item.wareId === itemm.id){
              itemm.children.forEach(itemmm => {
                if(itemmm.id === item.areaId){
                  if(itemmm.positionList.length > 0){
                    itemmm.positionList.forEach(ic =>{
                    if(ic.children.length > 0){
                      ic.children.forEach(icc => {
                        if(icc.id === item.locationId){
                          obj.push({
                            warehouseName:itemm.name,
                            regionName:itemmm.name,
                            code:icc.code
                          })
                        }
                      })
                    }
                    })
                  }
                }
              })
            }
          })
        })
        console.log(obj,'obj')
        this.storageSpaceList = obj;
      })
    }
  }
}
</script>

<style scoped>

</style>
