<template>
  <view style="background: #fff; min-height: calc(100vh - 44px)">
      <view class="search-header">
		    <!-- 通过batchModal来判断是否显示弹窗，否则会和弹窗上的他扫码框冲突 -->
        <scanlistener
        v-if="showScanlistener && !batchModal && !errorModal"
        suffixIcon="scan"
        ref="scanInput"
        :placeholder="$t('请扫描条形码')"
        :focus="focusStart"
        v-model="loadNumber"
        @iconClick="()=>{scanCode('loading')}"
        @confirm="scanLoad"
        @submit="loadNumber=$event;scanLoad()"
        >
        </scanlistener>
      </view>

    <scroll-view :scroll-into-view="heightLightId" scroll-y="true" class="scroll-view" scroll-with-animation>

      <view class="scroll">
        <!-- 自编号 -->
        <view class="list-header">
          <view class="title text-bold">{{$t('自编号')}}</view>
          <view class="content">{{ loadData.boxInfo.selfNo }}</view>
        </view>

        <view>
          <view class="productsList">
              <view class="flex text-center text-black bg-white text-bold padding-sm">
                <view class="flex-sub">{{$t('合包箱号')}}</view>
                <view class="flex-sub">{{$t('订单号')}}</view>
                <view class="flex-sub">{{$t('体积')}}</view>
                <view class="flex-sub">{{$t('重量')}}</view>
                <view class="flex-sub">{{$t('计划')}}/{{$t('已出')}}</view>
              </view>
              <view>
                <view class="flex text-center padding-sm" :id="'order-' + order.orderNo" :class="'order-' + order.orderNo == heightLightId ? 'bg-yellow' : 'bg-white'" v-for="(order, key) in sectionOrderList" :key="key">
                  <view class="flex-sub">{{ order.pkgNum }}</view>
                  <view class="flex-sub text-blue" @tap="showOrderDetail(true, order.orderId)">
                    <view>{{ order.orderNo }}</view>
                    <view style="color:blue;fontWeight:bold;">
                      {{ order.isExternalWarehouse === 1 ? ('('+$t('外部仓')+')') : ''}}
                    </view>
                  </view>
                  <view class="flex-sub">{{ order.volume | toFixed }} m³</view>
                  <view class="flex-sub">{{ order.weight | toFixed }} kg</view>
                  <view class="flex-sub" @click="showUnload(true, order.orderId)">
                    <view v-if="order.num != order.installNum"><text style="color:blue;">{{ order.num }}</text>/<text style="color:blue;" :class="actualClass(order.num, order.installNum)">{{ order.installNum }}</text></view>
                    <view v-else><text style="color:green;">{{ order.num }}</text>/<text style="color:green;" :class="actualClass(order.num, order.installNum)">{{ order.installNum }}</text></view>
                  </view>
                </view>
              </view>
            </view>
        </view>

        <uni-card class="margin-top bg-white infoBox">
          <view class="padding-sm padding-top-0">
            <text class="text-bold text-black">{{$t('合包后总箱数')}}：</text>
            <text class="padding-sm">{{ boxStatistics.mergeNum }}{{$t('箱')}}</text>
            <text class="padding-sm">{{ boxStatistics.mergeVolume | toFixed }}m³</text>
            <text class="padding-sm">{{ boxStatistics.mergeWeight | toFixed }}kg</text>
          </view>


