<template>
 <!--备货页面-->
  <view>
    <view class="top">
      <view class="card-style"></view>
      <uni-card>
        <view class="card-content-wrap">
          <view>
            <view>{{$t('订单号')}}</view>
            <view>{{ detail.orderNo }}</view>
          </view>
          <view>
            <view>{{$t('唛头')}}</view>
            <view>{{ detail.marks }}</view>
          </view>
          <view>
            <view>{{$t('已到箱数')}}/{{$t('总箱数')}}</view>
            <view>{{ detail.sumNum }}/{{ detail.costVO ? detail.costVO.totalNum : 0 }}</view>
          </view>
          <view>
            <view>{{$t('订单状态')}}</view>
            <view><dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="detail.status" /></view>
          </view>
          <view>
            <view>{{$t('送货日期')}}</view>
            <view>{{ detail.deliveryDate }}</view>
          </view>
          <view>
            <view>{{$t('运输方式')}}</view>
            <view><dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="detail.transportId" /></view>
          </view>
          <view>
            <view>{{$t('出货渠道')}}</view>
            <view>{{detail.channelName}}</view>
          </view>
          <view>
            <view>{{$t('可出特性')}}</view>
            <view>{{getProductAttrsByIds(detail.channelAttrId)}}</view>
          </view>
          <view>
            <view>{{$t('始发仓')}}</view>
            <view>{{ detail.logisticsInfoDto ? $l(detail.logisticsInfoDto, 'startTitle') : ''}}</view>
          </view>
          <view>
            <view>{{$t('目的仓')}}</view>
            <view>{{ detail.logisticsInfoDto ? $l(detail.logisticsInfoDto, 'destTitle') : '' }}</view>
          </view>
        </view>
      </uni-card>
    </view>
    <view class="content-wrap" v-if="detail && detail.orderItemVOList">
      <view v-for="(item, index) in detail.orderItemVOList" :key="index" class="info-wrap" style="margin-top:15px">
        <view class="info-header pos">
          <view class="header-title">{{$t('序号')}}: {{ index + 1 }}</view>
          <view class="header-status" v-if="item.warehouseInInfoVO">
            <template v-if="wareItemPackStatus(item.orderItemId) == 1">
              <button size="mini" type="warn" @click="notNeedPack(item)">{{$t('无需打包')}}</button>
              <button size="mini" type="primary" @click="pack(item)">{{$t('打包')}}</button>
            </template>
            <template v-else-if="getOrderLog(item).length > 0">
              <button size="mini" type="primary" @click="pack(item)">{{$t('修改打包')}}</button>
              <button size="mini" type="primary" @click="showHistory(item)">{{$t('打包历史')}}</button>
            </template>
            <button size="mini" type="warn" @click="rollback(item)">{{$t('并箱')}}</button>
          </view>
          <view class="tips" v-if="item.warehouseInInfoVO">请先确认货物已打包完成再并箱</view>
        </view>
        <view class="info-content">
          <view>
            <view>
              <view class="label">{{$t('品名')}}: </view>
              <view class="content">{{ item.prodTitleZh }}</view>
            </view>
            <view>
              <view class="label">{{$t('英文品名')}}: </view>
              <view class="content">{{ item.prodTitleEn }}</view>
            </view>
          </view>
          <view v-if="!item.warehouseInInfoVO">未入仓</view>
          <template v-else>
            <view>
              <view>
                <view class="label">{{$t('品牌')}}: </view>
                <view class="content">
                  <template v-if="item.brandName">{{item.brandName}}</template>
                  <dict-tag v-else :type="DICT_TYPE.ECW_IS_BRAND" :value="item.brandType"></dict-tag>
                </view>
              </view>
              <view>
                <view class="label">{{$t('箱数')}}: </view>
                <view class="content">{{ item.warehouseInInfoVO.cartonsNum }}{{$t('箱')}}</view>
              </view>
            </view>
            <view>
              <view>
                <view class="label">{{$t('体积')}}: </view>
                <view class="content">{{ item.warehouseInInfoVO.volume }}m³</view>
              </view>
              <view>
                <view class="label">{{$t('重量')}}: </view>
                <view class="content">{{ item.warehouseInInfoVO.weight }}Kg</view>
              </view>
            </view>
            <view>
              <view>
                <view class="label">{{$t('数量')}}（{{$t('个')}}）: </view>
                <view class="content">{{ item.warehouseInInfoVO.quantityAll }}</view>
              </view>
              <view>
                <view class="label">{{$t('打包状态')}}: </view>
                <view class="content">
                  <dict-tag :type="DICT_TYPE.ORDER_ITEM_PACK_STATUS" :value="wareItemPackStatus(item.orderItemId)" />
                </view>
              </view>
            </view>
            <view>
              <view>
                <view class="label">{{$t('商品特性')}}: </view>
                <view class="content">{{ getProductAttrsByIds(item.warehouseInProdAttrIds) }}</view>
              </view>
            </view>
          </template>

        </view>
        <view v-for="(ite, ind) in getOrderLog(item)" :key="ind">
          <uni-card class="info-card" v-if="orderItemList.find(v => v.orderItemId === item.orderItemId)">
            <view class="info-content">
              <view>
                <view>
                  <view class="label">{{$t('品名')}}: </view>
                  <view class="content">{{ $l(item, 'prodTitle' )}}</view>
                </view>
                <view>
                  <view class="label">{{$t('箱数')}}: </view>
                  <view class="content">{{ ite.cartonsNum }}{{ite.specificationType == 2 ? $t('整板') : $t('箱')}}</view>

                </view>
              </view>
              <view>
                <view>
                  <view class="label">{{$t('品牌')}}: </view>
                  <!-- <view class="content">{{ [$t('无牌'), $t('有牌'), $t('中性')][item.brandType] }}</view> -->
                  <view class="content">{{ item.brandName }}</view>
                </view>
                <view>
                  <view class="label">{{$t('重量')}}: </view>
                  <view class="content">{{ ite.weight }}Kg</view>
                </view>
              </view>
              <view>
                <view>
                  <view class="label">{{$t('体积')}}: </view>
                  <view class="content">{{ ite.volume }}m³</view>

                </view>
                <view>
                  <view class="label">{{$t('商品特性')}}: </view>
                  <!--
                  23-10-02
                  工单要求改成填单特性 https://zentao.test.jdshangmen.com/bug-view-4825.html#app=execution
                  工单要求入仓后显示特性 https://zentao.test.jdshangmen.com/bug-view-4824.html#app=execution
                  工单要求显示最新特性 https://zentao.test.jdshangmen.com/bug-view-4821.html#app=execution
                  -->
                  <view class="content">{{ getProductNamesByIds(item.warehouseInInfoVO ? item.warehouseInProdAttrIds : item.prodAttrIds) }}</view>
                </view>
              </view>
              <view>
                <view>
                  <view class="label">{{$t('尺寸')}}: </view>
                  <view class="content">{{ ite.boxGauge }}</view>
                </view>
                <view>
                  <view class="label">{{$t('数量')}}: </view>
                  <view class="content">{{ ite.quantityAll }}</view>
                </view>
              </view>
            </view>
            <view class="card-btn">
              <text style="color: #007aff" @click="showPictrues(item, ind)">查看入仓影像</text>
              <view>
                <button class="mini-btn" type="primary" size="mini"  @tap="pack(item, ind)">{{$t('修改')}}</button>
                <button class="mini-btn" type="default" size="mini" @tap="deleteClick(ite.id)">{{$t('删除')}}</button>
              </view>
            </view>
          </uni-card>
        </view>
      </view>
    </view>
    <view class="special" v-if="specialNeeds.length">
      <view class="section-title">{{$t('特殊需求')}}</view>
      <view v-for="item in specialNeeds" :key="item.text">
        {{item.text}} : {{item.transFee}}{{showCurrencyName(item.transCurrency)}}
      </view>
    </view>
    <view class="stat">
      <view class="section-title">{{$t('小计')}}</view>
      <view class="" v-if="detail.costVO">
        {{$t('下单统计')}}：
        {{ $t(`{num}箱 {weight}Kg {volume}m³ {quantity}个`, {
          num: statistics.sumNumInput,
          weight: statistics.sumWeightInput,
          volume: statistics.sumVolumeInput,
          quantity: statistics.sumQuantityInput
        }) }}
      </view>
      <view class="" v-if="firstWarehouseIn">
        {{$t('入仓统计')}}：
        {{ $t(`{num}箱 {weight}Kg {volume}m³ {quantity}个`, {
        num: statistics.sumCartonsNumFinishedWarehouseIn,
        weight: statistics.sumWeightFinishedWarehouseIn,
        volume: statistics.sumVolumeFinishedWarehouseIn,
        quantity: statistics.sumQuantityAllFinishedWarehouseIn
      }) }}
      </view>
      <view class="">
        {{$t('打包前统计')}}：
        {{ $t(`{num}箱 {weight}Kg {volume}m³ {quantity}个`, {
          num: statistics.sumCartonsNumPrevPacked,
          weight: statistics.sumWeightPrevPacked,
          volume: statistics.sumVolumePrevPacked,
          quantity: statistics.sumQuantityAllPrevPacked
        }) }}
      </view>
      <view class="">
        {{$t('打包后统计')}}：
        {{ $t(`{num}箱 {weight}Kg {volume}m³ {quantity}个`, {
          num: statistics.sumNum,
          weight: statistics.sumWeight,
          volume: statistics.sumVolume,
          quantity: statistics.sumQuantity
        }) }}
      </view>
    </view>
    <view class="actions flex">
      <button type="info" @click="showNewProductDialog=true">{{$t('添加新商品')}}</button>
      <button type="warn" @click="showExceptionDialog">{{$t('转异')}}</button>
      <button type="primary" @click="submit">{{$t('完成备货')}}</button>
    </view>
    <pack
      v-if="curPackItem"
      ref="pack"
      :item="curPackItem"
      :order="detail"
      :attr="curPackAttr"
      :usage="curPackUsage"
      :warehouseIn="curPackItemWarehouseInList"
      :warehouseInIndex="curPackItemIndex"
      @close="curPackItem=null"
      @success="onPackSuccess"></pack>

    <exception v-if="showException" @close="showException=false" v-bind="showException"></exception>
    <new-product v-if="showNewProductDialog"
                 @close="showNewProductDialog=false"
                 @success="onPackSuccess"
                 :detail="detail"></new-product>
  </view>
