<template>
<!--打包历史-->
  <view>

    <view class="content-wrap">
      <view class="section-title">
        {{$t('入仓数据')}}
      </view>
      <view class="info-wrap">
        <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>
            <view>
              <view class="label">{{$t('品牌')}}: </view>
              <view class="content">{{ [$t('无牌'), $t('有牌'), $t('中性')][item.brandType] }}</view>
            </view>
            <view>
              <view class="label">{{$t('箱数')}}: </view>
              <view class="content">{{ item.num }}{{$t('箱')}}</view>
            </view>
          </view>
          <view>
            <view>
              <view class="label">{{$t('体积')}}: </view>
              <view class="content">{{ warehouseInData.volume }}m³</view>
            </view>
            <view>
              <view class="label">{{$t('重量')}}: </view>
              <view class="content">{{ warehouseInData.weight }}Kg</view>
            </view>
          </view>
          <view>
            <view>
              <view class="label">{{$t('数量')}}（{{$t('个')}}）: </view>
              <view class="content">{{ warehouseInData.quantityAll }}</view>
            </view>
            <view>
              <view class="label">{{$t('打包状态')}}: </view>
              <view class="content">
                <dict-tag :type="DICT_TYPE.ORDER_ITEM_PACK_STATUS" :value="item.packStatus" />
              </view>
            </view>
          </view>
          <view>
            <view>
              <view class="label">{{$t('商品特性')}}: </view>
              <view class="content">{{ attr }}</view>
            </view>
            <view>
              <view class="label">{{$t('用途')}}: </view>
              <view class="content">{{ usage }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!--列表-->
    <view class="list" v-if="!showHistoryDetail">
      <view class="item" v-for="(item, index) in list" :key="index">
        <view>{{index+1}}、{{$t('打包人')}}：{{item.creatorName}}，{{$t('打包时间')}}：{{item.createTime|parseTime(true)}}</view>
        <view class="flex justify-end action">
          <button v-if="!item.isNoNeedToPack" type="primary" size="mini" @click="showDetail(index)">{{$t('查看详情')}}</button>
          <button v-else type="primary" size="mini" disabled>{{$t('无需打包')}}</button>
        </view>
      </view>
    </view>
    <!--详情-->
    <view v-else class="detail">
      <view class="section-title">{{$t('打包前入仓记录')}}</view>
      <uni-card class="add-popup-card" v-for="(item, index) in before" :key="`before${index}`">
        <view class="card-row">
          <uni-easyinput disabled v-model="item.cartonsNum" type="number" :placeholder="$t('箱数')" :clearable="false"/>
          <!--<switch disabled :checked="item.specificationType === 1" @change="switchChange(item, index)" />-->
          <dict-tag :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" :value="item.specificationType + ''"/>
          <uni-easyinput disabled v-model="item.weight" type="number" :placeholder="$t('重量')" :clearable="false"/>
          <text>KG</text>
          <uni-easyinput disabled v-model="item.quantityAll" type="number" :placeholder="$t('个数')" :clearable="false"/>
          <text>{{$t('个')}}</text>
        </view>
        <view class="card-row">
          <uni-easyinput disabled v-model="item.c" type="number" :placeholder="$t('长')" :clearable="false"/>
          <text>*</text>
          <uni-easyinput disabled v-model="item.k" type="number" :placeholder="$t('宽')" :clearable="false"/>
          <text>*</text>
          <uni-easyinput disabled v-model="item.g" type="number" :placeholder="$t('高')" :clearable="false"/>
          <text>=</text>
          <uni-easyinput disabled v-model="item.volume" type="number" placeholder="" :clearable="false" />
          <text>CBM</text>
        </view>
        <!--<view class="card-row cu-form-group">
          <view class="title">{{$t('包装类型')}}</view>
          <picker mode="selector" :range="unitRange" range-key="text" @change="handleUnitChange($event, index)">
            <view class="label">{{item.unit ? showUniLabel(item.unit) : $t('请选择')}}</view>
          </picker>
        </view>

        <view class="cu-form-group">
          <view class="title">{{$t('储位')}}</view>
          <view class="content" @tap="toLocation(index)" style="flex:1;justify-content: flex-end;">
            {{ item.orderLocationCreateReqVOList && item.orderLocationCreateReqVOList.length ? item.orderLocationCreateReqVOList.map(v => v.code ||  v.areaName + (v.locationName || '')).join(',') : '' }}
            <uni-icons type="right" size="16"></uni-icons>
          </view>
        </view>-->
      </uni-card>
      <view class="section-title">{{$t('打包前影像')}}</view>
      <media-list :value="beforePictureUrls" readonly></media-list>

      <view class="section-title" style="margin-top: 15px">{{$t('打包后入仓记录')}}</view>
      <uni-card class="add-popup-card" v-for="(item, index) in after" :key="'after' + index">
        <view class="card-row">
          <uni-easyinput disabled v-model="item.cartonsNum" type="number" :placeholder="$t('箱数')" :clearable="false"/>
          <!--<switch disabled :checked="item.specificationType === 1" @change="switchChange(item, index)" />-->
          <dict-tag :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" :value="item.specificationType + ''"/>
          <uni-easyinput disabled v-model="item.weight" type="number" :placeholder="$t('重量')" :clearable="false"/>
          <text>KG</text>
          <uni-easyinput disabled v-model="item.quantityAll" type="number" :placeholder="$t('个数')" :clearable="false"/>
          <text>{{$t('个')}}</text>
        </view>
        <view class="card-row">
          <uni-easyinput disabled v-model="item.c" type="number" :placeholder="$t('长')" :clearable="false"/>
          <text>*</text>
          <uni-easyinput disabled v-model="item.k" type="number" :placeholder="$t('宽')" :clearable="false"/>
          <text>*</text>
          <uni-easyinput disabled v-model="item.g" type="number" :placeholder="$t('高')" :clearable="false"/>
          <text>=</text>
          <uni-easyinput disabled v-model="item.volume" type="number" placeholder="" :clearable="false" />
          <text>CBM</text>
        </view>
      </uni-card>
      <view class="section-title">{{$t('打包后影像')}}</view>
      <media-list :value="afterPictureUrls" readonly></media-list>

      <view class="section-title" style="margin-top:15px">{{$t('打包数据')}}</view>
      <view class="pack-data">
        <view>{{$t('打包后箱数')}}：{{ packData.cartonsNum }}{{$t('箱')}}</view>
        <view>{{$t('打包后体积')}}：{{ packData.volume}}m³</view>
        <view>{{$t('打包后重量')}}：{{packData.weight}}kg</view>
        <view>{{$t('打包后数量')}}：{{packData.quantityAll}}</view>
        <view>{{$t('打包人')}}：{{showHistoryDetail.creatorName}} {{$t("打包时间")}}：{{showHistoryDetail.createTime|parseTime(true)}}</view>
      </view>
    </view>

  </view>
</template>

<script>
import {getPackRecord} from "@/pages/stocking/api";
import util from "@/util/util.js";
import {alert} from '@/util/tools'
import {getOrderWarehouseIn} from "@/pages/warehousing/api";
import Decimal from "decimal.js";
import MediaList from "@/pages/utils/components/MediaList.vue";
export default {
  name: "history",
  components: { MediaList },
  filters: {
    parseTime: util.formatDate
  },
  data(){
    return {
      // 商品项
      item: {},
      // 商品特性
      attr: '',
      // 用途
      usage: '',
      // 记录列表
      list: [],
      // 是否显示详情
      showHistoryDetail: false,
      // 详情的入仓前记录
      before: [],
      beforePictureUrls: [],
      // 详情的入仓后记录
      after:[],
      afterPictureUrls: []
    }
  },
  computed:{
    packData(){
      let cartonsNum = new Decimal(0),
          volume = new Decimal(0),
          weight = new Decimal(0),
          quantityAll = new Decimal(0)
      this.after.forEach(item => {
        cartonsNum = cartonsNum.plus(item.cartonsNum || 0)
        volume = volume.plus(item.volume || 0)
        weight = weight.plus(item.weight || 0)
        quantityAll = quantityAll.plus(item.quantityAll || 0)
      })
      return {
        cartonsNum: cartonsNum.toNumber(),
        volume: volume.toNumber(),
        weight: weight.toNumber(),
        quantityAll: quantityAll.toNumber()
      }
    },
    // 如果有打包历史则取第一条，否则取品名入仓数据
    warehouseInData(){
      if(!this.list.length) return this.item.warehouseInInfoVO
      const records = JSON.parse(this.list[this.list.length - 1].orderWarehouseInContent)?.orderWarehouseInBackItemDoList || []
      // 多条入仓记录累加
      let cartonsNum = new Decimal(0),
        volume = new Decimal(0),
        weight = new Decimal(0),
        quantityAll = new Decimal(0)
      records.forEach(item => {
        cartonsNum = cartonsNum.plus(item.cartonsNum || 0)
        volume = volume.plus(item.volume || 0)
        weight = weight.plus(item.weight || 0)
        quantityAll = quantityAll.plus(item.quantityAll || 0)
      })
      return {
        cartonsNum: cartonsNum.toNumber(),
        volume: volume.toNumber(),
        weight: weight.toNumber(),
        quantityAll: quantityAll.toNumber()
      }
    }
  },
  onBackPress(){
    if (this.showHistoryDetail){
      this.showHistoryDetail = false
      uni.setNavigationBarTitle({
        title: this.$t('打包历史')
      })
      return true
    }
  },
  onLoad(query){
    // 特性传参过来，这个页面就不用再去解析了
    this.attr = query.attr
    this.usage = query.usage

    // 通过全局变量获取商品信息，此页面必须从打包页面点开，不能直接打开，不能刷新，否则数据会缺失
    if (query.globalVarField){
      this.item = getApp()[query.globalVarField]
      if(!this.item){
        return alert('请从打包页面进入')
      }
    }

    this.loadList(query)
  },
  methods:{
    // 查询历史，query包含orderId和orderItemId
    loadList(query){
      const params = {...query, page: 1, rows: 10000}
      getPackRecord(params).then(res => {
        this.list = res.list
      })
    },
    // 查看详情，本条记录存的是打包前的，打包后的记录取下一条记录，如果没有下一条记录取入仓记录
    showDetail(index){
      this.showHistoryDetail = this.list[index]
      uni.setNavigationBarTitle({
        title: this.$t('打包记录详情')
      })
      // 当前记录是上一次的数据，也就是打包前的数据
      const json = JSON.parse(this.list[index].orderWarehouseInContent)
      console.log({json})
      this.before = this.parseRecords(json?.orderWarehouseInBackItemDoList || [])
      this.beforePictureUrls = json.pictureUrls || []
      // 如果是首条(最后一次打包记录)，则打包后的数据取当前入仓记录
      if(index === 0){
        this.after = []
        getOrderWarehouseIn(this.item.orderId).then(res => {
          const item = res.find(item => item.orderItemId == this.item.orderItemId)
          console.log({item})
          this.after = this.parseRecords(item?.orderWarehouseInBackItemDoList || [])
          this.afterPictureUrls = item.pictureUrls
        })
      }
      // 否则就取下一次打包的数据
      else{
        const afterJson = JSON.parse(this.list[index - 1].orderWarehouseInContent)
        this.after = this.parseRecords(afterJson?.orderWarehouseInBackItemDoList || [])
        this.afterPictureUrls = afterJson.pictureUrls
      }
    },
    // 解析入仓记录（规格转换成长宽高）
    parseRecords(list){
      return list.map(item => {
        const [c, k, g] = item.boxGauge.split('*')
        item.c = c
        item.k = k
        item.g = g
        return item
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import "./styles/detail.scss";
page{
  background-color: #ffffff;
}
.list{
  padding: 30rpx;
  .item{
    padding: 20rpx 0;
    border-bottom: 1px solid #eee;
    &:last-child{
      border-bottom: none;
    }
    .action{
      margin-top: 20rpx;
      button{
        margin: 0
      }
    }
  }
}
.section-title{
  font-weight: bold;
  font-size: 34rpx;
}
.detail{
  padding: 0 30rpx
}
.card-row{
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
  text{
    margin:0 10rpx;
  }
}
</style>