<!--          <view class="padding-sm top-line">
          <view class="padding-sm top-line">
            <text class="">{{$t('合包后箱数')}}</text>
            <text class="padding-sm text-green">{{ loadData.boxInfo.boxStatistics.mergeNum }}</text>
            <text>{{$t('箱')}}</text>
            <text class=" padding-sm text-green">{{ loadData.boxInfo.boxStatistics.mergeVolume | toFixed }}</text>
            <text>m³</text>
            <text class="padding-sm text-green">{{ loadData.boxInfo.boxStatistics.mergeWeight  | toFixed }}</text>
            <text>kg</text>
          </view>
          
          <view class="padding-sm top-line">
            <text class="">{{$t('已出')}}</text>
            <text class="padding-sm text-green">{{ loadData.boxInfo.boxStatistics.loadNum }}</text>
            <text>{{$t('箱')}}</text>
            <text class=" padding-sm text-green">{{ loadData.boxInfo.boxStatistics.loadVolume | toFixed }}</text>
            <text>m³</text>
            <text class="padding-sm text-green">{{ loadData.boxInfo.boxStatistics.loadWeight | toFixed }}</text>
            <text>kg</text>
          </view> -->
		  <view class="padding-sm top-line">
			    <text class="">{{$t('订单总箱数')}}</text>
				<text class="padding-sm">{{ boxStatistics.num }}{{$t('箱')}}</text>
				<text class="padding-sm">{{ boxStatistics.volume | toFixed }}m³</text>
				<text class="padding-sm">{{ boxStatistics.weight | toFixed }}kg</text>
			</view>
			<view class="padding-sm top-line">
			    <text class="text-bold text-black">{{$t('合包后已出')}}</text>
				<text class="padding-sm">{{ boxStatistics.checkoutMergeNum }}{{$t('箱')}}</text>
				<text class="padding-sm">{{ boxStatistics.checkoutMergeVolume | toFixed }}m³</text>
				<text class="padding-sm">{{ boxStatistics.checkoutMergeWeight | toFixed }}kg</text>
			</view>
		   <view class="padding-sm top-line">
				<text class="">{{$t('订单已出箱数')}}</text>
				<text class="padding-sm">{{ boxStatistics.checkoutOrderNum }}{{$t('箱')}}</text>
				<text class="padding-sm">{{ boxStatistics.checkoutOrderVolume | toFixed }}m³</text>
				<text class="padding-sm">{{ boxStatistics.checkoutOrderWeight | toFixed }}kg</text>
			</view>
        </uni-card>

        <view class="padding-xl">
          <block>
            <view class="">
              <button class="cu-btn block bg-yellow margin-tb-sm lg" @click="showBatch(true)">{{$t('批量输入')}}</button>
            </view>
            <view class="">
              <button class="cu-btn block bg-red margin-tb-sm lg" @click="showErrorCorrection(true)">{{$t('出仓纠错')}}</button>
            </view>
            <view class="">
              <button class="cu-btn block bg-green margin-tb-sm lg" @tap="toDetail()">{{$t('下一步')}}</button>
            </view>
          </block>
        </view>
      </view>
    </scroll-view>

    <!-- 订单详情弹窗 -->
    <view class="cu-modal" :class="orderDetailModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content title-bolder">{{$t('订单详情')}}</view>
        </view>
        <scroll-view scroll-y="true" style="height: 300px;">
          <view class="cu-form-group margin-top">
            <view class="title">{{$t('订单号')}}</view>
            <view class="content">
              {{ orderDetail.orderNo }}
              <view style="color:blue;fontWeight:bold;">
                {{ orderDetail.isExternalWarehouse === 1 ? ('('+$t('外部仓')+')') : ''}}
              </view>
              <view style="color:sandybrown;fontWeight:bold;">
                {{ orderDetail.adjustToDestWarehouseId > 0 ? ('('+$t('调仓')+')') : ''}}
              </view>
            </view>
          </view>
          <view class="cu-form-group">
            <view class="title">{{$t('唛头')}}</view>
            <view class="content">{{ orderDetail.marks }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">{{$t('报关方式')}}</view>
            <view class="content"><dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="orderDetail.customsType" /></view>
          </view>
          <view class="cu-form-group">
            <view class="title">{{$t('入仓时间')}}</view>
            <view class="content">{{ orderDetail.rucangTime | formatDate }}</view>
          </view>

          <view>
            <view class="item-content" v-for="(v, goodsKey) in orderDetail.orderItemVOList" :key="'goods-' + goodsKey">
              <view>
                <view>{{$t('品名')}}：{{ $lang.locale==='zh-Hans'?v.prodTitleZh:v.prodTitleEn }}</view>
                <view>{{$t('备案')}}：
                  <template v-if="v.brandName">{{v.brandName}}</template>
                  <dict-tag v-else :type="DICT_TYPE.ECW_IS_BRAND" :value="v.feeType" />
                </view>
              </view>
              <view>
                <view>{{$t('箱数')}}：{{ v.warehouseInInfoVO && v.warehouseInInfoVO.cartonsNum }}</view>
                <view>{{$t('体积')}}：{{ v.warehouseInInfoVO && v.warehouseInInfoVO.volume | toFixed }} CBM</view>
              </view>
              <view>
                <view>{{$t('重量')}}：{{ v.warehouseInInfoVO && v.warehouseInInfoVO.weight | toFixed }} kg</view>
                <view>
                  {{$t('储位')}}：
                  <template v-if="v.warehouseInInfoVO && v.warehouseInInfoVO.orderLocationMergeVOSet">
                    {{v.warehouseInInfoVO.orderLocationMergeVOSet.map(location => `${location.areaName}${location.locationName || ''}`).join(',')}}
                  </template>
				        </view>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="cu-bar bg-white justify-end top-line">
          <view class="action"><button class="cu-btn bg-grey" @tap="showOrderDetail(false)">{{$t('取消')}}</button></view>
        </view>
      </view>
    </view>

    <!-- 未装弹窗 -->
    <view class="cu-modal" :class="unloadModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content title-bolder">{{$t('未出')}}</view>
        </view>
        <scroll-view scroll-y="true" style="height: 300px;">
          <view class="cu-form-group" v-for="(item, k) in unloadList" :key="k">
            <view class="content">{{ item }}</view>
          </view>
        </scroll-view>
        <view class="cu-bar bg-white justify-end top-line">
          <view class="action"><button class="cu-btn bg-grey" @tap="showUnload(false)">{{$t('返回')}}</button></view>
        </view>
      </view>
    </view>

    <!-- 批量输入 -->
    <view class="cu-modal" :class="batchModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content title-bolder">{{$t('批量输入1')}}</view>
        </view>
        <view>
          <view>
            <view class="cu-bar bg-white search">
              <view class="search-form round">
				<!-- 通过batchModal来判断是否显示弹窗，否则会和页面上的其他扫码狂冲突 -->
                <scanlistener
                v-if="showScanlistener && batchModal && !errorModal"
                suffixIcon="scan"
                :placeholder="$t('请扫描订单号')"
                v-model="scanNumber"
                @iconClick="()=>{scanCode('batchScan')}"
                @confirm="batchScan"
                @submit="scanNumber=$event;batchScan()"
                style="width: 100%"
                ></scanlistener>
              </view>
            </view>
            <view>
              <view v-if="true" class="cu-form-group">
                <text class="title">{{$t('订单号')}}:</text>
                <text class="content">{{ batchOrderInfo.orderNo }}</text>
              </view>
              <view v-else class="cu-form-group">
              <text class="title">{{$t('合包箱号')}}:</text>
              <text class="content">{{ unloadpkgNum }}</text>
            </view>
              <view class="cu-form-group">
                <text class="title">{{$t('箱数')}}:</text>
                <input v-if="batchOrderInfo.isExternalWarehouse === 1" class="text-right" type="number" v-model.number="batchOrderInfo.num" :placeholder="$t('输入箱数')" />
                <text v-else class="content">{{ batchOrderInfo.num }}箱</text>

              </view>
              <view class="cu-form-group">
                <text class="title">{{$t('方数')}}:</text>
                <text class="content">{{ batchOrderInfo.volume | toFixed }}m³</text>
              </view>
              <view class="cu-form-group">
                <text class="title">{{$t('重量')}}:</text>
                <text class="content">{{ batchOrderInfo.weight | toFixed }}kg</text>
              </view>
              <view class="cu-form-group">
                <text class="title">{{$t('储位')}}:</text>
                <text class="content">{{ batchOrderInfo.positionNo }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="cu-bar bg-white justify-end top-line">
          <view class="action">
            <button class="cu-btn bg-green" @tap="batchConfirm">{{ $t('确认') }}</button>
            <button class="cu-btn bg-grey margin-left" @tap="showBatch(false)">{{$t('返回')}}</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 批量密码弹窗 -->
    <view class="cu-modal" :class="batchPwModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content title-bolder">{{$t('批量输入2')}}</view>
        </view>
        <view class="cu-form-group">
          <text class="title">{{$t('密码')}}:</text>
          <input class="text-right" :placeholder="$t('请输入密码')" type="text" password="true" v-model="batchLoadPassword" />
        </view>
        <view class="cu-bar bg-white justify-end top-line">
          <view class="action">
            <button class="cu-btn bg-green" @tap="submitBatch">{{$t('确认')}}</button>
            <button class="cu-btn bg-grey margin-left" @tap="showBatchPassword(false)">{{$t('取消')}}</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 出仓纠错 -->
    <view class="cu-modal" :class="errorModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content title-bolder">{{$t('出仓纠错')}}</view>
        </view>
        <view>
          <view class="cu-bar bg-white search">
            <view class="search-form round">
              <!-- <uni-easyinput suffixIcon="scan" :placeholder="$t('请扫描订单号')" v-model="unloadNumber" @iconClick="()=>{scanCode('unloadConfirm')}" @confirm="unloadConfirm"></uni-easyinput> -->
			  <scanlistener
			  v-if="showScanlistener && !batchModal && errorModal"
			  suffixIcon="scan"
			  :placeholder="$t('请扫描订单号/合包箱号')"
			  v-model="unloadNumber"
			  @iconClick="()=>{scanCode('unloadConfirm')}"
			  @confirm="unloadConfirm"
			  @submit="unloadNumber=$event;unloadConfirm()"
			  darkIcon
			  style="width:calc(100% - 10px); "
			  :styles="{color:'#333'}"
			  ></scanlistener>
			</view>
          </view>
          <view>
            <view v-if="!mergeOrder" class="cu-form-group">
              <text class="title">{{$t('订单号')}}:</text>
              <text class="content">{{ unloadConfirmNumber }}</text>
            </view>
            <view v-else class="cu-form-group">
              <text class="title">{{$t('合包箱号')}}:</text>
              <text class="content">{{ unloadpkgNum }}</text>
            </view>
            <view class="cu-form-group">
              <text class="title">{{$t('标签号')}}:</text>
              <input class="text-right" :placeholder="$t('开始')" type="number" v-model="unloadSubNumberBegin" />
              <text class="text-bold">-</text>
              <input class="text-right" :placeholder="$t('结束')" type="number" v-model="unloadSubNumberEnd" />
            </view>
          </view>
        </view>
        <view class="cu-bar bg-white justify-end top-line">
          <view class="action">
            <button class="cu-btn bg-green" @tap="unload">{{ $t('确认') }}</button>
            <button class="cu-btn bg-grey margin-left" @tap="showErrorCorrection(false)">{{$t('返回')}}</button>
          </view>
        </view>
      </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 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>
          </view>
          <view>
            <text>{{$t('计划箱数')}}</text>
            <view>{{params.planNum}}</view>
          </view>
          <view>
            <text>{{$t('出仓箱数')}}</text>
            <view>{{params.realNum}}</view>
          </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 imageListMain" :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.remark" 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 cl" type="default" size="mini" @tap="cancel">{{$t('取消')}}</button>
        </view>
      </view>
    </uni-popup>
  </view>

</template>

<script>
import * as types from "@/store/mutations-types.js";
import util from "@/util/util.js";
import mixins from "@/mixins/mixin.js";
import iconpath from "@/static/images/close.png";
import {
  getLoadingDetail,
  getOrderDetailAdmin,
  orderTagList,
  getOrderDetailByBoxNo,
  batchLoadGoods,
  unloadGoods,
  loadGoods,
  listByOrderId,
} from "../loading/api";
import { getAdjustWaitOutList, warehouseAdjustSendOutBatch, getSupplierPage,getAirShipmentByShipmentId,boxAirCheckoutGet,warehouseCreate,getAirCheckoutByShipmentId,searchLoadOrderByBoxNo,batchAirCreate,singleAirCreate } from './api'
import { updateImg } from "@/api/system";

export default {
  name: "loading-detail",
  components: {
  },
  mixins: [mixins],
  data() {
    return {
      movingOrderId: undefined,
      popupMessage: '',
      /* 出货ID */
      shipmentId: null,
      /* 自编号 */
      keyword: "",
      /* 图片 */
      imageList: [],
      imageListMain: [],
      iconpath: iconpath,
      /* 出仓数据 */
      loadData: {
        boxInfo: {
          cabinetRespVO: {},
          boxStatistics: {},
        },
        loadDetail: {},
      },
      /* 部分的汇总数据 */
      totalSecStatistics: {
        num: 0,
        volume: 0,
        weight: 0,
      },
      /* 折叠 */
      partShow: [],
      /* 订单详情 */
      orderDetailModal: false,
      orderDetail: {},
      /* 未装详情 */
      unloadModal: false,
      unloadList: [],
      /* 批量输入 */
      batchModal: false,
      scanNumber: "",
      batchOrderInfo: {},
      /* 出仓纠错 */
      errorModal: false,
      unloadNumber: "",
      unloadConfirmNumber: "",
      mergeOrder: false,
      unloadpkgNum: "",
      unloadSubNumberBegin: "",
      unloadSubNumberEnd: "",
      /* 批量密码 */
      batchPwModal: false,
      batchLoadPassword: "",
      /* 扫描出仓 */
      loadNumber: "",
      /* 高亮 */
      heightLightId: "",
      onHideFlag: false,
      isFocus: false,
      focusStart: false,
      focusError: false,
      //出仓订单信息
      sectionOrderList: [],
      //出仓信息
      params: {},
      selectItem: {},
	  totalMergeData:{},
	  totalMergecheckoutData:{},
	  orderCheckoutData:{},
    boxStatistics: {}
    };
  },
  computed: {
    /* 折叠样式 */
    iconClass() {
      return (k) => {
        return this.partShow[k] == undefined || this.partShow[k]
          ? "cuIcon-unfold"
          : "cuIcon-fold";
      };
    },
    /* 折叠样式 */
    partClass() {
      return (k) => {
        return this.partShow[k] == undefined || this.partShow[k] ? "" : "none";
      };
    },
    /* 计划实装标红 */
    actualClass() {
      return (plan, actual) => {
        return this.comparePlanAndActual(plan, actual) ? "" : "text-red";
      };
    },
    /* 计划实装标红 */
    comparePlanAndActual() {
      return (plan, actual) => {
        return plan == actual;
      };
    },
  },
  methods: {
    delimage(index) {
      this.imageListMain.splice(index, 1);
      this.saveImage()
    },
    /* 视频/图片 */
    chooseVideoImage() {
      uni.showActionSheet({
        title: this.$t("选择上传类型"),
        itemList: [this.$t("图片") /* , this.$t("视频") */],
        success: (res) => {
          if (res.tapIndex == 0) {
            this.chooseImages();
          } else {
            this.chooseVideo();
          }
        },
      });
    },
    /* 视频/图片 */
    chooseImages() {
      uni.chooseImage({
        count: 9, // 默认是9张
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], //从相册选择
        success: (res) => {
          res.tempFilePaths.forEach((item, index) => {
            updateImg(item).then((data) => {
              this.imageListMain.push({ type: "image", url: data.data });
              this.saveImage()
            });
          });
        },
      });
    },
    saveImage() {
      this.params.shipmentId = this.selectItem.shipmentId
      this.params.operateType = 1
      if (this.imageListMain.length > 0){
        this.params.checkoutFiles = this.imageListMain.map(v => v.url).join(',')
      }else{
        this.params.checkoutFiles = ''
      }
      if(this.params.id){
        warehouseAdjustSendOutBatch(this.params)
      }else{ 
        warehouseCreate(this.params)
      }
    },
    /* 视频/图片 */
    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;
          // 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();
      }
    },
    /* 折叠 */
    fold(k) {
      if (this.partShow[k]) this.partShow[k] = true;
      this.partShow[k] = !this.partShow[k];
      this.$forceUpdate();
    },
    /* 显示未装 */
    showUnload(show, orderId) {
      this.unloadModal = show;
      if (show) {
        orderTagList({
          orderId: orderId,
        }).then((res) => {
          this.unloadList = res.unLoadList;
        });
      }
    },
    /* 消息提示与loading */
    showMessageAndReload(message) {
      this.$store.dispatch(types.SHOW_TOAST, {
        msg: message,
      });
      setTimeout(() => {
        this.getLoadDetail();
      }, 1000);
    },
    /* 重新加载 */
    reload() {
      setTimeout(() => {
        this.getLoadDetail();
      }, 1000);
    },
    /* 显示批量输入 */
    showBatch(show) {
      this.scanNumber = "";
      this.batchModal = show;
    },
    /* 批量扫描-读取信息 */
    batchScan() {
      this.isFocus = false;
      setTimeout(this.batchScanReal, 100);
    },
    batchScanReal() {
      this.isFocus = true;
      this.scanNumber = util.getQrCode(this.scanNumber);
      this.batchOrderInfo = {};
      getOrderDetailByBoxNo({
        orderNumCode: this.scanNumber,
        shipmentId: this.shipmentId,
      })
        .then((data) => {
          this.batchOrderInfo = {
            orderId: data.orderId,
            orderNo: data.orderNo,
            isExternalWarehouse: data.isExternalWarehouse,
            num: data.num,
            volume: data.volume,
            weight: data.weight,
          };
        //   if(data.mergeOrder){
        //   this.mergeOrder = data.mergeOrder;
        //   this.unloadpkgNum = data.mergeOrderNum;
        // }
          listByOrderId({ orderId: data.orderId }).then((data) => {
            let positionNos = [...(new Set(data.map((item) => {
              return `${item.warehouseName ?? ""}${item.areaName ?? ""}${
                item.locationName ?? ""
              }`;
            })))];
            this.$set(this.batchOrderInfo, "positionNo", positionNos.join(","));
          });
        })
        .catch(() => {
          this.scanNumber = "";
        });
    },
    /* 显示批量输入密码 */
    showBatchPassword(show) {
      this.batchPwModal = show;
    },
    /* 显示出仓纠错 */
    showErrorCorrection(show) {
      this.errorModal = show;
      this.unloadNumber = "";
      this.unloadConfirmNumber = "";
      this.unloadSubNumberBegin = "";
      this.unloadSubNumberEnd = "";
      this.mergeOrder = false;
      this.unloadpkgNum = "";
    },
    /* 显示订单详情 */
    showOrderDetail(show, id) {
      this.orderDetailModal = show;
      if (show) {
        this.getOrderDetail(id);
      }
    },
    /* 读取订单详情 */
    getOrderDetail(id) {
      return new Promise((resolve, reject) => {
        getOrderDetailAdmin(id).then((data) => {
          //订单信息
          this.orderDetail = data;
          listByOrderId({ orderId: id }).then((data) => {
            let positionNos = data.map((item) => {
              return `${item.warehouseName ?? ""}${item.areaName ?? ""}${
                item.locationName ?? ""
              }`;
            });
            this.$set(this.orderDetail, "positionNo", positionNos.join(","));
          });
        });
      });
    },
    scanCode(type) {
      uni.scanCode({
        success: (res) => {
          switch (type) {
            case "batchScan":
              this.scanNumber = res.result;
              this.batchScan();
              break;
            case "loading":
              this.loadNumber = res.result;
              this.scanLoad();
              break;
            case "unloadConfirm":
              this.unloadNumber = res.result;
              this.unloadConfirm();
              break;
          }
        },
      });
    },
    /* 扫描出仓 */
    scanLoad() {
      this.focusStart = false;
      setTimeout(() => {
        if (this.shipmentId) {
          let loadCode = util.getQrCode(this.loadNumber);
          this.focusStart = true;
          singleAirCreate({
            shipmentId: this.shipmentId,
            orderNumCode: loadCode,
          })
            .then((data) => {
              this.showMessageAndReload("出仓成功");
              //跳转高亮
              let mainNumber = this.loadNumber.substring(
                0,
                this.loadNumber.lastIndexOf("-")
              );
              if (this.heightLightId != "order-" + mainNumber.toUpperCase()) {
                setTimeout(() => {
                  this.heightLightId = "order-" + mainNumber.toUpperCase();
                }, 1500);
              }

              this.ScanSuccess();

              //清空
              this.loadNumber = "";
            })
            .catch((data) => {
              //其它错误
              this.$store.dispatch("SHOW_TOAST", {
                msg: data.msg,
              });
              //清空
              this.loadNumber = "";

              this.ScanError();
            });
        }
      }, 100);
    },
    /* 确认出仓纠错订单 */
    unloadConfirm() {
      this.focusError = false;
      // 扫码速度过快，可能导致取值不完整，所以延迟执行
      setTimeout(this.unloadConfirmReal, 100);
    },
    unloadConfirmReal() {
      this.unloadNumber = util.getQrCode(this.unloadNumber);
      searchLoadOrderByBoxNo({
        orderNumCode: this.unloadNumber,
        shipmentId: this.shipmentId,
      }).then((res) => {
        const { orderNo } = res;
        if (orderNo) {
          // 替换掉真实的订单号
          let numbers = this.unloadNumber.replace(orderNo, "");
          numbers = numbers.split("-"); // 去掉箱号
          //自动按后面箱号输入范围
          if (numbers.length > 1) {
            this.unloadSubNumberBegin = numbers[numbers.length - 1];
            this.unloadSubNumberEnd = numbers[numbers.length - 1];
          }
          this.unloadConfirmNumber = orderNo;
        }
        if(res.mergeOrder){
          this.mergeOrder = res.mergeOrder;
          this.unloadpkgNum = res.mergeOrderNum;
          this.unloadSubNumberBegin = 1;
          this.unloadSubNumberEnd = 1;
          this.unloadConfirmNumber = res.mergeOrderNum;
        }
        else{
          this.mergeOrder = false;
          this.unloadSubNumberBegin = '';
          this.unloadSubNumberEnd = '';
        }
      });
      this.focusError = true;
    },
    /* 删除出仓 */
    unload() {
      if (
        this.unloadConfirmNumber &&
        this.unloadSubNumberBegin &&
        this.unloadSubNumberEnd
      ) {
        unloadGoods({
          orderNo: this.unloadConfirmNumber,
          shipmentId: this.shipmentId,
          startNo: this.unloadSubNumberBegin,
          endNo: this.unloadSubNumberEnd,
        }).then((data) => {
          if (data) {
            this.showMessageAndReload(this.$t("出仓纠错成功"));
            this.showErrorCorrection(false);
            this.unloadNumber = "";
            this.unloadConfirmNumber = "";
            this.unloadSubNumberBegin = "";
            this.unloadSubNumberEnd = "";
          }
        });
      } else {
        this.$store.dispatch(types.SHOW_TOAST, {
          msg: this.$t("请输入或扫描正确订单号与标签号"),
        });
        this.unloadNumber = "";
        this.unloadConfirmNumber = "";
        this.unloadSubNumberBegin = "";
        this.unloadSubNumberEnd = "";
      }
    },
    /* 计算部分的汇总数据 */
    getSecTotal() {
      // 部分汇总
      let totalSecStatistics = {
        num: 0,
        volume: 0,
        weight: 0,
      };
	  //合包后总箱数
	  let totalMergeData = {
		  num: 0,
		  volume: 0,
		  weight: 0,
	  }
	  //合包后已出
	  let totalMergecheckoutData = {
	  		  num: 0,
	  		  volume: 0,
	  		  weight: 0,
	  }
	  //订单已出箱数
	  let orderCheckoutData = {
	  		  num: 0,
	  		  volume: 0,
	  		  weight: 0,
	  }
      const { boxInfo } = this.loadData;
      this.boxStatistics = boxInfo.boxStatistics
    //   loadDetail.forEach((v, k) => {
    //     const { secStatistics } = v;
    //     if (secStatistics) {
    //       totalSecStatistics.num += secStatistics.num;
    //       totalSecStatistics.volume += secStatistics.volume;
    //       totalSecStatistics.weight += secStatistics.weight;
		  
		//   totalMergeData.num += secStatistics.mergeNum;
		//   totalMergeData.volume += secStatistics.mergeVolume;
		//   totalMergeData.weight += secStatistics.mergeWeight;
		  
		//   totalMergecheckoutData.num += secStatistics.checkoutMergeNum;
		//   totalMergecheckoutData.volume += secStatistics.checkoutMergeVolume;
		//   totalMergecheckoutData.weight += secStatistics.checkoutMergeWeight;
		  
		//   orderCheckoutData.num += secStatistics.checkoutOrderNum;
		//   orderCheckoutData.volume += secStatistics.checkoutOrderVolume;
		//   orderCheckoutData.weight += secStatistics.checkoutOrderWeight;
    //     }
    //   });
    //   this.totalSecStatistics = totalSecStatistics;
	  // this.totalMergeData = totalMergeData
	  // this.totalMergecheckoutData = totalMergecheckoutData
	  // this.orderCheckoutData = orderCheckoutData
    },
    /* 读取预装信息 */
    getLoadDetail() {
      if (this.shipmentId) {
        getLoadingDetail({
          shipmentId: this.shipmentId,
        }).then((data) => {
          this.loadData = {
            ...data,
            loadDetail: data.loadDetail,
          };
          this.sectionOrderList = data.loadDetail[0].sectionOrderList
          this.getSecTotal();
          const { cabinetInfo } = data;
          if (cabinetInfo && cabinetInfo.ldPictures) {
            try {
              this.imageList = JSON.parse(cabinetInfo.ldPictures);
            } catch (error) {
              this.imageList = [];
            }
          }
          uni.stopPullDownRefresh();
        });
      }
    },
    /* 确认批量扫描 */
    batchConfirm() {
      if (this.batchOrderInfo.orderNo) {
        if (this.batchOrderInfo.num === 0) {
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: "箱数不能为0",
          });
          return;
        }
        this.showBatchPassword(true);
      } else {
        this.$store.dispatch(types.SHOW_TOAST, {
          msg: this.$t("请输入或扫描正确订单号"),
        });
      }
    },
    /* 批量出仓 */
    submitBatch() {
      batchAirCreate({
        boxNum: this.batchOrderInfo.num,
        orderId: this.batchOrderInfo.orderId,
        orderNo: this.batchOrderInfo.orderNo,
        shipmentId: this.shipmentId,
        pwd: this.batchLoadPassword,
        checkPwd: 1,
      }).then(() => {
        this.showMessageAndReload(this.$t("批量出仓成功"));
        this.showBatchPassword(false);
        this.showBatch(false);
        this.batchOrderInfo = {};
        this.scanNumber = "";
      });
      //清空密码
      this.batchLoadPassword = "";
    },
    cancel() {
      this.$refs.popup.close()
    },
    closePopup({ show }) {
      !show && (this.selectItem = {})
      !show && (this.params = {})
    },
    confirmOut() {
      // this.params.orderIdList = this.selectItem.map(v => v.orderId)
      if(!this.params.checkoutTime){
        return uni.showToast({
          title:this.$t('请选择出仓日期'),
          icon:'error'
        })
      }
      this.params.checkoutTime = this.dayjs(this.params.checkoutTime).format("YYYY-MM-DD HH:mm:ss")
      if (this.imageListMain.length > 0) this.params.checkoutFiles = this.imageListMain.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 = {}
          uni.navigateTo({
            url: "./list",
          });
        })
      }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 = {}
          uni.navigateTo({
            url: "./list",
          });
        })
      }

    },
    async toDetail() {
      this.imageListMain = []
      await getAirShipmentByShipmentId({shipmentId:this.shipmentId}).then(res=>{
        this.selectItem = res
        // this.selectItem.containerNumber = data.selfNo
        // this.selectItem.checkoutStatus = data.checkoutStatus
      })
      getAirCheckoutByShipmentId({shipmentId:this.shipmentId}).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.imageListMain = []
            img.forEach(item=>{
              if(['jpg','jpeg','png'].indexOf(item.split('.')[item.split('.').length-1])>-1){
                this.imageListMain.push({type:'image',url:item})
              }else{
                this.imageListMain.push({type:'video',url:item})
              }
            })
          }
          if(!this.params.checkoutTime) this.params.checkoutTime = util.formatDate(new Date().getTime(), true);
        }

      })
      this.$refs.popup.open('center')
    },
  },
  onPullDownRefresh() {
    this.getLoadDetail();
  },
  onLoad: function (option) {
    uni.setNavigationBarTitle({
      title: this.$t("开始出仓"),
    });
    if ("id" in option) {
      this.shipmentId = option.id;
      this.getLoadDetail();
    }
    let today = util.formatDate(new Date().getTime(), true);
    this.confirmCloseCloseBoxTime = today; //确认封柜弹窗表单-封仓时间
    this.confirmLeaveStoreTime = today; //确认封柜弹窗表单-出仓时间
  },
  onShow() {
    if (this.onHideFlag) {
      this.getLoadDetail();
    }
  },
  onHide() {
    this.onHideFlag = true;
  },
};
</script>