</template>

<script>
import {getProductAttrList} from "@/api/system";
import {getOrder, getOrderWarehouseIn} from "@/pages/tally/api";
import {confirm, msg} from "@/util/tools";
import {
  getOrderSpecialNeed,
  noNeedPack,
  finishStock,
  getFirstWarehouseIn,
  finishPack,
  getPackStatistics
} from "@/pages/stocking/api";
import Pack from "@/pages/stocking/components/pack";
import {
  deleteWarehouseInRecord,
  getCurrencyList
} from "@/pages/warehousing/api";
import Exception from './components/exception'
import {alert} from "@/util/tools";
import { DICT_TYPE } from "@/util/dict";
import NewProduct from "@/pages/stocking/components/NewProduct.vue";
import { rollbackDelete } from "@/pages/warehousingAir/api";
export default {
  name: "stocking",
  components: { NewProduct, Pack, Exception},
  data(){
    return {
      // 是否显示新品弹层
      showNewProductDialog: false,
      // 订单ID
      orderId: null,
      productAttrList:[],
      // 订单信息
      detail: {},
      // 入仓信息
      orderItemList: [],
      // 当前打包的商品
      curPackItem: null,
      // 当前打包商品的入仓记录
      curPackItemWarehouseInList: [],
      // 当前打包的商品特性
      curPackAttr: null,
      // 当前打包的用途
      curPackUsage: null,
      // 当前修改的入仓记录索引
      curPackItemIndex: -1,
      // 特需
      specialNeeds: [],
      // 货币
      currencyList: [],
      // 是否显示转异
      showException: false,
      // 首次入仓数据
      firstWarehouseIn: null,
      // 统计
      statistics: {}
    }
  },
  computed:{
    DICT_TYPE() {
      return DICT_TYPE
    },
    // 显示货币名称
    showCurrencyName(){
      return currency => this.$l(this.currencyList.find(item => item.id === currency), 'title')
    },
    // 根据orderItemId获取入仓item
    wareItem(){
      return orderItemId => {
        return this.orderItemList.find(item => item.orderItemId === orderItemId)
      }
    },
    // 获取打包状态
    wareItemPackStatus(){
      return orderItemId => {
        return this.wareItem(orderItemId)?.packStatus
      }
    },
    isChinese(){
      return uni.getLocale() === 'zh-Hans'
    },
  },
  onLoad(options){
	  console.log({options})
    uni.setNavigationBarTitle({title: this.$t('备货')})

    getProductAttrList().then(data => {
      this.productAttrList = data
    })
	  this.orderId = options.orderId

    this.loadOrder()

    getOrderSpecialNeed(this.orderId).then(data => {
      const dictList = this.getDictDatas(this.DICT_TYPE.ORDER_SPECIAL_NEEDS)
      this.specialNeeds = data.map(item => {
        item.text = this.$l(dictList.find(dict => item.advanceType === dict.value), 'label')
        return item
      })
    })
    getCurrencyList({}).then(data => {
      this.currencyList = data
    })
  },
  methods:{
    getStatistics() {
      getPackStatistics(this.orderId).then(data => {
        this.statistics = data
      })
    },
    loadOrder(){
      getOrder(this.orderId).then(data => {
        this.detail = data
      })
      this.getStatistics()

      // 获取货物入仓详情
      getOrderWarehouseIn(this.orderId).then(data => this.orderItemList = data)
      // 获取首次入仓数据
      getFirstWarehouseIn(this.orderId).then(data => {
        this.firstWarehouseIn= data
      })
    },
    // 获取商品特性文本
    getProductAttrsByIds(ids){
      if(!ids) return ''
      const result = []
      ids.split(',').forEach(e => {
        this.productAttrList.forEach(f => {
          if (parseInt(e) === f.id) {
            result.push(this.$l(f, 'attrName'))
          }
        })
      })
      return result.join('、')
    },
    // 获取用途文本
    getProductUsageByIds(ids){
      if(!ids) return ''
      const result = []
      ids.split(',').forEach(e => {
        this.getDictDatas(this.DICT_TYPE.WAREHOUSING_RECORD_DETAIL_USAGE).forEach(f => {
          if (e === f.value) {
            result.push(this.$l(f, 'label'))
          }
        })
      })
      return result.join('、')
    },
    // 无需打包
    notNeedPack(item){
        confirm(this.$t('确认无需打包？'), this.$t('提示')).then(() => {
          noNeedPack(item.orderItemId).then(() => {
            this.loadOrder()
          })
        })
    },
    // 打包
    pack(item, index=-1){
      this.curPackItem = item
      this.curPackAttr = this.getProductAttrsByIds(item.warehouseInProdAttrIds)
      this.curPackUsage = this.getProductUsageByIds(item.usageIds)
      this.curPackItemWarehouseInList = this.wareItem(item.orderItemId)
      this.curPackItemIndex = index
    },
    // 打包历史
    showHistory(item){
      // 通过全局变量来讲商品项传递过去
      getApp().globalTempData = { ...item, packStatus: this.wareItemPackStatus(item.orderItemId) }
      const attr = this.getProductAttrsByIds(item.warehouseInProdAttrIds)
      const usage = this.getProductUsageByIds(item.usageIds)
      uni.navigateTo({
        url: `/pages/stocking/history?globalVarField=globalTempData&orderId=${item.orderId}&orderItemId=${item.orderItemId}&attr=${attr}&usage=${usage}`
      })
    },
    // 打包的储位选择回调，因为是调用上一页页面的方法，所以要通过页面方法中转调用组件方法
    setLocation(locationList, extra){
      if(!this.$refs.pack){
        return msg(this.$t('非打包操作'))
      }
      this.$refs.pack.setLocation(locationList, extra)
    },
    // 完成备货
    submit(){
      // 判断是否有未打包的商品
      let unpackProds = []
      this.orderItemList.forEach(item => {
        if(item.orderWarehouseInBackItemDoList?.length && item.packStatus == 1){
          unpackProds.push(this.$l(item, 'prodTitle'))
        }
      })
      if(unpackProds.length){
        return alert(`商品${unpackProds.join(',')}未完成打包,无法完成备货`, this.$t('提示'))
      }
      let form = { }
      form.orderId = this.detail.orderId
      form.manualExceptionType = ''
      // 以下两项数据待完善，在转异弹层中也是待处理
      form.sumVolume = this.detail.sumVolume
      form.sumWeight = this.detail.sumWeight

      finishStock(form).then(res => {
        return alert(this.$t('操作成功'))
      }).then(() => {
        uni.navigateBack()
      })
    },
    // 从入仓记录中统计数据
    calcTotal(field){

    },
    // 打开转异弹层
    showExceptionDialog(){
      this.showException = {
        detail: this.detail,
        sumVolume: this.detail.sumVolume,
        sumWeight: this.detail.sumWeight,
      }
    },
    // 打包成功
    onPackSuccess(){
      this.curPackItem = null
      this.curPackItemIndex = -1
      this.showNewProductDialog = false
      this.loadOrder()
    },
    getOrderLog(item){
      return this.orderItemList.length > 0 ? this.orderItemList.find(v => v.orderItemId === item.orderItemId)?.orderWarehouseInBackItemDoList : []
    },
    getProductNamesByIds(ids){
      const result = []
      ids?.split(',').forEach(e => {
        this.productAttrList.forEach(f => {
          if (parseInt(e) === f.id) {
            result.push(this.isChinese ? f.attrName : f.attrNameEn)
          }
        })
      })
      return result.join('、')
    },
    deleteClick(id) {
      uni.showModal({
        title: this.$t('是否删除'),
        content: this.$t('删除后不可恢复，确定是否要删除该入仓信息')+'?',
        success: (data) => {
          if (data.confirm) {
            deleteWarehouseInRecord(id).then(() => {
              this.loadOrder()
            })
          }
        }
      })
    },
    // 查看入仓影响
    showPictrues(item, index){
      console.log('查看素材')
      if(!item.pictureUrls || !item.pictureUrls.length){
        return uni.showModal({
          title:this.$t('提示'),
          content: this.$t('暂无可查看内容'),
          showCancel:false,
        })
      }
      uni.MEDIA_LIST = item.pictureUrls
      uni.navigateTo({
        url: '/pages/utils/media'
      })
    },
    // 并箱
    rollback(item){
      console.log(item)
      confirm(this.$t('{prod}并箱后不可恢复，是否确认并箱?', {prod: this.$l(item, 'prodTitle')}), this.$t('提示')).then(() => {
        return rollbackDelete({
          orderId: this.orderId,
          orderItemId: item.orderItemId,
          isPackagingRollback: true
        })
      }).then(res => {
        return alert(this.$t('并箱成功'), this.$t('提示'))
      }).then(() => {
        this.loadOrder()
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import "./styles/detail.scss";
page{
  background: #ffffff;
  .pos{
    position: relative;
    height: 50px;
    .tips{
      position: absolute;
      right: 0;
      bottom: 0;
      background: #000;
      color: #fff;
      font-size: 12px;
      height: 18px;
      line-height: 18px;
      padding: 0 5px;
      border-radius: 2px;
      &:after{
        content: '';
        width: 0;
        height: 0;
        border: 5px solid transparent;
        border-bottom-color: #000;
        position: absolute;
        top: -10px;
        right: 20px;
      }
    }
  }
}
.top{
  padding: 20rpx;
  .card-style {
    height: 16px;
    background: #1f4bbe;
    border: 4px solid #3b70ff;
    border-radius: 20px;
    margin-top: 16px;
  }
  .card-content-wrap {
    > view {
      display: flex;
      padding: 10px 0;
      > view + view {
        margin-left: auto;

      }
    }
    > view + view {
      border-top: 0.5px solid #eee;
    }
  }
  ::v-deep .uni-card {
    margin: -8px 4px 0 !important;
  }
}
.section-title{
  font-weight: bold;
  font-size: 30rpx;
  margin-bottom: 20rpx;
}
.special, .stat, .actions{
  padding: 20rpx 30rpx;

}

</style>
