<template>
  <view class="warehouse-out-wrap">
    <view style="height: 100px; background: #2f4dae"></view>
    <view class="detail-wrap">
      <view class="order-info">
        <view class="title">{{$t('订单信息')}}</view>
        <view class="card-style"></view>
        <uni-card>
          <view class="card-content-wrap">
            <view>
              <view>{{$t('发件人')}}</view>
              <view>{{ detail.consignorVO && detail.consignorVO.name }}</view>
            </view>
            <view>
              <view>{{$t('邮箱')}}</view>
              <view>{{ detail.consignorVO && detail.consignorVO.email }}</view>
            </view>
            <view>
              <view>{{$t('手机号')}}</view>
              <view>  <text style="margin-right: 5px;"> + {{ detail.consignorVO && detail.consignorVO.countryCode }}</text><text>{{ detail.consignorVO && detail.consignorVO.phone }}</text> </view>
            </view>
          </view>
        </uni-card>
        <view class="card-style"></view>
        <uni-card>
          <view class="card-content-wrap">
            <view>
              <view>{{$t('收件人')}}</view>
              <view>{{ detail.consigneeVO && detail.consigneeVO.name }}</view>
            </view>
            <view>
              <view>{{$t('邮箱')}}</view>
              <view>{{ detail.consigneeVO && detail.consigneeVO.email }}</view>
            </view>
            <view>
              <view>{{$t('手机号')}}</view>
              <view> <text style="margin-right: 5px;" > +{{ detail.consigneeVO && detail.consigneeVO.countryCode}}</text> <text>{{ detail.consigneeVO && detail.consigneeVO.phone }}</text></view>
            </view>
          </view>
        </uni-card>
        <view class="card-style"></view>
        <uni-card>
          <view class="card-content-wrap">
            <view>
              <view>{{$t('唛头')}}</view>
              <view>{{ detail.marks }}</view>
            </view>
            <view>
              <view>{{$t('已到箱数')}}/{{$t('总箱数')}}</view>
              <view>{{ detail.sumNum }}/{{ detail.costVO ? detail.costVO.totalNum : 0 }}</view>
            </view>
            <view>
              <view>{{$t('订单状态')}}</view>
              <view><dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="detail.status" /></view>
            </view>
            <view>
              <view>{{$t('送货日期')}}</view>
              <view>{{ detail.deliveryDate }}</view>
            </view>
            <view>
              <view>{{$t('运输方式')}}</view>
              <view><dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="detail.transportId" /></view>
            </view>
            <view>
              <view>{{$t('始发仓')}}</view>
              <view>{{ detail.logisticsInfoDto && detail.logisticsInfoDto[isChinese ? 'startTitleZh' : 'startTitleEn'] }}</view>
            </view>
            <view>
              <view>{{$t('目的仓')}}</view>
              <view>{{ detail.logisticsInfoDto && detail.logisticsInfoDto[isChinese ? 'destTitleZh' : 'destTitleEn'] }}</view>
            </view>
          </view>
        </uni-card>
      </view>
      <view class="goods-info">
        <view class="title">{{$t('货物信息')}}</view>
        <template v-if="detail.orderItemVOList && detail.orderItemVOList.length > 0">
          <uni-card v-for="(item, index) in detail.orderItemVOList" :key="index">
            <view class="card-content-wrap">
              <view class="card-title">
                <view>{{$t('序号')}}</view>
                <view>{{  index + 1 }}</view>
              </view>
              <view>
                <view>{{$t('品名')}}</view>
                <view>{{ isChinese ? item.prodTitleZh : item.prodTitleEn }}</view>
              </view>
              <view>
                <view>{{$t('状态')}}</view>
                <view>
                  <dict-tag v-if="item.warehouseInInfoVO && item.warehouseInInfoVO.diffType" :type="DICT_TYPE.ORDER_WAREHOUSE_IN_STATUS" :value="item.warehouseInInfoVO.diffType" class="red" :class="{green: item.warehouseInInfoVO.diffType === 4}"/>
                  <span class="red" v-if="item.warehouseInInfoVO && item.warehouseInInfoVO.cartonsNumDiff"> {{ item.warehouseInInfoVO.cartonsNumDiff }} {{ $t('箱') }}</span>
                </view>
              </view>
              <view>
                <view>{{ $t('填单货物属性') }}</view>
                <view>{{ $t('品牌')}}:{{[$t('无牌'), $t('有牌'), $t('中性')][item.brandType]}}{{$t('箱数')}}:{{item.num}} {{$t('体积')}}:{{item.volume}}m³ {{$t('重量')}}:{{item.weight}}kg</view>
              </view>
              <view v-if="item.warehouseInInfoVO">
                <view>{{ $t('入库货物属性') }}</view>
                <view>{{
                   orderItemList.find(v => v.orderItemId === item.orderItemId)
                        && orderItemList.find(v => v.orderItemId === item.orderItemId).orderWarehouseInBackItemDoList[0]
                        && orderItemList.find(v => v.orderItemId === item.orderItemId).orderWarehouseInBackItemDoList[0].boxGauge
                        ? ($t('规格')+'('+orderItemList.find(v => v.orderItemId === item.orderItemId).orderWarehouseInBackItemDoList[0].boxGauge+')')
                        : ''}}
					{{$t('品牌')}}:{{[$t('无牌'), $t('有牌'), $t('中性')][item.brandType]}} {{$t('箱数')}}:{{item.warehouseInInfoVO.cartonsNum}}{{$t('体积')}}:{{item.warehouseInInfoVO.volume}}m³ {{$t('重量')}}:{{item.warehouseInInfoVO.weight}}kg
                  </view>
              </view>
              <view>
                <view>{{$t('最后操作时间')}}</view>
                <view>{{ dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss") }}</view>
              </view>
            </view>
          </uni-card>
        </template>
        <uni-card>
          <view class="card-content-wrap">
            <view class="card-title">{{$t('小计')}}</view>
            <view>
              <view>{{$t('下单统计')}}</view>
              <view>{{ statistics.orderSum }}{{$t('箱')}} {{ statistics.orderV }}m³ {{ statistics.orderW }}Kg {{$t('数量')}}: {{ statistics.orderQ }}{{$t('个')}}</view>
            </view>
            <view>
              <view>{{$t('入仓统计')}}</view>
              <view>{{ statistics.leviteSum }}{{$t('箱')}} {{ statistics.leviteV.toFixed(2) }}m³ {{ statistics.leviteW }}Kg {{$t('数量')}}: {{ statistics.leviteQ }}{{$t('个')}}</view>
            </view>
          </view>
        </uni-card>
        <uni-card>
          <view class="card-content-form-wrap">
            <view>
              <view>{{$t('集运仓库')}}</view>
              <view>{{ warehouseDetails.warehouseOutName || '' }}</view>
            </view>
            <view>
              <view>{{$t('货架')}}</view>
              <view style="display: block;">
                <view v-for="(val,i) in storageSpaceList" :key="i">
                  {{ val.warehouseName ? val.warehouseName : '' }} {{val.warehouseName ? val.regionName :''}}{{$t('区')}}
                </view>
              </view>
            </view>
            <view>
              <view>{{$t('调拨目标仓')}}</view>
              <view>{{ warehouseDetails.warehouseInName || '' }}</view>
            </view>
          </view>
        </uni-card>
      </view>
      <view class="form-wrap">
        <view>
          <text>{{$t('物流公司')}}</text>
          <!-- <uni-easyinput v-model="params.logisticsCompany" placeholder=""></uni-easyinput> -->
          <uni-data-select v-model="params.logisticsCompany" :localdata="expressList"></uni-data-select>
        </view>
        <view>
          <text>{{$t('联系电话')}}</text>
          <uni-easyinput v-model="params.phone" placeholder=""></uni-easyinput>
        </view>
        <view>
          <text>{{$t('物流单号')}}</text>
          <uni-easyinput v-model="params.logisticsNo" placeholder=""></uni-easyinput>
        </view>
        <view>
          <text>{{$t('出仓日期')}}</text>
          <uni-datetime-picker type="date" :clear-icon="false" v-model="params.deliveryDate" />
        </view>
        <view>
          <text>{{$t('出仓影像')}}</text>
          <view class="img-wrap">
            <uni-grid :column="4" :highlight="true" :show-border="false">
              <uni-grid-item v-for="(item, index) in imageList" :index="index" :key="index">
                <view class="grid-item-box" style="height: 100%;position: relative;">
					<image :src="iconpath" style="position: absolute;top:4px;right:4px;height:24px;width:24px;z-index:9" @tap="delimage(index)" mode="widthFix"></image>
                  <image v-if="item.type === 'image'" :src="item.url" mode="scaleToFill" style="height: 100%" @tap="previewImage(item.url)" />
                  <video v-else-if="item.type === 'video'" :id="`video_${index}`" style="width: 100%;height: 100%" :src="item.url" @play="playVideo(index)" @tap="playVideo(index)" @fullscreenchange="fullscreenchange"></video>
                </view>
              </uni-grid-item>
              <uni-grid-item>
                <view class="grid-item-box" style="height: 100%">
                  <view class="grid-item-box-add" @tap="chooseVideoImage">
                    <uni-icons type="plusempty" size="30" color="#eae8eb"></uni-icons>
                    <!-- <text>添加视频或图片</text> -->
                  </view>
                </view>
              </uni-grid-item>
            </uni-grid>
          </view>
        </view>
        <view>
          <text>{{$t('备注')}}</text>
          <uni-easyinput type="textarea" autoHeight v-model="params.deliveryRemark" placeholder=""></uni-easyinput>
        </view>
      </view>
    </view>
    <view class="foot-btn">
      <button class="mini-btn" type="primary" size="mini" @tap="submit">{{$t('确认出仓')}}</button>
      <button class="mini-btn" type="default" size="mini" @tap="cancel">{{$t('返回')}}</button>
    </view>
  </view>
</template>

<script>

import { getOrderInfo, getOrderWarehouseIn,adjustLastWithStatus } from '../warehousing/api'
import { orderWarehouseInGetAdjustInfo, listByOrderId, getByWarehouseId, warehouseAdjustSendOut, orderWarehousePicturePage, getSupplierPage } from './api'
import { updateImg } from '@/api/system'
import * as types from '@/store/mutations-types.js'
import iconpath from '../../static/images/close.png'

export default {
  data() {
    return {
      orderId: '',
      detail: {},
      orderItemList: [],
      statistics: {},
      warehouseDetails: {},
      storageSpaceList: [],
      expressList:[],
      imageList: [],
      params: {},
	  iconpath:iconpath,
	  adjust:{}
    }
  },
  onLoad(option) {
	  uni.setNavigationBarTitle({
	  	title:this.$t('调仓确认出仓')
	  })
    if ('orderId' in option) {
      this.orderId = option.orderId
      getOrderInfo(this.orderId).then(data => {
        this.detail = data
        this.getStatistics()
      })
	  adjustLastWithStatus(this.orderId,0).then(data => this.adjust = data||[])
      getSupplierPage({ pageNo: 1, pageSize: 10000}).then(data => {
        this.expressList = data.list.map(v => ({ value: v.id, text: v[this.isChinese ? 'companyZh' : 'companyEn'] }));
      })
      getOrderWarehouseIn(this.orderId).then(data => this.orderItemList = data ? data.reverse() : [])
      orderWarehouseInGetAdjustInfo({ orderId: this.orderId, lang: 0 }).then(data => {
        this.warehouseDetails = data[0] || {}
        listByOrderId({orderId:this.orderId}).then(res => {
          getByWarehouseId().then(r =>{
            let obj = [];
            res.forEach(item => {
              r.forEach(itemm => {
                if(item.wareId === itemm.id){
                  itemm.children.forEach(itemmm => {
                  if(itemmm.id === item.areaId){
                    obj.push({
                      warehouseName:itemm.name,
                      regionName:itemmm.name
                    })
                  }
                  })
                }
              })
            })
            this.storageSpaceList = obj;
          })
        })
        this.params.phone = this.warehouseDetails.phone || '';
        this.params.logisticsNo = this.warehouseDetails.logisticsNo;
        this.params.id = this.warehouseDetails.id;
        this.params.deliveryDate = this.warehouseDetails.deliveryDate
        this.params.logisticsCompany = this.warehouseDetails.logisticsCompany ? parseInt(this.warehouseDetails.logisticsCompany) :undefined;
        // orderWarehousePicturePage({rows:100,bizId:this.params.id,type: 2 })
      })
    }
  },
  methods: {
    cancel() {
      uni.navigateBack()
    },
	delimage(index){
		this.imageList.splice(index,1)
	},
    submit(){
      this.params.deliveryDate = this.dayjs(this.params.deliveryDate || new Date()).format("YYYY-MM-DD HH:mm:ss")
      if (this.imageList.length > 0) this.params.urls = this.imageList.map(v => v.url)
	  this.params.id = this.adjust?this.adjust.orderWarehouseAdjustBackVO.id:0
      warehouseAdjustSendOut(this.params).then(
        r => {
          this.$store.dispatch(types.SHOW_TOAST, { msg: this.$t('调拨出仓成功') });
          setTimeout(() => {
            uni.navigateBack()
          }, 500)
        }
      )
    },
    getStatistics(){
      let orderSum = 0
      let orderV = 0
      let orderW = 0
      let leviteSum = 0
      let leviteV = 0
      let leviteW = 0
      let orderQ = 0
      let leviteQ = 0
      this.detail?.orderItemVOList?.forEach((column, index) => {
          orderSum += column.num
          orderV += column.volume
          orderW += column.weight
          orderQ += column.quantity
          leviteSum += column.warehouseInInfoVO?column.warehouseInInfoVO.cartonsNum:0
          leviteV += column.warehouseInInfoVO?column.warehouseInInfoVO.volume:0
          leviteW += column.warehouseInInfoVO?column.warehouseInInfoVO.weight:0
          leviteQ += column.warehouseInInfoVO?column.warehouseInInfoVO.quantityAll:0
      });
      this.statistics = { orderSum, orderV, orderW, leviteSum, leviteV, leviteW, orderQ, leviteQ };
    },
    chooseVideoImage() {
      uni.showActionSheet({
        title: this.$t('选择上传类型'),
        itemList: [this.$t('图片'), this.$t('视频')],
        success: res => {
          console.log(res);
          if (res.tapIndex == 0) {
            this.chooseImages();
          } else {
            this.chooseVideo();
          }
        }
      });
    },
	delimage(index){
		this.imageList.splice(index,1)
	},
    chooseImages() {
      uni.chooseImage({
        count: 9, //默认是9张
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: res => {
          console.log(res.tempFiles, 'ddddsss')
          res.tempFilePaths.forEach((item, index) => {
            updateImg(item).then(data => {
				this.imageList.push({ type: 'image', url: data.data })
            })
          })
        }
      })
    },
    //上传视频
    chooseVideo(index) {
      uni.chooseVideo({
        maxDuration: 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
        count: 9,
        // camera: this.cameraList[this.cameraIndex].value, //'front'、'back'，默认'back'
        // sourceType: sourceType[this.sourceTypeIndex],
        success: res => {
          let videoFile = res.tempFilePath;
          console.log(res, 'ddddsss')
          // res.tempFilePaths.forEach((item, index) => {
          updateImg(videoFile).then(data => {
				this.imageList.push({ type: 'video', url: data.data })
          })
          // })
        },
        fail:(error)=>{
          uni.hideLoading();
          uni.showToast({
            title: error,
            icon: 'none'
          })
        }
      })
    },
    previewImage(url) {
      //uniapp预览轮播图
      uni.previewImage({
        current: 0, //预览图片的下标
        urls: [url] //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
      })
    },
    playVideo(index) {
      setTimeout(() => {
        this.videoContext = uni.createVideoContext(`video_${index}`)
        // this.videoContext.play()
        // this.videoContext.requestFullScreen()
      }, 500)
    },
    fullscreenchange(event) {
      if (!event.detail.fullScreen) {
        // this.videoContext.pause()
      }
    },
  },
  computed: {
    isChinese(){
      return uni.getLocale() === 'zh-Hans'
    }
  }
}
</script>

<style lang="scss" scoped>
.warehouse-out-wrap {
  .detail-wrap {
    margin: -75px 0 0;
    background: #fff;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    padding: 10px;
    > .order-info {
      .title {
        font-size: 18px;
        font-weight: bold;
      }
      .card-style {
        height: 16px;
        background: #1f4bbe;
        border: 4px solid #3b70ff;
        border-radius: 20px;
        margin-top: 16px;
      }
      .card-content-wrap {
        > view {
          display: flex;
          padding: 10px 0;
          > view + view {
            margin-left: auto;

          }
        }
        > view + view {
          border-top: 0.5px solid #eee;
        }
      }
      ::v-deep .uni-card {
        margin: -8px 4px 0 !important;
      }
    }
    .goods-info {
      margin-top: 20px;
      .title {
        font-size: 18px;
        font-weight: bold;
      }
      ::v-deep .uni-card {
        margin: 16px 4px 0 !important;
      }
      .card-content-wrap {
        .card-title {
          font-size: 16px;
          font-weight: 500;
        }
        > view {
          display: flex;
          > view {
            display: flex;
            // min-width: 50%;
          }
          > view:nth-of-type(1) {
            white-space: nowrap;
          }
          > view:nth-of-type(2) {
            word-break: break-all;
          }
          > view + view {
            margin-left: 8px;
          }
        }
        > view + view {
          margin-top: 4px;
        }
      }
      .card-content-form-wrap {
        > view {
          display: flex;
          align-items: center;
          padding: 10px 0;
          > view + view {
            margin-left: auto;

          }
        }
        > view + view {
          border-top: 0.5px solid #eee;
        }
      }
    }
    .form-wrap {
      margin-top: 10px;
      padding: 8px;
      > view {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        > text {
          width: 60px;
          margin-right: 8px;
        }
      }
      .img-wrap {
        flex: 1;
        width: calc(100% - 68px);
        ::v-deep .uni-grid-item {
          background: #fbf8fb;
        }
        .grid-item-box-add {
          height: 100%;
          display: flex;
          flex-flow: column;
          font-size: 10px;
          padding: 16px 0;
          text-align: center;
          justify-content: center;
        }
      }
    }
    // .img-and-video-wrap {
    //   margin-top: 20px;
    //   .title {
    //     font-size: 18px;
    //     font-weight: bold;
    //   }
    //   .img-wrap {
    //     margin-top: 20px;
    //     ::v-deep .uni-grid-item {
    //       background: #fbf8fb;
    //     }
    //     .grid-item-box-add {
    //       height: 100%;
    //       display: flex;
    //       flex-flow: column;
    //       font-size: 10px;
    //       padding: 16px 0;
    //       text-align: center;
    //       justify-content: center;
    //     }
    //   }
    //   .delivery-remark {
    //     display: flex;
    //     margin-top: 20px;
    //     > text {
    //       width: 40px;
    //       margin-right: 8px;
    //     }
    //     > view {
    //       flex: 1;
    //     }
    //   }
    // }
  }
}
</style>
