<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>
          <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:12%;">{{$t('体积') + "(m³)"}}</view>
                <view style="width:12%;">{{$t('重量') + "(kg)"}}</view>
                <view style="width:12%;">{{$t('箱数')}}</view>
                <view style="width:12%;">{{$t('储位')}}</view>
                <view  style="width:12%;">{{$t('计划')}}/{{$t('实装')}}</view>
                <view style="width:20%;">{{$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 v.sectionOrderList" :key="key">
                  <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 v-if="order.goodsList.some(ele => ele.brandType && [$t('无牌'), $t('有牌'), $t('中性')][ele.brandType] !== $t('无牌'))" style="color:red;fontWeight:bold;">{{ $t('有牌') }}</view> -->
                    <!-- 特性 -->
                    <!-- <view style="color:red;fontWeight:bold;">{{ getProductAttrsByIds(uniqueProductAttrs(order.goodsList, 'warehouseInProdAttrIds')) }}</view> -->
                    <!-- 报关方式 -->
                    <view style="color: red;fontWeight:bold;" 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 uniqueArr(order.units)" :key="index">
                        <dict-tag :type="DICT_TYPE.ECW_PACKAGING_TYPE" :value="unit" />{{ index!== uniqueArr(order.units).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;" @tap="showMixOrder(order)">{{$t('混箱')}}</view>
                  </view>
                  <view style="width:12%;">{{ order.volume | toFixed }}</view>
                  <view style="width:12%;">{{ order.weight | toFixed }}</view>
                  <view class="text-break" style="width:15%;">
                  <view class="text-break text-blue" @tap="showGoodsDetail(true, order)">{{ order.num }}箱</view>
                  <view style="color:blue;fontWeight:bold;">
                    {{ order.multiSpecification === true ? ('('+$t('多规格')+')') : ''}}
                  </view>
                </view>
                <view style="width:12%;">{{ order.positionNo ? order.positionNo.split(',').join(', ') : '' }}</view>
                  <view style="width:12%;" @click="showUnload(true, order.orderId)">
                  <text style="width:12%;">{{ order.num }}</text>/<text :class="actualClass(order.num, order.installNum)">{{ order.installNum }}</text>
                  </view>
                  <view class="flex justify-center" style="width:20%;">
                    <view class="text-green text-bold" v-if="order.installNum == 0" @click.stop="moveOut(order)">
                      {{$t('移出')}}
                    </view>
                    <view class="text-red text-bold" v-if="order.installNum != 0 && order.num > order.installNum" @click.stop="showSplit(true, 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">
            <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>
          <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>
        </uni-card>

        <!-- 装柜影像 -->
        <view v-if="getStatus() === 3">
          <view class="detail-title">
            <uni-title type="h3" :title="$t('装柜影像')"></uni-title>
          </view>
          <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%">
                  <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 class="padding-xl">
          <block v-if="getStatus() === 1">
            <view class="flex">
              <view class="flex-sub" style="padding-right: 10px;">
                <button class="cu-btn block bg-blue margin-tb-sm lg" @click="toPatch()">{{$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="">
              <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" @click="next">{{$t('下一步')}}</button>
            </view>
          </block>
          <block v-if="getStatus() === 2">
            <button class="cu-btn block bg-green margin-tb-sm lg" :disabled="true">
              {{$t('审核中')}}
            </button>
          </block>
          <block v-if="getStatus() === 3">
            <button class="cu-btn block bg-green margin-tb-sm lg" @click="showConfirmClosing">
              {{$t('确认封柜')}}
            </button>
          </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 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="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>

    <warehouse-list ref="warehouseList" />
    <mix-order-list ref="mixOrderList" />

    <!-- 未装弹窗 -->
    <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 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="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 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>

    <!-- 拆单 -->
    <split-com ref="splitCom" :shipmentId='shipmentId' @reload="reload"></split-com>

    <!-- 确认封柜弹窗 -->
    <view class="cu-modal" :class="confirmCloseModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-form-group">
          <text class="title">{{$t('装柜时间')}}:</text>
          <uni-datetime-picker type="datetime" :border=false :value="confirmCloseCloseBoxTime" @change="(val)=>selectDate('confirmCloseCloseBoxTime',val)" :placeholder="$t('请选择')">
          </uni-datetime-picker>
        </view>
        <view class="cu-form-group">
          <text class="title">{{$t('出仓时间')}}:</text>
          <uni-datetime-picker type="datetime" :border=false :value="confirmLeaveStoreTime" @change="(val)=>selectDate('confirmLeaveStoreTime',val)" :placeholder="$t('请选择')">
          </uni-datetime-picker>
        </view>
        <view class="cu-bar bg-white justify-end top-line">
          <view class="action">
            <button class="cu-btn bg-green" @tap="submitConfirmClosing">{{$t('确认')}}</button>
            <button class="cu-btn bg-grey margin-left" @tap="showConfirmClosing(false)">{{$t('取消')}}</button>
          </view>
        </view>
      </view>
    </view>

    <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="moveOut2(2)">{{$t('确定移出')}}</button>
          <button class="mini-btn" type="primary" size="mini" @tap="moveOut2(1)">{{$t('仅移出当前订单')}}</button>
          <button class="mini-btn" type="default" size="mini" @tap="$refs.popup.close()">{{$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 {
  getLoadingDetailV2,
  getOrderDetailAdmin,
  orderTagList,
  getOrderDetailByBoxNo,
  batchLoadGoods,
  unloadGoods,
  moveOutLoadGoods,
  loadGoods,
  createCabinet,
  listByOrderId,
} from "./api";
import splitCom from "./components/split-com.vue";
import OrderDetailModal from "@/components/order-detail-modal/index.vue"
import WarehouseList from "@/pages/tally/warehouseList.vue";
import MixOrderList from "@/pages/tally/mixOrderList.vue";
import { updateImg, getProductAttrList } from "@/api/system";
import dayjs from "dayjs";

export default {
  name: "loading-detail",
  components: {
    splitCom,
    OrderDetailModal,
    MixOrderList,
    WarehouseList
  },
  mixins: [mixins],
  data() {
    return {
      movingOrderId: undefined,
      popupMessage: '',
      /* 出货ID */
      shipmentId: null,
      /* 自编号 */
      keyword: "",
      /* 图片 */
      imageList: [],
      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: "",
      unloadSubNumberBegin: "",
      unloadSubNumberEnd: "",
      /* 批量密码 */
      batchPwModal: false,
      batchLoadPassword: "",
      /* 扫描装柜 */
      loadNumber: "",
      /* 高亮 */
      heightLightId: "",
      onHideFlag: false,
      /* 确认封柜 */
      confirmCloseModal: false, // 确认封柜弹窗显示
      confirmCloseCloseBoxTime: "", //确认封柜弹窗表单-装柜时间
      confirmLeaveStoreTime: "", //确认封柜弹窗表单-出仓时间,
      isFocus: false,
      focusStart: false,
      focusError: false,
      // 货物详情
      goodsModal: false,
      // 当前行
      currRow: {},
      productAttrList:[],
    };
  },
  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: {
    // 从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(',')
    },
    delimage(index) {
      this.imageList.splice(index, 1);
    },
    getStatus() {
      /**
       * 装柜状态：41、未装柜；42、装柜中；43、已装柜、待封柜；44、封柜审核中；45、封柜审核失败；46、封柜审核成功；47、已封柜，待出仓
       */
      const { boxInfo } = this.loadData;
      const ldStatus = boxInfo.ldStatus;
      switch (true) {
        case [41, 42, 43, 45].includes(ldStatus):
          return 1;
        case [44].includes(ldStatus):
          return 2;
        case [46].includes(ldStatus):
          return 3;
      }
      return 3;
    },
    /* 视频/图片 */
    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.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;
          // 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();
    },
    /* 二次确认移出订单 */
    moveOut2(deleteType) {
      moveOutLoadGoods({
        shipmentId: this.shipmentId,
        orderId: this.movingOrderId,
        deleteType
      }).then((data) => {
        if (data) {
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: this.$t("移出成功"),
          });
          this.$refs.popup.close()
          setTimeout(() => {
            this.getLoadDetail();
          }, 1000);
        }
      })
    },
    /* 移出订单 */
    moveOut(row) {
      this.movingOrderId = row.orderId
      let _content = this.$t("确认移出订单") + row.orderNo + "?";
      uni.showModal({
        content: _content,
        success: (e) => {
          if (e.confirm) {
            moveOutLoadGoods({
              shipmentId: this.shipmentId,
              orderId: row.orderId,
            }).then((data) => {
              if (data === true) {
                this.$store.dispatch(types.SHOW_TOAST, {
                  msg: this.$t("移出成功"),
                });
                setTimeout(() => {
                  this.getLoadDetail();
                }, 1000);
              } else {
                this.popupMessage = data.msg.replace(/<br>/g, '') + this.$t('，是否需要一起移出?')
                this.$refs.popup.open()
              }
            });
          }
        },
      });
    },
    /* 显示未装 */
    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);
    },
    /* 显示拆单窗口 */
    showSplit(show, row) {

      if (
        this.loadData.cabinetSplitInfo &&
        this.loadData.cabinetSplitInfo.approvalStatus == 1
      ) {
        return uni.showToast({
          title: this.$t("装柜拆单审核中，请耐心等待拆单成功后操作"),
          icon: "none",
        });
      }
      // 可拆数量 = 预装数量 - 已装数量
      const canSplitNum = row.num - row.installNum
      // 跳转到退场的拆单页面操作，弹出窗口不是最新的，且页面内容较多不适合弹层操作
      return uni.navigateTo({
        url: `../ExitWarehouse/split?fr=loading&orderId=${row.orderId}&canSplitNum=${canSplitNum}&shipmentId=${this.shipmentId}`
      })
      // this.$refs.splitCom.showSplit(show, row);
    },
    /* 跳转到关联单 */
    relatedClick(orderNo) {
      const { boxInfo } = this.loadData;
      uni.navigateTo({
        url: `../tally/relatedOrder?orderId=${orderNo}&selfNo=${boxInfo.selfNo}`,
      });
    },
    /* 跳转到补单 */
    toPatch() {
      const { boxInfo } = this.loadData;
      uni.navigateTo({
        url: `./patch?id=${this.shipmentId}&destWarehouseId=${boxInfo.destWarehouseId}`,
      });
    },
    /* 显示批量输入 */
    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,
          };
          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 = "";
    },
    // 显示混箱明细
    showMixOrder(row) {
      this.orderId = row.orderId;
      this.$refs.mixOrderList.showDetail(row);
    },
    // 显示入仓记录
    showWarehouseLogs(row) {
      this.orderId = row.orderId;
      this.$refs.warehouseList.showDetail(row);
    },
    // 货物详情
    showGoodsDetail(show, row) {
      if (show) this.currRow = row;
      this.goodsModal = show;
    },
    /* 过滤包装类型 */
    uniqueArr(arr) {
      if (!arr || !arr.length) return
      return arr.split(',').filter((obj) =>
      !['1', '2'].includes(obj));
    },
    // 过滤商品特性
    uniqueProductAttrs(arr, field) {
      let uniqueValues = [...new Set(arr.map(item => item[field].split(',')).flat())];
      return uniqueValues.join(',')
    },
    // 获取商品特性文本
    getProductAttrsByIds(ids){
      if(!ids) return ''
      const result = []
      ids.split(',').forEach(e => {
        this.productAttrList.forEach(f => {
          if (parseInt(e) === f.id && this.$l(f, 'attrName') !== '普货') {
            result.push(this.$l(f, 'attrName'))
          }
        })
      })
      console.log('result', result)
      return result.join('、')
    },
    /* 显示订单详情 */
    showOrderDetail(show, id) {
      this.orderDetailModal = show;
      console.log('OrderDetailModal', this.OrderDetailModal)
      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;
          loadGoods({
            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);
      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];
          }
          this.unloadConfirmNumber = orderNo;
        }
      });
      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,
      };
      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;
    },
    /* 读取预装信息 */
    getLoadDetail() {
      if (this.shipmentId) {
        getLoadingDetailV2({
          shipmentId: this.shipmentId,
        }).then((data) => {
          const { loadDetail } = data;
          let newLoadDetail = [];
          loadDetail.forEach((item) => {
            if (item.sectionOrderList && item.sectionOrderList.length) {
              newLoadDetail.push({
                ...item,
                secName: item.sectionOrderList[0].sectionName,
              });
            }
          });

          this.loadData = {
            ...data,
            loadDetail: newLoadDetail,
          };
          this.getSecTotal();
          const { cabinetInfo } = data;
          if (cabinetInfo && cabinetInfo.ldPictures) {
            try {
              this.imageList = JSON.parse(cabinetInfo.ldPictures);
            } catch (error) {
              this.imageList = [];
            }
          }
          uni.stopPullDownRefresh();
        });
      }
    },
    /* 下一步 */
    next() {
      uni.navigateTo({
        url: `./loading-confirm?id=${this.shipmentId}`,
      });
    },
    /* 确认批量扫描 */
    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() {
      batchLoadGoods({
        boxNum: this.batchOrderInfo.num,
        orderId: this.batchOrderInfo.orderId,
        orderNo: this.batchOrderInfo.orderNo,
        shipmentId: this.shipmentId,
        pwd: this.batchLoadPassword,
        checkPwd: 1,
      }).then((data) => {
        if (data) {
          this.showMessageAndReload(this.$t("批量装柜成功"));
          this.showBatchPassword(false);
          this.showBatch(false);
          this.batchOrderInfo = {};
          this.scanNumber = "";
        }
      });
      //清空密码
      this.batchLoadPassword = "";
    },
    /* 确认封柜弹窗-显示/隐藏 */
    showConfirmClosing(v) {
      this.confirmCloseModal = v;
    },
    /* 确认封柜-时间选择 */
    selectDate(key, val) {
      this[key] = val;
    },
    //确认封柜提交
    submitConfirmClosing() {
      if (!this.confirmCloseCloseBoxTime) {
        this.$store.dispatch(types.SHOW_TOAST, {
          msg: this.$t("请选择装柜时间"),
        });
      }
      if (!this.confirmLeaveStoreTime) {
        this.$store.dispatch(types.SHOW_TOAST, {
          msg: this.$t("请选择出仓时间"),
        });
      }
      createCabinet({
        ldBoxTime: dayjs(this.confirmCloseCloseBoxTime).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        ldOutWarehouseTime: dayjs(this.confirmLeaveStoreTime).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        operateType: 2,
        ldPictures: JSON.stringify(this.imageList),
        shipmentId: this.shipmentId,
      })
        .then((data) => {
          this.showConfirmClosing(false);
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: this.$t("操作成功"),
            onHide() {
              setTimeout(() => {
                uni.redirectTo({
                  url: "./list",
                });
              }, 1500);
            },
          });
        })
        .catch((e) => {
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: e.msg,
          });
        });
    },
  },
  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; //确认封柜弹窗表单-出仓时间

    getProductAttrList().then(data => {
      this.productAttrList = data
    })
  },
  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);
}
.text-break {
  word-break: break-word;
}
</style>
