<template>
  <view style="background: #fff; min-height: calc(100vh - 44px)">
    <view class="search-header">
      <scanlistener
        v-if="showScanlistener"
        suffixIcon="scan"
        v-model="keyword"
        :placeholder="$t('请扫描订单号')"
        @iconClick="scanCode"
        @confirm="searchOrder"
        @submit="keyword=$event;searchOrder()"
      ></scanlistener>
    </view>
    <view class="scroll">
      <view>
        <uni-card v-for="(v, key) in listData" :key="key">
          <view class="content-item-wrap">
            <view class="item-header" >
              <view style="width: 90%;display: flex;align-items: center;" @tap="toDetail(v)">
                <image src="../../static/images/no.png" mode=""></image>
                <text>{{ v.selfNo }}</text>
              </view>
              <!-- <uni-data-checkbox v-model="v.checkboxValue" multiple :localdata="[{ value: v.orderId}]"></uni-data-checkbox> -->
            </view>
            <view class="item-content" @tap="toDetail(v)">
              <view>
                <view>{{$t('方数')}}({{$t('计划')}}/{{$t('已出')}}): {{v.volume||0}}/{{v.loadVolume||0}}</view>
                <view>{{$t('到仓时间')}}: {{ dayjs(v.rucangTime).format("YYYY-MM-DD")  }}</view>
              </view>
              <view>
                <view>{{$t('重量')}}({{$t('计划')}}/{{$t('已出')}}): {{v.weight||0}}/{{v.loadWeight||0}}</view>
                <view>{{$t('目的地')}}: {{ v.titleEn }}</view>
              </view>
              <view>
                <view>{{$t('数量')}}({{$t('计划')}}/{{$t('已出')}}):{{v.planNum||0}}/{{v.realNum||0}}</view>
                <view>{{$t('运输方式')}}: <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="v.transportType" /></view>
              </view>
              <view>
                <view>{{$t('状态')}}:{{v.shipmentStatusText}}</view>
                <view>
                  <button class="mini-btn" type="primary" size="mini" @tap="toDetail(v)">{{v.checkoutStatus==221?$t('出仓'):$t('查看出仓')}}</button>
                </view>

              </view>
            </view>
          </view>
        </uni-card>
        <uni-load-more :status="status" :icon-size="16" :content-text="contentText" />
      </view>
    </view>
    <uni-popup ref="popup" background-color="#fff" @change="closePopup">
      <view class="popup-content">
        <view class="popup-title">{{$t('空运出仓')}}</view>
        <view class="content-wrap">
          <view class="content-header">
            <view>{{$t('自编号')}}:{{selectItem.containerNumber}}</view>
          </view>
        </view>
        <view class="form-wrap">
          <view>
            <text>{{$t('出货方式')}}</text>
            <view>{{selectItem.deliverType==1?$t('送货上门'):$t('自提')}}</view>
          </view>
          <view>
            <text>{{selectItem.deliverType==1?$t('送货时间'):$t('自提时间')}}</text>
            <view>{{$util.formatDate(selectItem.deliverTime,1)||'/'}}</view>
          </view>
          <view>
            <text>{{selectItem.deliverType==1?$t('送货地址'):$t('自提地址')}}</text>
            <view>{{selectItem.deliverAddress||'/'}}</view>
          </view>
          <view>
            <text>{{$t('车牌')}}</text>
            <view>{{selectItem.licensePlate||'/'}}</view>
          </view>
          <view>
            <text>{{$t('司机')}}</text>
            <view>{{selectItem.driver||'/'}}</view>
          </view>
          <view>
            <text>{{$t('司机联系方式')}}</text>
            <view>{{selectItem.driverPhone||'/'}}</view>
          </view>
          <view>
            <text><span style="color: #dd524d;">*</span>{{$t('出仓日期')}}</text>
            <view v-if="selectItem.checkoutStatus==221" style="position: relative" >
              <!--uni-datetime-picker 组件必须点击图标才会弹出，所以覆盖一个button，点击后手动弹出-->
              <uni-datetime-picker ref="date" type="datetime" :clear-icon="false" v-model="params.checkoutTime" />
              <button v-if="$refs.date" @click="$refs.date.show" style="position:absolute; width: 100%; height: 100%; top: 0; left: 0; opacity: 0" />
            </view>

            <text v-else>{{params.checkoutTime?$util.formatDate(params.checkoutTime,1):'/'}}</text>
          </view>
           <view>
            <text>{{$t('计划箱数')}}</text>
            <view>{{params.planNum}}</view>
          </view>
          <view>
            <text>{{$t('出仓箱数')}}</text>
              {{params.realNum}}
            </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 v-if="selectItem.checkoutStatus==221">
                  <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 v-if="selectItem.checkoutStatus==221" type="textarea" autoHeight v-model="params.remark" placeholder=""></uni-easyinput>
            <text v-else>{{params.remark}}</text>
          </view>
        </view>
        <view v-if="selectItem.checkoutStatus==221" class="popup-foot-btn">
          <button class="mini-btn" type="primary" size="mini" @tap="confirmOut">{{$t('确认出仓')}}</button>
          <button class="mini-btn cl" type="default" size="mini" @tap="cancel">{{$t('取消')}}</button>
          <button class="mini-btn st" type="warn" size="mini" @tap="startout">{{$t('开始出仓')}}</button>
        </view>
        <view class="popup-foot-btn" v-else>
          <button class="mini-btn" type="default" size="mini" @tap="cancel">{{$t('返回')}}</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getAdjustWaitOutList, warehouseAdjustSendOutBatch, getSupplierPage,getAirShipmentByShipmentId,boxAirCheckoutGet,warehouseCreate,getAirCheckoutByShipmentId } from './api'
