<template>
  <view style="background: #fff; min-height: calc(100vh - 44px)">
	  <view class="search-header">
	    <scanlistener
	    v-if="showScanlistener"
	    suffixIcon="scan"
	    v-model="keyword"
		:focus="focusStart"
	    :placeholder="$t('请扫描条形码')"
	    @iconClick="()=>{scanCode('loading')}"
	    @confirm="searchCode"
	    @submit="keyword=$event;searchCode()"
	    ></scanlistener>
	  </view>
    <scroll-view scroll-y="true" scroll-with-animation>

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

        <!-- 部分 -->
        <view>
          <uni-card v-for="(v, k) in loadData.loadDetail" :key="k">
            <view class="cu-bar bg-white solid-bottom" @click="fold(k)">
              <view class="action">
                <text class="cuIcon-title text-blue"></text>
                <text class="text-bold text-black">{{ v.secName }}</text>
              </view>
              <view class="action"><text :class="iconClass(k)"></text></view>
            </view>
            <view :style="{ display: partClass(k) }" class="productsList">
              <view class="flex text-center text-black bg-white text-bold padding-sm">
                <view style="width:20%;">{{$t('订单号')}}</view>
                <view style="width:15%;">{{$t('体积')}}</view>
                <view style="width:15%;">{{$t('重量')}}</view>
                <view style="width:15%;">{{$t('计划/已理')}}</view>
                <view style="width:15%;">{{$t('储位')}}</view>
                <view style="width:20%;">{{$t('操作')}}</view>
              </view>
              <view class="padding-sm" :id="'order-' + order.orderNo" :class="'order-' + order.orderNo == heightLightId ? 'bg-yellow' : 'bg-white'" v-for="(order, key) in v.sectionOrderList" :key="key">
                <view class="flex text-center">
                  <view class="text-break text-blue" style="width:20%;">
                    <view @tap="showOrderDetail(true, order.orderId)">{{ order.orderNo }}</view>
                    <view style="color:blue;fontWeight:bold;">
                      {{ order.isExternalWarehouse === 1 ? ('('+$t('外部仓')+')') : ''}}
                    </view>
                    <view style="color:sandybrown;fontWeight:bold;">
                      {{ order.adjustToDestWarehouseId > 0 ? ('('+$t('调仓')+')') : ''}}
                    </view>
                    <!-- 报关方式 -->
                    <view v-if="order.customsType !== 1">
                      <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="order.customsType" style="color:red;fontWeight:bold;" />
                    </view>
                     <!-- 包装类型 -->
                    <view style="color:red;fontWeight:bold;">
                      <text v-for="(unit, index) in order.units.split(',')" :key="index">
                        <dict-tag :type="DICT_TYPE.ECW_PACKAGING_TYPE" :value="unit" />{{ index!== order.units.split(',').length-1 ? ',':'' }}
                      </text>
                    </view>
                    <!-- 关联单 -->
                    <view v-if="order.hasRelationOrder" style="color:red;fontWeight:bold;" @tap="relatedClick(order.orderId)">{{$t('关联单')}}</view>
                    <!-- 混箱 -->
                    <view v-if="order.mixStatus === 1" style="color:red;fontWeight:bold;">{{$t('混箱')}}</view>
                  </view>
                  <view style="width:15%;">{{ order.volume | toFixed }} m³</view>
                  <view style="width:15%;">{{ order.weight | toFixed }} kg</view>
                  <view class="text-break" style="width:15%;">
                    <!-- <view class="text-break text-blue" @tap="showGoodsDetail(true, order)">{{ order.num }}箱</view> -->
					<view class="text-break text-blue" @tap="showNoGoodsList(true,order.orderId)">{{ order.num }}/{{order.installNum}}箱</view>
                    <view style="color:blue;fontWeight:bold;">
                      {{ order.multiSpecification === true ? ('('+$t('多规格')+')') : ''}}
                    </view>
                  </view>
                  <view style="width:15%;">{{ order.positionNo }}</view>
                  <view class="" style="width:20%;">
                    <view class="flex justify-center">
                      <view class="text-blue text-bold" @click.stop="removeClick(order)">
                        {{$t('移出')}}
                      </view>
                      <view class="text-blue text-bold" style="padding-left: 5px;" @click.stop="tallyClick(order)">
                        {{$t('理货')}}
                      </view>
                    </view>
                    <view class="text-blue text-bold margin-top-sm" style="padding-left: 5px;" @click.stop="turnException(order)">
                      {{$t('转异')}}
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="padding-sm top-line bg-white">
              <text class="">{{$t('总计')}}</text>
              <text class="padding-sm text-green">{{ v.secStatistics ? v.secStatistics.num : 0 }}</text>
              <text>{{$t('箱')}}</text>
              <text class=" padding-sm text-green">{{(v.secStatistics ? v.secStatistics.volume  : 0) | toFixed }}</text>
              <text>m³</text>
              <text class="padding-sm text-green">{{ (v.secStatistics ? v.secStatistics.weight : 0) | toFixed }}</text>
              <text>kg</text>
            </view>
          </uni-card>
        </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>{{ loadData.boxInfo.cubNo }}</text>
          </view>-->
          <view class="padding-sm padding-top-0">
            <text class="text-bold text-black">{{$t('总计')}}：</text>
            <text class="padding-sm">{{ totalSecStatistics.num }}{{$t('箱')}}</text>
            <text class="padding-sm">{{ totalSecStatistics.volume | toFixed }}m³</text>
            <text class="padding-sm">{{ totalSecStatistics.weight | toFixed }}kg</text>
          </view>
          <!--<view class="padding-sm padding-top-0" v-if="loadData.boxInfo.cabinetRespVO">
            <text class="text-bold text-black">{{$t('容量')}}：</text>
            <text class="padding-sm">{{ loadData.boxInfo.cabinetRespVO.name }}</text>
            <text class="padding-sm">{{ loadData.boxInfo.cabinetRespVO.volume | toFixed }}m³</text>
            <text class="padding-sm">{{ loadData.boxInfo.cabinetRespVO.weight | toFixed }}kg</text>
          </view>-->
        </uni-card>

        <view class="padding-xl">
          <block>
            <view class="flex-sub" style="padding-right: 10px;">
              <button class="cu-btn block bg-yellow margin-tb-sm lg" @click="toPatch">{{$t('补单')}}</button>
            </view>
			  <view class="flex">
				<view class="flex-sub">
				  <button class="cu-btn block bg-red margin-tb-sm lg" @click="showErrorCorrection(true)">{{$t('理货纠错')}}</button>
				</view>
			    <view class="flex-sub" style="padding-left: 10px;">
			      <button class="cu-btn block bg-yellow margin-tb-sm lg" @click="showBatch(true)">{{$t('批量输入')}}</button>
			    </view>
			  </view>
            <view class="flex">
              <view class="flex-sub" style="padding-right: 10px;">
                <button class="cu-btn block bg-blue margin-tb-sm lg" @click="tallyFinish">{{$t('完成理货')}}</button>
              </view>
              <view class="flex-sub" style="padding-left: 10px;">
                <button class="cu-btn block bg-gray margin-tb-sm lg" @click="goBack">{{$t('返回')}}</button>
              </view>
            </view>
          </block>
        </view>
      </view>
    </scroll-view>

    <!-- 订单详情弹窗 -->
    <OrderDetailModal :orderDetailModal="orderDetailModal" :orderDetail="orderDetail" @close="showOrderDetail"></OrderDetailModal>
    <!-- <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>
            <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('备案')}}：
                  <dict-tag :type="DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE" :value="orderDetail.productRecord" />
                </view>
              </view>
              <view v-if="v.warehouseInInfoVO">
                <view>{{$t('箱数')}}：{{ v.warehouseInInfoVO.cartonsNum }}</view>
                <view>{{$t('体积')}}：{{ v.warehouseInInfoVO.volume | toFixed }} CBM</view>
              </view>
              <view v-if="v.warehouseInInfoVO">
                <view>{{$t('重量')}}：{{ v.warehouseInInfoVO.weight | toFixed }} kg</view>
                <view>{{$t('储位')}}: {{ showLocationName(v.warehouseInInfoVO.orderLocationMergeVOSet) }}</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="goodsModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content title-bolder" style="width:100%;">{{`${$t('货物详情')}-${$t('订单号')}${currRow.orderNo}`}}</view>
        </view>
        <scroll-view scroll-y="true" style="height: 400px;">
          <uni-card v-for="(v, key) in currRow.goodsList" :key="key">
            <view class="item-content noPadding">
              <view>
                <view>{{$t('中文名')}}：{{ v.prodTitleZh }}</view>
                <view>{{$t('英文名')}}：{{ v.prodTitleEn }}</view>
              </view>
              <view>
                <view>{{$t('品牌')}}：
                  {{ v.brandName }}
                </view>
                <view>
                  <view class="flex">
                    {{$t('入仓件数')}}：
                    <view class="text-break text-blue" @tap="showWarehouseLogs(v)">
                      <view>{{ v.num }}{{ $t('箱') }}</view>
                      <view style="color:blue;fontWeight:bold;">
                        {{ v.multiSpecification === true ? ('('+$t('多规格')+')') : '' }}
                      </view>
                    </view>
                  </view>
                </view>
              </view>
              <view>
                <view>{{$t('材质')}}:
                  <dict-tag :type="DICT_TYPE.ECW_PRODUCT_MATERIAL" :value="v.material" />
                </view>
                <view>{{$t('体积') + '(m³)'}}：{{ v.volume }}</view>
              </view>
              <view>
                <view>{{$t('重量') + '(kg)'}}：{{ v.weight }}</view>
                <view>{{$t('入仓快递单号')}}：{{ JSON.parse(v.warehouseInInfo).expressNo }}</view>
              </view>
              <view>
                <view>{{$t('数量') + '(个)'}}：{{ v.quantity }}</view>
				        <view>{{$t('储位')}}：{{v.positionNo || showLocationName(v.orderItemLocationList)}}</view>
              </view>
            </view>
          </uni-card>
        </scroll-view>

        <view class="cu-bar bg-white justify-end top-line">
          <view class="action"><button class="cu-btn bg-grey" @tap="showGoodsDetail(false)">{{$t('关闭')}}</button></view>
        </view>
      </view>
    </view>
	<view class="cu-modal" :class="noTallyAir ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content title-bolder" style="width:100%;">{{$t('未理')}}</view>
        </view>
        <scroll-view scroll-y="true" style="height: 400px;">
            <view class="item-content" v-for="(v, index) in noTallyAirList" :key="index">
                <view>{{v}}</view>
            </view>
        </scroll-view>

        <view class="cu-bar bg-white justify-end top-line">
          <view class="action"><button class="cu-btn bg-grey" @tap="showNoGoodsList(false)">{{$t('返回')}}</button></view>
        </view>
      </view>
    </view>
    <warehouse-detail ref="warehouseDetail" :orderId="orderId" :orderItemId="showWarehouseInItemId" />
    <warehouse-list ref="warehouseList" />
    <mix-order-list ref="mixOrderList" />

    <uni-popup ref="popup" class="add-popup">
      <view class="popup-content">
        <view style="padding: 20px">
          {{ popupMessage }}
        </view>

        <view class="popup-foot-btn">
          <button class="mini-btn" type="primary" size="mini" @tap="removeClick2(2)">{{$t('确定移出')}}</button>
          <button class="mini-btn" type="primary" size="mini" @tap="removeClick2(1)">{{$t('仅移出当前订单')}}</button>
          <button class="mini-btn" type="default" size="mini" @tap="$refs.popup.close()">{{$t('取消')}}</button>
        </view>
      </view>
    </uni-popup>
	<!-- 批量输入 -->
	<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('批量输入')}}</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 class="cu-form-group">
	            <text class="title">{{$t('订单号')}}:</text>
	            <text class="content">{{ batchOrderInfo.orderNo }}</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="submitBatch">{{ $t('确认') }}</button>
	        <button class="cu-btn bg-grey margin-left" @tap="showBatch(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 class="cu-form-group">
              <text class="title">{{$t('订单号')}}:</text>
              <text class="content">{{ unloadConfirmNumber }}</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>
    <exception v-if="!!turnExceptionOrder" :detail="turnExceptionOrder" @close="turnExceptionOrder=null"
      @success="turnExceptionOrder=null"
    ></exception>
  </view>

