<template>
  <div style="padding: 0 20px">
    <h1>{{type == 1 ? $t('调拨出仓') :$t('调拨到仓')}}</h1>
    <el-divider content-position="left">
      {{$t('订单信息')}}
    </el-divider>
    <ordeDetailsForm :details="orderDetails"></ordeDetailsForm>
    <el-divider content-position="left">
      {{$t('货物信息')}}
    </el-divider>
    <el-table :show-summary="true" :summary-method="totalFn" :data="orderItemVOList">
      <el-table-column width="80" type="index" :label="$t('序号')"></el-table-column>
      <el-table-column :label="$t('品名')">
        <template v-slot="{row}">
          <div>{{ row.prodTitleZh }}</div>
          <div>{{ row.prodTitleEn }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('填单货物属性')">
        <template v-slot="{row}">
          <div>{{$t('品牌')}}：
            <span v-if="row.brandType === 0">{{$t('无')}}</span>
            <span v-if="row.brandType === 1">{{$t('有')}}</span>
            <span v-if="row.brandType === 2">{{$t('中性')}}</span>
          </div>
          <div>{{$t('箱数')}}：{{row.num}}</div>
          <div>{{$t('体积')}}：{{ row.volume }}m³</div>
          <div>{{$t('重量')}}：{{row.weight}}Kg</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('入库货物属性')">
        <template v-slot="{row}">
          <div v-for="(item,index) in row.orderWarehouseInBackItemDoList" :key="index">
            <div>{{$t('规格')}}：{{item.boxGauge.split('*').map(item =>`${item}cm`).join('*')}}</div>
            <div>
              <div>{{$t('品牌')}}：{{(brandList.find(item => item.id == row.brand) || {}).titleZh}}
                <span v-if="!row.brand">
            {{$t('无')}}
          </span></div>
              <div>{{$t('箱数')}}：{{item.cartonsNum}}</div>
              <div>{{$t('体积')}}：{{item.volume}} CMB</div>
              <div>{{$t('重量')}}：{{item.weight}}KG</div>
            </div>
          </div>
          <p v-if="row.orderWarehouseInBackItemDoList.length === 0">
            {{$t('暂无货物入库信息')}}
          </p>
        </template>
      </el-table-column>
      <el-table-column :label="$t('最后操作时间')">
           <template v-slot="{row}">
             {{parseTime(row.updateTime)}}
           </template>
      </el-table-column>
      <el-table-column :label="$t('状态')">
        <template v-slot="{row}">
          {{calculationStatus(row)}}
        </template>
      </el-table-column>
    </el-table>
    <el-divider content-position="left" v-if="type == 2">
      {{$t('调仓明细')}}
    </el-divider>
    <el-table :data="warehouseList" v-if="type == 2">
      <el-table-column :label="$t('调仓编号')" type="index" ></el-table-column>
      <el-table-column :label="$t('调出仓库')" prop="warehouseOutName" ></el-table-column>
      <el-table-column :label="$t('调入仓库')" prop="warehouseInName"></el-table-column>
      <el-table-column :label="$t('申请人')" prop="creatorName"></el-table-column>
      <el-table-column :label="$t('申请时间')">
        <template v-slot="{row}">
         {{parseTime(row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('状态')">
        <template v-slot="{row}">
            {{STATUS[row.status]}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('出仓影像')">
        <template v-slot="{row}">
          <warehouse-video-list :status="2" :item ="row"></warehouse-video-list>
        </template>
      </el-table-column>
      <el-table-column :label="$t('到仓影像')">
        <template v-slot="{row}">
          <warehouse-video-list :status="3" :item ="row"></warehouse-video-list>
        </template>
      </el-table-column>
      <el-table-column :label="$t('调拨出仓备注')" prop="deliveryRemark">
      </el-table-column>
      <el-table-column :label="$t('调拨到仓备注')" prop="arrivalRemark">
      </el-table-column>
    </el-table>
    <el-descriptions style="margin-top: 20px" :column="4" border>
      <el-descriptions-item :label="$t('集运仓库')">{{ warehouseDetails && warehouseDetails.warehouseOutName  ?  warehouseDetails.warehouseOutName : '' }}</el-descriptions-item>
      <el-descriptions-item :label="$t('储位')">
        {{ ($refs.area ? $refs.area.selected : []).join(',') }}
      </el-descriptions-item>
      <el-descriptions-item v-if="type == 2" :label="$t('选择储位')">
        <div @click="areaVisible = true" style="color: #0a84ff;cursor: pointer;">{{$t('选择储位')}}</div>
      </el-descriptions-item>
      <el-descriptions-item :label="$t('调拨目标仓')">{{ warehouseDetails && warehouseDetails.warehouseInName ? warehouseDetails.warehouseInName : '' }}</el-descriptions-item>
      <el-descriptions-item :label="$t('物流公司')">
        <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="$t('物流单号')">
        <el-input :disabled="type == 2" v-model="params.logisticsNo"></el-input>
      </el-descriptions-item>
      <el-descriptions-item :label="$t('联系电话')">
        <el-input :disabled="type == 2" v-model="params.phone"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <span style="color: red;font-size: 20px;margin-right: 5px;">*</span>{{$t('出仓日期')}}
        </template>
        <el-date-picker
          :disabled="type == 2"
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="params.deliveryDate"
          type="datetime"
          :placeholder="$t('选择日期')">
        </el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item  v-if="type == 2">
        <template slot="label">
          <span style="color: red;font-size: 20px;margin-right: 5px;">*</span>{{$t('到仓日期')}}
        </template>
        <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="params.arrivalDate"
          type="datetime"
          :placeholder="$t('选择日期')">
        </el-date-picker>
      </el-descriptions-item>
    </el-descriptions>
    <el-divider content-position="left">
      {{$t('出仓影像')}}
    </el-divider>
    <image-and-video-upload   :fileSize="50" :isShowTip="true" v-model="params.urls" ></image-and-video-upload>
    <el-form>
      <el-form-item :label="$t('备注')">
        <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">{{$t('确认出仓')}}</el-button>
      <el-button v-else @click="submit2(true)" size="medium" >{{$t('确认到仓')}}</el-button>
      <el-button v-if="type == 2" @click="escapeBol = true;">{{$t('转异')}}</el-button>
      <el-button v-if="type == 1" size="medium" @click="cancellationOfOrder">{{$t('取消调仓')}}</el-button>
      <el-button size="medium" @click="$tab.closeOpenPage({path:'/order/order'})">{{$t('返回')}}</el-button>
    </div>
    <warehouse-location ref="area" :visible.sync="areaVisible" v-model="params.orderLocationCreateReqVOList" :warehouse-id="Number(this.type) === 1 ? warehouseDetails.warehouseOutId  : warehouseDetails.warehouseInId" :order-id="Number(orderId)"></warehouse-location>
    <el-dialog :title="$t('订单转异')" center :visible.sync="escapeBol">
      <el-form ref="form2" :model="params" label-position="top" label-width="200">
        <el-form-item prop="manualExceptionType"  :rules="{ required:true,message:'至少选择一个转异原因'}" :label="$t('原因类型')">
          <dict-selector v-model="params.manualExceptionType" form-type="checkbox" :type="DICT_TYPE.MANUAL_EXCEPTION_TYPE" multiple ></dict-selector>
        </el-form-item>
        <el-form-item  :label="$t('附件')">
          <image-upload v-model="params.exceptionUrls"></image-upload>
        </el-form-item>
        <el-form-item :label="$t('详细信息')">
          <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)">{{$t('确认并完成入仓')}}</el-button>
        <el-button @click="escapeBol = false">{{$t('取消')}}</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 "@/components/WarehouseAreaDialog";
import imageUpload from "@/components/ImageUpload";
import {getProductBrankPage} from "@/api/ecw/productBrank";
import {parseTime} from "@/utils/ruoyi";
import WarehouseVideoList from "@/views/ecw/order/components/warehouse-video-list.vue";
export default {
  name: "transferWarehousing",
  components: {
    WarehouseVideoList,
    ImageAndVideoUpload,
    Template,
    ordeDetailsForm,
    warehouseLocation,
    imageUpload
  },
  props: {
    orderId: [String, Number],
    type: [String],
  },
  data() {
    return {
      areaVisible:false,
      escapeBol:false,
      STATUS :{1:this.$t('申请中'), 2:this.$t('通过'), 3:this.$t('不通过'), 4:this.$t('已取消'), 5:this.$t('已出仓'),6:this.$t('已到仓')},
      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:[],
      brandList:[]

    }
  },
  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.phone,
        urls: this.params.urls,
      }
      },
    toWarehouseAbnormal(){
     let exceptionUrls =  this.params.exceptionUrls
      return {
        arrivalDate: this.params.arrivalDate,
        arrivalRemark: this.params.deliveryRemark,
        descZh: this.params.descZh,
        id: this.params.id,
        manualExceptionType:this.params.manualExceptionType.join(','),
        orderLocationCreateReqVOList: this.params.orderLocationCreateReqVOList,
        urls: this.params.urls,
        exceptionUrls:exceptionUrls.length ? exceptionUrls.split(',') :[],
      }
    },
    toWarehouse(){
      return {
        arrivalDate: this.params.arrivalDate,
        arrivalRemark: this.params.deliveryRemark,
        id: this.params.id,
        urls: this.params.urls,
        orderLocationCreateReqVOList: this.params.orderLocationCreateReqVOList,

      }
    },
    calculationStatus(){
      return (val)=>{
        let des = ''
       switch (val.diffType) {
         case 2 :
            des = `${this.$t('多了')}${val.cartonsNumDiff}${this.$t('箱')}`
           break
         case 3 :
           des = `${this.$t('少了')}${val.cartonsNumDiff}${this.$t('箱')}`
           break
         case 4 :
           des = this.$t('准确到齐')
           break
       }
       return des
      }
    }
  },
  created() {
    //获得品牌
    getProductBrankPage({pageNo:1,pageSize:10000,}).then(r => {
        this.brandList = r.data.list
    })
    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 && Number(this.type) === 1){
          this.params.orderLocationCreateReqVOList = res.data
        }
        // 等待仓库id和已选的储位后初始化储位信息
        this.$nextTick(() => {
          this.$refs.area.updateArea()
        })
      })
      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.logisticsCompany = this.warehouseDetails.logisticsCompany ? parseInt(this.warehouseDetails.logisticsCompany) :undefined;
      if(this.type == 2){
        this.params.deliveryDate = parseTime(this.warehouseDetails.deliveryDate)
      }
      // 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.$t('调拨出仓成功！'));
            this.$tab.closeOpenPage({path:'/order/order'})
          }
        }
      )
    },
    submit2(val){
      if(val){
        warehouseAdjustArrived(val ? this.toWarehouse : this.toWarehouseAbnormal).then(r => {
          if(r.code === 0){
            this.$message.success(this.$t('调拨到仓成功！'));
            this.$tab.closeOpenPage({path:'/order/order'})
          }
        })
      }else {
        this.$refs.form2.validate( validate => {
          if(validate){
            warehouseAdjustArrived(val ? this.toWarehouse : this.toWarehouseAbnormal).then(r => {
              if(r.code === 0){
                this.$message.success(this.$t('调拨到仓成功！'));
                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)
         if(i.orderWarehouseInBackItemDoList){
           i.orderWarehouseInBackItemDoList.forEach(m => {
             Wvolume += Number(m.volume || 0)
             Wnum += Number(m.cartonsNum || 0)
             Wweight += Number(m.weight || 0)
           })
         }
       })
      let text = `${this.$t('下单统计')}：${num}${this.$t('箱')} ${volume.toFixed(2)}m³ ${weight.toFixed(2)}Kg`
      let text2 =` ${this.$t('入仓统计')}：${Wnum}${this.$t('箱')} ${Wvolume.toFixed(2)}m³ ${Wweight.toFixed(2)}Kg`
      return [this.$t('合计：'),text,text2]
    },
    cancellationOfOrder(){
      this.$prompt(this.$t('请输入取消调仓原因'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
      }).then(({ value }) => {
        cancelAdjust({
          orderId: this.orderId,
          reason: value,
        }).then(r => {
          console.log(r,'r');
          if(r.code === 0){
            this.$message({
              type: 'info',
              message: this.$t('取消调仓成功')
            });
            this.$tab.closeOpenPage({path:'/order/order'})
          }
        })
      }).catch(() => {
      });
    },
  },
  watch:{
    'params.orderLocationCreateReqVOList'(vo, vn){
      console.log(vo, vn)
    }
  }
}
</script>

<style scoped>

</style>