import { updateImg } from '@/api/system'
import util from "@/util/util.js";
import * as types from '@/store/mutations-types.js'
import iconpath from '../../static/images/close.png'

export default {
  name: 'warehouseing-list',
  data() {
    return {
      iconpath:iconpath,
      checkboxAll: '',
      selectItem: {},
      listData: [],
      page: 1,
      keyword: '',
      // oldKeyword: '',
      status: 'more',
      contentText: {
        contentdown: this.$t('上拉加载更多'),
        contentrefresh: this.$t('加载中'),
        contentnomore: this.$t('没有更多')
      },
      onHideFlag:false,
      imageList: [],
      expressList: [],
      params: {},
      warehouseStatus:['默认值','待出','可出','备货中','已备货'],
    };
  },
  methods: {
    closePopup({ show }) {
      !show && (this.selectItem = {})
      !show && (this.params = {})
    },
    cancel() {
      this.$refs.popup.close()
    },
    confirmOut() {
      // this.params.orderIdList = this.selectItem.map(v => v.orderId)
      if(!this.params.checkoutTime){
        return uni.showToast({
          title:this.$t('请选择出仓日期'),
          icon:'error'
        })
      }
	  if(this.params.planNum!=this.params.realNum){
		  return uni.showToast({
		    title:this.$t('出仓件数与计划出仓件数不一致，请检查'),
		    icon:'error'
		  })
	  }
	  this.params.realNum = parseInt(this.params.realNum)
      this.params.checkoutTime = this.dayjs(this.params.checkoutTime).format("YYYY-MM-DD HH:mm:ss")
      if (this.imageList.length > 0) this.params.checkoutFiles = this.imageList.map(v => v.url).join(',')
      this.params.shipmentId = this.selectItem.shipmentId
      if(this.params.id){
        this.params.operateType = 2
        warehouseAdjustSendOutBatch(this.params).then(data => {
          this.$store.dispatch(types.SHOW_TOAST, { msg: this.$t('出仓成功') });
          this.$refs.popup.close()
          this.selectItem = {}
          this.page = 1;
          this.getData();
          this.checkboxAll = ''
        })
      }else{
        this.params.operateType = 2
        warehouseCreate(this.params).then(data => {
          this.$store.dispatch(types.SHOW_TOAST, { msg: this.$t('出仓成功') });
          this.$refs.popup.close()
          this.selectItem = {}
          this.page = 1;
          this.getData();
          this.checkboxAll = ''
        })
      }

    },
    selectAll(value) {
      console.log(value.detail.value);
      if (value.detail.value.length > 0) {
        this.listData = this.listData.map(v => {
          return { ...v, checkboxValue: [v.orderId] }
        })
      } else {
        this.listData = this.listData.map(v => {
          return { ...v, checkboxValue: [] }
        })
      }
    },
    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();
          }
        }
      });
    },
    chooseImages() {
      uni.chooseImage({
        count: 9, //默认是9张
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: res => {
          console.log(res, 'ddddsss')
          // let imgFile = res.tempFilePaths;
          res.tempFilePaths.forEach((item, index) => {
            updateImg(item).then(data => {
              console.log(data, '--------res--------');
              // const type = res.tempFiles[index].type.split('/')[0]
              this.imageList.push({ type:'image', url: data.data })
              this.saveImage()
            })
          })
        }
      })
    },
    //上传视频
    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 => {
            console.log(data, '--------res--------');
            // const type = res.tempFile.type.split('/')[0]
            this.imageList.push({ type:'video', url: data.data })
          })
          // })
          this.saveImage()
        },
        fail:(error)=>{
          uni.hideLoading();
          uni.showToast({
            title: error,
            icon: 'none'
          })
        }
      })
    },
    delimage(index){
      this.imageList.splice(index,1)
      this.saveImage()
    },
    saveImage() {
      this.params.shipmentId = this.selectItem.shipmentId
      this.params.operateType = 1
      if (this.imageList.length > 0){
        this.params.checkoutFiles = this.imageList.map(v => v.url).join(',')
      }else{
        this.params.checkoutFiles = ''
      }
      if(this.params.id){
        warehouseAdjustSendOutBatch(this.params)
      }else{
        warehouseCreate(this.params)
      }
    },
    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()
      }
    },
    scanCode() {
      uni.scanCode({
        success: (res) => {
          console.log('条码类型：' + res.scanType);
          console.log('条码内容：' + res.result);
          this.keyword = res.result
          this.searchOrder()
        }
      })
    },
    searchOrder() {
      this.page = 1
      setTimeout(() => {
        this.getData(this.keyword)
      }, 100)
    },
    getData(selfNo) {
      let that = this
	  let params = {}
	  if(selfNo){
        params = {
			page: this.page,
			rows: 20,
			selfNo:selfNo,
		}
      }else{
		  params = {
			  page: this.page,
			  rows: 20
		  }
	  }
      getAdjustWaitOutList(params).then(res => {
        const data = res.list
        if (that.page == 1) this.listData = [];
        if (data.length > 0) {
          that.listData = that.listData.concat(data);
          that.status = 'more';
        }
        if (res.total === that.listData.length) that.status = 'noMore';
        uni.stopPullDownRefresh();
      });
    },
    async toDetail(data) {
      this.imageList = []
      await getAirShipmentByShipmentId({shipmentId:data.id}).then(res=>{
        this.selectItem = res
        this.selectItem.containerNumber = data.selfNo
        this.selectItem.checkoutStatus = data.checkoutStatus
      })
      getAirCheckoutByShipmentId({shipmentId:data.id}).then(re=>{
        if(re){
          this.params = re
          if(this.params.checkoutFiles && this.params.checkoutFiles.length>0&&this.params.checkoutFiles.split(',')){
            var img = this.params.checkoutFiles.split(',')
            this.imageList = []
            img.forEach(item=>{
              if(['jpg','jpeg','png'].indexOf(item.split('.')[item.split('.').length-1])>-1){
                this.imageList.push({type:'image',url:item})
              }else{
                this.imageList.push({type:'video',url:item})
              }
            })
          }
          if(!this.params.checkoutTime) this.params.checkoutTime = util.formatDate(new Date().getTime(), true);
        }

      })
      this.$refs.popup.open('center')
    },
    startout(){
      uni.navigateTo({
        url: "./airStartcheckOut?id=" + this.selectItem.shipmentId,
      });
    }
  },
  onPullDownRefresh() {
    this.page = 1;
    this.getData();
  },
  onReachBottom() {
    if (this.status == 'more') {
      this.status = 'loading';
      this.page++;
      this.getData();
    }
  },
  onLoad: function(option) {
    uni.setNavigationBarTitle({
      title:this.$t('空运待出仓列表')
    })
    this.getData();
    getSupplierPage({ pageNo: 1, pageSize: 10000}).then(data => {
      this.expressList = data.list.map(v => v.companyZh);
    })
  },
  onShow(){
    if(this.onHideFlag){
      this.checkboxAll = ''
      this.page = 1;
      this.getData(this.keyword);
    }
  },
  onHide(){
    this.onHideFlag = true;
  },
  onBackPress(options) {
    uni.reLaunch({
      url: '../index/index'
    });
    return true;
  }
};
</script>

