<template>
  <view style="background: #fff; min-height: calc(100vh - 44px)">
    <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" v-for="(order, key) in v.sectionOrderList" :key="key">
                <view class="flex text-center">
                  <view class="text-break text-blue" style="width:20%;" @tap="showOrderDetail(true, order.orderId)">
                    <view>{{ 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 style="color: red"><dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="order.customsType" /></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 style="color:blue;fontWeight:bold;">
                      {{ order.multiSpecification === true ? ('('+$t('多规格')+')') : ''}}
                    </view>
                  </view>
                  <view style="width:15%;">{{ order.positionNo ? order.positionNo.split(',').join(', ') : '' }}</view>
                  <view class="flex justify-center" style="width:20%;">
                    <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>
              </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>
        </uni-card>

        <view class="padding-xl">
          <block>
            <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>

    <!-- 订单详情弹窗 -->
    <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('备案')}}：
                  <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>

    <warehouse-detail ref="warehouseDetail" :orderId="orderId" :orderItemId="showWarehouseInItemId" />

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

</template>

<script>
import * as types from "../../store/mutations-types.js";
import mixins from "../../mixins/mixin.js";
import {
  tallyList,
  tallyRemove,
  tallyLocationUpdate,
  tallyCommit,
  listByOrderId,
} from "./api";
import { getOrderDetail, getLoadingDetail } from "../loading/api";
import WarehouseDetail from "./warehouseDetail.vue";

export default {
  name: "tally-detail",
  components: { WarehouseDetail },
  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: {},
    };
  },
  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: {
	// 从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(',')
	},
    // 显示入仓记录
    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;
    },
    /* 折叠 */
    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;
    },
    /* 读取理货详情 */
    getLoadDetail() {
      if (this.shipmentId) {
        // 获取出货信息
        getLoadingDetail({ shipmentId: this.shipmentId }).then((res) => {
          this.loadData.boxInfo = res.boxInfo;
        });
        tallyList({ shipmentId: this.shipmentId }).then((res) => {
          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();
        });
      }
    },
    /* 二次确认移出 */
    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();
      });
    },
    /* 理货完成 */
    tallyFinish() {
      tallyCommit({ shipmentId: this.shipmentId }).then((res) => {
        if (res) {
          uni.navigateBack();
        }
      });
    },
    goBack() {
      uni.navigateBack();
    },
  },
  onPullDownRefresh() {
    this.getLoadDetail();
  },
  onLoad: function (option) {
    uni.setNavigationBarTitle({
      title: this.$t("理货"),
    });
    if ("id" in option) {
      this.shipmentId = 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>
