<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 class="list-header">

        <view class="checkbox-wrap">
          <text style="font-weight: normal">{{$t('全选')}}</text>
          <uni-data-checkbox v-model="checkboxAll" multiple :localdata="[{ value: 'all' }]" @change="selectAll"></uni-data-checkbox>
		  <view class="title" @tap="batchOut">{{$t('批量出仓')}}</view>
        </view>
      </view>
      <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;" @tap="toDetail(v)">
					<image src="../../static/images/xiegui-12.png"></image>
					<view  >{{$t('订单号')}} {{ v.orderNo }}</view>
				</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('唛头')}}: {{ v.marks }}</view>
                <view>{{$t('收件人电话')}}: {{ (v.consignorCountryCode||'')+v.consigneePhone }}</view>
              </view>
              <view>
                <view>{{$t('当前仓')}}: {{ v.startWarehouseName }}</view>
                <view>{{$t('目标仓')}}: {{ v.dstWarehouseName }}</view>
              </view>
              <view>
                <view>{{$t('运输方式')}}: <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="v.transportId" /></view>
                <view>{{$t('出货渠道')}}: {{ v.channelName }}</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('订单列表')}}</view>
            <view>{{$t('唛头')}}</view>
          </view>
          <view v-for="(item, index) in selectItemList" :key="index">
            <view>{{ item.orderNo }}</view>
            <view>{{ item.marks }}</view>
          </view>
        </view>
        <view class="form-wrap">
          <view>
            <text>{{$t('物流公司')}}</text>
			 <uni-combox :candidates="expressList" placeholder="" v-model="params.logisticsCompany"></uni-combox>
            <!-- <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><span style="color: #dd524d;">*</span>{{$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 class="popup-foot-btn">
          <button class="mini-btn" type="primary" size="mini" @tap="confirmOut">{{$t('确认出仓')}}</button>
          <button class="mini-btn" type="default" size="mini" @tap="cancel">{{$t('取消')}}</button>
        </view>
      </view>
    </uni-popup>
	</view>
</template>

<script>
  import { getAdjustWaitOutList, warehouseAdjustSendOutBatch, 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 {
		name: 'warehouseing-list',
		data() {
			return {
				iconpath:iconpath,
				checkboxAll: '',
				selectItemList: [],
						listData: [],
						page: 1,
						keyword: '',
						// oldKeyword: '',
						status: 'more',
						contentText: {
							contentdown: this.$t('上拉加载更多'),
							contentrefresh: this.$t('加载中'),
							contentnomore: this.$t('没有更多')
						},
						onHideFlag:false,
				imageList: [],
				expressList: [],
				params: {}
					};
		},
		methods: {
      closePopup({ show }) {
        !show && (this.selectItemList = [])
      },
      cancel() {
        this.$refs.popup.close()
      },
      confirmOut() {
        this.params.orderIdList = this.selectItemList.map(v => v.orderId)
		if(!this.params.deliveryDate){
			return uni.showToast({
				title:this.$t('请选择出仓日期'),
				icon:'error'
			})
		}
        this.params.deliveryDate = this.dayjs(this.params.deliveryDate).format("YYYY-MM-DD HH:mm:ss")
        if (this.imageList.length > 0) this.params.urls = this.imageList.map(v => v.url)
        warehouseAdjustSendOutBatch(this.params).then(data => {
          this.$store.dispatch(types.SHOW_TOAST, { msg: this.$t('批量调拨出仓成功') });
          this.$refs.popup.close()
		  this.selectItemList = []
          this.page = 1;
		  this.getData();
          this.checkboxAll = ''
        })
      },
      batchOut() {
        this.selectItemList = this.listData.filter(v => v.checkboxValue && v.checkboxValue.length > 0)
        if (this.selectItemList.length === 0) {
          this.$store.dispatch(types.SHOW_TOAST, {msg: this.$t('请选择需要出仓的订单')})
          return
        }
        this.$refs.popup.open('center')
      },
      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 })
              })
            })
          }
        })
      },
      //上传视频
      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 })
            })
            // })
          },
          fail:(error)=>{
            uni.hideLoading();
            uni.showToast({
              title: error,
              icon: 'none'
            })
          }
        })
      },
	  delimage(index){
	  	this.imageList.splice(index,1)
	  },
      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(orderNo) {
				let that = this
        const params = {
          page: this.page,
          rows: 20,
          orderNo
        }
				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();
				});
			},
			toDetail(data) {
        console.log(data);
				// this.modalId = data.id;
				// this.modalData = data;
        uni.navigateTo({
					url: './detail?orderId=' + data.orderId
				});
			},
		},
		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;
          }
        }
		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;
        margin-bottom: 8px;
        > text {
          width: 68px;
          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;
        }
      }
    }
    .popup-foot-btn {
      padding: 8px;
      margin-top: 8px;
      text-align: center;
      button {
        border: 1px solid #007aff;
      }
      > button + button {
        margin-left: 16px;
        color: #007aff;
        background: #fff;
      }
    }
  }
</style>