<style lang="scss" scoped>
.search-header{
  ::v-deep .uni-easyinput__content {
    border-radius: 20px;
    padding-right: 10px;
    background: rgba($color: #fff, $alpha: 0.5) !important;
    border: none;
    // opacity: 0.5;
  }
  ::v-deep .uni-input-placeholder {
    padding-left: 8px;
    color: #b2c9f3;
  }
  ::v-deep .uni-input-input {
    padding-left: 8px;
  }
}
.scroll {
  margin-top: -8px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  padding: 8px;
  background: #fff;
  .list-header {
    display: flex;
    .title {
      margin-left: 10upx;
      background-color: #007aff;
      color: #fff;
      font-size: 26upx;
      padding: 10upx 16upx;
      border-radius: 12upx;
    }
    .checkbox-wrap {
      margin-left: auto;
      display: flex;
      align-items: center;
      > text {
        margin-right: 8px;
      }
      ::v-deep .checklist-box {
        margin: 0;
      }
    }
  }
  ::v-deep .uni-card {
    margin: 12px 0 0 !important;
    padding: 0 !important;
  }
  .content-item-wrap {
    .item-header {
      display: flex;
      align-items: center;
      border-bottom: 0.5px solid #eee;
      padding-bottom: 10px;
      font-size: 16px;
      ::v-deep .uni-data-checklist {
        margin-left: auto !important;
        flex: none;
        .checklist-box {
          margin: 0;
        }
      }
      text{
        color:#333;
        font-size: 14px;
      }
      .no-icon{
        width: 24px;
        height: 24px;
        border-radius: 12px;
        background-color: #518BDA;
        font-size: 12px;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        margin-right: 6px;
      }
      image{
        width:20px;
        height:20px;
        margin-right: 8px;
      }
    }
    .item-content {
      padding-top: 10px;
      > view {
        display: flex;
        padding: 4px 0;
        > view {
          flex: 1;
          word-break: break-all;
        }
      }
    }
  }
}
::v-deep .uni-popup__wrappe {
  border-radius: 8px;
}
.popup-content {
  width: 90vw;
  max-height: 80vh;
  padding: 20px;
  overflow-y: auto;
  .popup-title {
    font-size: 18px;
    font-weight: bold;
    text-align: center;
  }
  .content-wrap {
    margin-top: 10px;
    .content-header {
      font-weight: bold;
    }
    > view {
      display: flex;
      padding: 4px 0;
      > view {
        flex: 1;
      }
    }
  }
  .form-wrap {
    margin-top: 10px;
    > view {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      > text {
        width: 88px;
        margin-right: 4px;
      }
    }
    .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;
      }
    }
  }
  .popup-foot-btn {
    padding: 8px;
    margin-top: 8px;
    text-align: center;
    button {
      border: 1px solid #007aff;
    }
    > button + button {
      margin-left: 16px;
    }
    .cl {
      background-color: #fbf8fb;
      color: #007aff;
    }
   .st {
    border: 1px solid red;
   }
  }

}
</style>