<style lang="scss" scoped>

.add-popup {
  ::v-deep .uni-popup__wrapper {
    background: none !important;
  }

  .popup-content {
    width: 90vw;
    border-radius: 8px;
    background: #fff;
    padding: 8px;
    max-height: 80vh;
    overflow: auto;

    .popup-foot-btn {
      padding: 8px;
      margin-top: 8px;
      text-align: center;

      button {
        border: 1px solid #007aff;
      }

      >button+button {
        margin-left: 12px;
      }
      :last-child{
        color: #007aff;
        background: #fff;
      }
    }
  }
}
.search-header {
  ::v-deep .uni-easyinput__content {
    border-radius: 20px;
    padding-right: 10px;
    background: rgba($color: #fff, $alpha: 0.5) !important;
    border: none;
  }

  ::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;
    align-items: center;

    .title {
      flex: 1;
      font-weight: bold;
      font-size: 18px;
    }

    .checkbox-wrap {
      margin-left: auto;
      display: flex;
      align-items: center;

      > text {
        margin-right: 8px;
      }
    }
  }

  ::v-deep .uni-card {
    margin: 12px 0 0 !important;
    padding: 0 !important;
  }

  .img-wrap {
    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;
    }
  }
}

.cu-dialog {
  background-color: #fff;

  .content {
    &.title-bolder {
      color: #333333;
      font-weight: bolder;
    }
  }

  .item-content {
    text-align: left;
    padding: 10px 20px 0px 20px;

    > view {
      display: flex;
      padding: 4px 0;

      > view {
        flex: 1;
        word-break: break-all;
      }
    }
  }
}
.search-form.round {
  ::v-deep .uni-easyinput__content {
    border-radius: 20px;
    /* padding-right: 10px; */
    background: rgba($color: #fff, $alpha: 0.5) !important;
    border: none;
  }
}
.scroll-view{
  height: calc(100vh - 44px - 75px);
}

.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>