</template>

<script>
import * as types from "../../store/mutations-types.js";
import mixins from "../../mixins/mixin.js";
import {
  tallyList,
  tallyRemove,
  tallyLocationUpdate,
  tallyCommit,
  listByOrderId,
  tallyPage,
  batchCreateMore,
  batchDeleteMore,
  singleCreate,
  orderTagList
} from "./api";
import { getOrderDetail, getLoadingDetail,getOrderDetailByBoxNo } from "../loading/api";
import WarehouseDetail from "./warehouseDetail.vue";
import WarehouseList from "@/pages/tally/warehouseList.vue";
import MixOrderList from "@/pages/tally/mixOrderList.vue";
import Exception from "./components/exception.vue";
import OrderDetailModal from "@/components/order-detail-modal/index.vue"
import util from "../../util/util.js";

export default {
  name: "tally-detail",
  components: { Exception, WarehouseDetail, OrderDetailModal, WarehouseList, MixOrderList },
  mixins: [mixins],
  data() {
    return {
      removeOrderIds: undefined,
      popupMessage: '',
      /* 出货ID */
      shipmentId: null,
      /* 理货数据 */
      loadData: {
        boxInfo: { cabinetRespVO: {} },
        loadDetail: [],
      },
      /* 部分的汇总数据 */
      totalSecStatistics: {
        num: 0,
        volume: 0,
        weight: 0,
      },
      /* 折叠 */
      partShow: [],
      /* 订单详情 */
      orderDetailModal: false,
      orderDetail: {},
      onHideFlag: false,
      // 储位信息
      orderLocationCreateReqVOList: [],
      // 入仓记录
      showWarehouseInItemId: null,
      orderId: null,
      // 货物详情
      goodsModal: false,
      // 当前行
      currRow: {},
      // 当前转异订单
      turnExceptionOrder: null,
	   keyword: "",
	   //未理货箱号
	   noTallyAir:false,
	   noTallyAirList:[],
      /* 批量输入 */
      batchModal: false,
      scanNumber: "",
      batchOrderInfo: {},
      /* 装柜纠错 */
      errorModal: false,
      unloadNumber: "",
      unloadConfirmNumber: "",
      unloadSubNumberBegin: "",
      unloadSubNumberEnd: "",
	  isFocus:false,
	  focusStart: false,
	  focusError:false,
	  /* 高亮 */
	  heightLightId: "",
	  onHideFlag: false,
    };
  },
  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";
      };
    },
  },
  watch: {
    orderLocationCreateReqVOList: {
      deep: true,
      handler: function (val) {
        this.tallyModify(val);
      },
    },
  },
  methods: {
	  scanCode(type) {
	    uni.scanCode({
	      success: (res) => {
	        switch (type) {
	          case "batchScan":
	            this.scanNumber = res.result;
	            this.batchScan();
	            break;
	          case "loading":
	            this.keyword = res.result;
	            this.getDetialOfSelfNO();
	            break;
	          case "unloadConfirm":
	            this.unloadNumber = res.result;
	            this.unloadConfirm();
	            break;
	        }
	      },
	    });
	  },
	  searchCode() {
		setTimeout(this.getDetialOfSelfNO, 100)
	  },
	  /* 显示装柜纠错 */
	  showErrorCorrection(show) {
	    this.errorModal = show;
	    this.unloadNumber = "";
	    this.unloadConfirmNumber = "";
	    this.unloadSubNumberBegin = "";
	    this.unloadSubNumberEnd = "";
	  },
	  /* 显示批量输入 */
	  showBatch(show) {
	    this.scanNumber = "";
	    this.batchModal = show;
	  },
    // 从warehouseInInfo中提取储位信息
    showLocationName(locationList){
      if(!locationList || !locationList.length) return ''
      let locations = new Set()
      locationList.forEach(item => {
        locations.add((item.areaName || '') + (item.locationName || ''))
      })
      return Array.from(new Set(locations)).join(',')
    },
    // 显示入仓列表
    showWarehouseList(row) {
      this.orderId = row.orderId;
      this.$refs.warehouseList.showDetail(row);
    },
    // 显示混箱明细
    showMixOrder(row) {
      this.orderId = row.orderId;
      this.$refs.mixOrderList.showDetail(row);
    },
    // 显示入仓记录
    showWarehouseLogs(row) {
      this.orderId = row.orderId;
      this.showWarehouseInItemId = row.orderItemId;
      this.$refs.warehouseDetail.showDetail(row);
    },
    // 货物详情
    showGoodsDetail(show, row) {
      if (show) this.currRow = row;
      this.goodsModal = show;
    },
	showNoGoodsList(show,orderId=0) {
	   this.noTallyAir = show;
	   if(show){
		   this.noTallyAirList = []
		   orderTagList(orderId,0).then(data=>{
			   if(data&&data.unLoadList){
				   this.noTallyAirList = data.unLoadList
			   }
		   })
	   }
	},
    /* 折叠 */
    fold(k) {
      if (this.partShow[k]) this.partShow[k] = true;
      this.partShow[k] = !this.partShow[k];
      this.$forceUpdate();
    },
    /* 消息提示与loading */
    showMessageAndReload(message) {
      this.$store.dispatch(types.SHOW_TOAST, {
        msg: message,
      });
      setTimeout(() => {
        this.getLoadDetail();
      }, 1000);
    },
    /* 显示订单详情 */
    showOrderDetail(show, id) {
      this.orderDetailModal = show;
      if (show) {
        this.getOrderDetail(id);
      }
    },
    /* 读取订单详情 */
    getOrderDetail(id) {
      return new Promise((resolve, reject) => {
        getOrderDetail(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(","));
          });
        });
      });
    },
    /* 计算部分的汇总数据 */
    getSecTotal() {
      // 部分汇总
      let totalSecStatistics = {
        num: 0,
        volume: 0,
        weight: 0,
      };
      const { loadDetail } = this.loadData;
      loadDetail.forEach((v, k) => {
        const { secStatistics } = v;
        if (secStatistics) {
          totalSecStatistics.num += secStatistics.num;
          totalSecStatistics.volume += secStatistics.volume;
          totalSecStatistics.weight += secStatistics.weight;
        }
      });
      this.totalSecStatistics = totalSecStatistics;
    },
    /* 过滤包装类型 */
    uniqueArr(arr) {
      return arr.filter((obj, index, self) =>
      index === self.findIndex((t) => t.unit === obj.unit));
    },
    /* 读取理货详情 */
    getLoadDetail() {
	  this.focusStart = false
      if (this.shipmentId) {
        // 获取出货信息
        getLoadingDetail({ shipmentId: this.shipmentId,orderNumCode:this.keyword}).then((res) => {
          this.loadData.boxInfo = res.boxInfo;
        });
        tallyList({ shipmentId: this.shipmentId }).then((res) => {
			 this.focusStart = true
          let newLoadDetail = [];
          res?.forEach((item) => {
            if (item.sectionOrderList && item.sectionOrderList.length) {
              newLoadDetail.push({
                ...item,
                secName: item.sectionOrderList[0].sectionName,
              });
            }
          });

		  //清空

          this.loadData.loadDetail = newLoadDetail;
          this.getSecTotal();
          uni.stopPullDownRefresh();
        });
      }
    },
	getDetialOfSelfNO(){
		singleCreate({shipmentId:parseInt(this.shipmentId),type:0,orderNumCode:this.keyword}).then((data)=>{
			 this.showMessageAndReload("理货成功");
			 let mainNumber = this.keyword.substring(
			   0,
			   this.keyword.lastIndexOf("-")
			 );
			 if (this.heightLightId != "order-" + mainNumber.toUpperCase()) {
			     setTimeout(() => {
			       this.heightLightId = "order-" +  mainNumber.toUpperCase();
			     }, 1500);
			   }
			   this.ScanSuccess();

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

			   this.ScanError();
			});

		// tallyPage({selfNo:this.keyword}).then((data) => {
		// 	if(data.list.length>0){
		// 		this.shipmentId = data.list[0].id
		// 		this.getLoadDetail();
		// 	}
		// })
	},
    /* 二次确认移出 */
    removeClick2(deleteType) {
      tallyRemove({
        orderIdLIst: this.removeOrderIds,
        shipmentId: this.shipmentId,
        deleteType
      }).then((res) => {
        if (res) {
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: this.$t("移出成功"),
          });
          this.$refs.popup.close()
          setTimeout(() => {
            this.getLoadDetail();
          }, 1000);
        }
      })
    },
    /* 移出 */
    removeClick(data) {
      let orderIds = [data.orderId];
      this.removeOrderIds = orderIds

      let _content = `${this.$t("请问您是否要将订单：")}${
        data.orderNo
      }${this.$t("移出当前出货单")}?`;

      uni.showModal({
        content: _content,
        success: (e) => {
          if (e.confirm) {
            tallyRemove({
              orderIdLIst: orderIds,
              shipmentId: this.shipmentId,
            }).then((res) => {
              if (res === true) {
                this.$store.dispatch(types.SHOW_TOAST, {
                  msg: this.$t("移出成功"),
                });
                setTimeout(() => {
                  this.getLoadDetail();
                }, 1000);
              } else {
                this.popupMessage = res.msg.replace(/<br>/g, '') + this.$t('，是否需要一起移出?')
                this.$refs.popup.open()
              }
            });
          }
        },
      });
    },
    /* 理货 */
    tallyClick(row) {
      const { boxInfo } = this.loadData;
      const { orderLocationList } = row;
      let url = `../warehousing/location?orderId=${row.orderId}&warehouseId=${boxInfo.startWarehouseId}`;
      if (orderLocationList && orderLocationList.length) {
        let locationList = [];
        for (const item of orderLocationList) {
          let local = Object.assign({}, item, {
            code: `${item.areaName}${item.locationName}`,
          });
          locationList.push(local);
        }
        locationList = JSON.stringify(locationList);
        url = `${url}&locationList=${locationList}`;
      }

      uni.navigateTo({
        url: url,
      });
    },
    /* 修改储位 */
    tallyModify(val) {
      if (val.length === 0) {
        setTimeout(() => {
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: this.$t("未选择储位信息"),
          });
        }, 200);
        return;
      }
      tallyLocationUpdate({
        shipmentId: this.shipmentId,
        orderLocationList: val,
      }).then((res) => {
        this.getLoadDetail();
      });
    },
    /* 跳转到关联单 */
    relatedClick(orderNo) {
      const { boxInfo } = this.loadData;
      uni.navigateTo({
        url: `../tally/relatedOrder?orderId=${orderNo}&selfNo=${boxInfo.selfNo}`,
      });
    },
    /* 跳转到补单 */
    toPatch() {
      const { boxInfo } = this.loadData;
      uni.navigateTo({
        url: `../mergePkg/patch?id=${this.shipmentId}&selfNo=${boxInfo.selfNo}`,
      });
    },
    /* 理货完成 */
    tallyFinish() {
		this.$store.dispatch(types.SHOW_TOAST, {
		  msg: this.$t("仍有订单未理货，请完成所有订单箱号标签扫码后完成理货"),
		});
      tallyCommit({ shipmentId: this.shipmentId }).then((res) => {
        if (res) {
          uni.showModal({
			title:'完成理货成功',
          	cancelText:this.$t('好的'),
			confirmText:'返回待理货列表',
			success(re) {
				if(re.confirm){
					uni.navigateTo({
					  url: `./list`,
					});
				}
			}
          })
        }
      });
    },
    goBack() {
      uni.navigateBack();
    },
    // 转异
    turnException(order){
      this.turnExceptionOrder = order
    },
	/* 确认装柜纠错订单 */
	unloadConfirm() {
	  this.focusError = false;
	  // 扫码速度过快，可能导致取值不完整，所以延迟执行
	  setTimeout(this.unloadConfirmReal, 100);
	},
	unloadConfirmReal() {
	  this.unloadNumber = util.getQrCode(this.unloadNumber);
	  getOrderDetailByBoxNo({
	    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];
	      }else{
			  this.unloadSubNumberBegin = 1;
			  this.unloadSubNumberEnd = res.num
		  }
	      this.unloadConfirmNumber = orderNo;
	    }
	  });
	  this.focusError = true;
	},
	/* 批量扫描-读取信息 */
	batchScan() {
		  console.log(111)
	  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,
	      };
	      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 = "";
	    });
	},
	  /* 批量装柜 */
	  submitBatch() {
	    batchCreateMore({
	      orderId: this.batchOrderInfo.orderId,
	      orderNo: this.batchOrderInfo.orderNo,
	      shipmentId: this.shipmentId,
	      type: 0
	    }).then((data) => {
	      if (data) {
	        this.showMessageAndReload(this.$t("批量理货成功"));
	        this.showBatch(false);
	        this.batchOrderInfo = {};
	        this.scanNumber = "";
	      }
	    });
	    //清空密码
	    this.batchLoadPassword = "";
	  },
	/* 删除装柜 */
	unload() {
	  if (
	    this.unloadConfirmNumber &&
	    this.unloadSubNumberBegin &&
	    this.unloadSubNumberEnd
	  ) {
	    batchDeleteMore({
	      orderNo: this.unloadConfirmNumber,
	      shipmentId: this.shipmentId,
	      startNo: this.unloadSubNumberBegin,
	      endNo: this.unloadSubNumberEnd,
			type:0
	    }).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 = "";
	  }
	},
  },
  onPullDownRefresh() {
    this.getLoadDetail();
  },
  onLoad: function (option) {
    uni.setNavigationBarTitle({
      title: this.$t("理货"),
    });
    if ("id" in option) {
      this.shipmentId = parseInt(option.id);
      this.getLoadDetail();
    }
  },

  /* 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 {
  // padding-bottom: 0px;
  ::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;

    &.noPadding {
      padding: 0;
    }

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

      > view {
        flex: 1;
        word-break: break-all;
        padding-left: 4px;
      }
    }
  }
}
.search-form.round {
  ::v-deep .uni-easyinput__content {
    border-radius: 20px;
    padding-right: 10px;
    background: rgba($color: #fff, $alpha: 0.5) !important;
    border: none;
  }
}
.text-break {
  word-break: break-word;
}
</style>
