<template>
<!--打包-->
  <uni-popup ref="popup" background-color="#fff" @maskClick="maskClick">
    <view class="popup-content">
      <view class="popup-title">{{$t("你确定要将{prod}进行打包么？", {prod: $l(item, 'prodTitle')})}}</view>
      <view class="content-wrap">
        <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.feeType] }}</view>
              </view>
              <view>
                <view class="label">{{$t('箱数')}}: </view>
                <view class="content blue" @click="showWarehouseIn(item)">{{ 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="warehouseIn.packStatus" />
                </view>
              </view>
            </view>
            <view>
              <view>
                <view class="label">{{$t('商品特性')}}: </view>
                <view class="content">{{ attr }}</view>
              </view>
            </view>
            <view>
              <view>
                <!--用途浩哥跟江南于23-10-27 10:20确认不需要修改了-->
                <view class="label">{{$t('用途')}}: </view>
                <view class="content">{{ usage }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="flex justify-between">
        <view class="popup-title">{{$t('打包记录')}}</view>
        <view v-if="warehouseInIndex < 0">
          <button class="mini-btn" type="primary" size="mini" @tap="addRow">{{$t('新增打包记录')}}</button>
        </view>
      </view>
      <template v-for="(item, index) in orderWarehouseInItemDtoList">
        <uni-card v-if="warehouseInIndex < 0 || warehouseInIndex === index" class="add-popup-card" :key="index" style="margin: 10px 0;">
        <view class="card-row">
          <uni-easyinput v-model="item.cartonsNum" type="number" :placeholder="$t('箱数')" :clearable="false" @input="handleVolume(index)"/>
          <switch :checked="item.specificationType === 1" @change="switchChange(item, index)" />
          <dict-tag :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" :value="item.specificationType + ''"/>
          <uni-easyinput v-model="item.weight" type="number" :placeholder="$t('重量')" :clearable="false"/>
          <text>KG</text>
          <uni-easyinput v-model="item.quantityAll" type="number" :placeholder="$t('个数')" :clearable="false"/>
          <text>{{$t('个')}}</text>
        </view>
        <view class="card-row">
          <uni-easyinput v-model="item.c" type="number" :placeholder="$t('长')" :clearable="false" @input="handleVolume(index)"/>
          <text>*</text>
          <uni-easyinput v-model="item.k" type="number" :placeholder="$t('宽')" :clearable="false" @input="handleVolume(index)"/>
          <text>*</text>
          <uni-easyinput v-model="item.g" type="number" :placeholder="$t('高')" :clearable="false" @input="handleVolume(index)"/>
          <text>=</text>
          <uni-easyinput 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>
          <!--<uni-data-select v-model="item.unit" :localdata="unitRange" :clear="false" :placeholder="$t('请选择')"></uni-data-select>-->
          <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>
        <view class="card-row">
          <text>{{$t('快递单号')}}</text>
          <uni-easyinput v-model="item.expressNo" :placeholder="$t('输入快递单号')" :clearable="false" />
          <WarehouseRecordDetail
            v-model="item.orderWarehouseInDetailsVOList"
           :order-id="order.orderId"
           :warehouse-in-id="item.id"
            @input="handleMergeExpressAndPictures(index)"
          />
        </view>

        <view v-if="index" class="delete-btn" @tap="delRow(index)">{{$t('删除')}}</view>
      </uni-card>
      </template>

      <view class="cu-form-group">
        <view class="title"><span style="color: red">*</span>{{$t('入仓影像')}}</view>
      </view>
      <!--<view class="img-wrap">
        <uni-grid :column="4" :highlight="true" :show-border="false">
          <uni-grid-item v-for="(image, index) in pictureUrls" :index="index" :key="index">
            <view class="grid-item-box" style="height: 100%;position: relative;">
              <image :src="iconpath" style="position: absolute;top:4px;right:4px;width:24px;height:24px;z-index:9" @tap="delimage(index)" mode="widthFix"></image>
              <image v-if="image.type === 'image'" :src="image.url" mode="scaleToFill" style="height: 100%" @tap="previewImage(image.url)" />
              <video v-else-if="image.type === 'video'" :id="`video_${index}`" style="width: 100%;height: 100%" :src="image.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(pictureUrls)">
                <uni-icons type="plusempty" size="30" color="#eae8eb"></uni-icons>
                &lt;!&ndash; <text>添加视频或图片</text> &ndash;&gt;
              </view>
            </view>
          </uni-grid-item>
        </uni-grid>
      </view>-->
      <media-list v-model="pictureUrls"></media-list>

      <view class="popup-title">{{$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>
      <view class="popup-foot-btn">
        <button class="mini-btn" type="primary" size="mini" @tap="saveForm">{{$t('确认')}}</button>
        <button class="mini-btn" type="default" size="mini" @tap="maskClick">{{$t('取消')}}</button>
      </view>
    </view>

    <!-- 查看入仓详情 -->
    <warehouse-detail ref="warehouseDetail" v-if="showWarehouseDetail" :orderId="order.orderId" :orderItemId="item.orderItemId" />
  </uni-popup>
</template>

<script>
import {alert} from "@/util/tools";
import {finishPack} from "@/pages/stocking/api";
import Decimal from "decimal.js";
import warehouseDetail from '../../tally/warehouseDetail.vue'
import WarehouseRecordDetail from "@/components/warehouse-record-detail/index.vue";
/*import iconpath from "@/static/images/close.png"
import { updateImg } from "@/api/system";*/
import MediaList from "@/pages/utils/components/MediaList.vue";

export default {
  name: "pack",
  components: {
    MediaList,
    WarehouseRecordDetail,
    warehouseDetail
  },
  props:{
    // 订单信息
    order: Object,
    // 商品信息
    item: Object,
    // 特性
    attr: String,
    // 品名入仓数据
    warehouseIn:Object,
    // 用途
    usage: String,
    // 指定修改入仓记录
    warehouseInIndex: Number,

  },
  data(){
    return {
      orderWarehouseInItemDtoList: [],
      // 是否显示入仓详情
      showWarehouseDetail: false,
      // 入仓影响
      pictureUrls: [],
      iconpath: null
    }
  },
  computed:{
    unitRange(){
      return (this.$store.getters.dict_datas[this.DICT_TYPE.ECW_PACKAGING_TYPE] || []).map(v => ({ ...v, text: this.$l(v, 'label')}))
    },
    // 显示包装类型
    showUniLabel(){
      return value => {
        let item = this.unitRange.find(v => v.value === value)
        return item ? this.$l(item, 'label') : ''
      }
    },
    // 打包后数据
    packData(){
      let cartonsNum = new Decimal(0),
          volume = new Decimal(0),
          weight = new Decimal(0),
          quantityAll = new Decimal(0)
      this.orderWarehouseInItemDtoList.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()
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      console.log(this.$refs)
      this.$refs.popup.open()
    })
    // 默认根据入仓记录添加打包记录
    this.warehouseIn.orderWarehouseInBackItemDoList.forEach(item => {
      let [c, k, g] = item.boxGauge.split('*')
      this.orderWarehouseInItemDtoList.push({
        ...item,
        orderLocationCreateReqVOList: item.orderLocationBackVOList,
        c, k, g
      })
    })
    this.pictureUrls = this.warehouseIn.pictureUrls || []
  },
  methods:{
    // 提交
    saveForm(){
      let fields = {
        cartonsNum: this.$t('箱数'),
        c: this.$t('长'),
        k: this.$t('宽'),
        g: this.$t('高'),
        // quantityAll: this.$t('个数'),
        volume: this.$t('体积'),
        weight: this.$t('重量')
      }
      // 检查是否有未填字段
      const empty = []
      this.orderWarehouseInItemDtoList.forEach((item, index) => {
        Object.keys(fields).forEach((key) => {
          if (!item[key]) {
            empty.push(this.$t("第{n}条记录的{field}未填写", {n: index+1, field: fields[key]}))
          }
        })
      })
      if(empty.length){
        return alert(empty.join('\n'), this.$t('提示'))
      }
      // 根据长宽高生成规格字段
      this.orderWarehouseInItemDtoList.forEach(item => {
        item.boxGauge = `${item.c}*${item.k}*${item.g}`
      })
      const data = {
        orderId: this.item.orderId,
        orderItemId: this.item.orderItemId,
        orderWarehouseInItemDtoList: this.orderWarehouseInItemDtoList,
        pictureUrls: this.pictureUrls,
      }
      finishPack(data).then(res => {
        return alert(this.$t('您已完成打包，请使用管理后台打印新标签'), this.$t('提示'))
      }).then(() => {
        this.$emit("success")
      })
    },
    // 取消
    maskClick(){
      this.$emit("close")
    },
    // 新增打包记录
    addRow(){
      this.orderWarehouseInItemDtoList.push({specificationType: 1})
    },
    // 删除一条
    delRow(index){
      this.orderWarehouseInItemDtoList.splice(index, 1)
    },
    // 计算体积
    handleVolume(index){
      this.$nextTick(() => {
        const { c, k, g, specificationType, cartonsNum } = this.orderWarehouseInItemDtoList[index]
        if (c && k && g && cartonsNum) {
          const volume = (((specificationType === 1 || specificationType === '1') ? cartonsNum : 1) * (c * k * g) / 1000000).toFixed(2)
          this.$set(this.orderWarehouseInItemDtoList[index], 'volume', volume === '0.00' ? '0.01' : volume)
        } else {
          this.orderWarehouseInItemDtoList[index].volume = 0
        }
        this.$forceUpdate()
      })
    },
    // 切换箱，整版
    switchChange(item, index){
      if (item.specificationType === 1){
        this.$set(item, 'specificationType', 2)
      }else {
        this.$set(item, 'specificationType', 1)
      }
      this.handleVolume(index)
    },
    // 选择单位(包装类型)
    handleUnitChange(e, index) {
      console.log('handleUnitChange', e, index)
      this.$set(this.orderWarehouseInItemDtoList[index], 'unit', this.unitRange[e.detail.value].value)
    },
    // 跳转储位选择
    toLocation(index){
      const warehouseId = this.order.adjustToDestWarehouseId || this.order?.logisticsInfoDto?.startWarehouseId
      const item = this.orderWarehouseInItemDtoList[index]
      let query = `warehouseId=${warehouseId}`
        query += `&orderId=${this.order.orderId}`
        query += `&locationList=${JSON.stringify(item.orderLocationCreateReqVOList || [])}`
        query += `&extra=${index}&callback=setLocation&orderItemId=${this.item.orderItemId}`
      if(item.id){
        query += `&warehouseInId=${item.id}`
      }

      let url = `../warehousing/location?${query}`
      uni.navigateTo({
        url: url
      });
    },
    // 选择储位回调
    setLocation(locationList, extra){
      this.$set(this.orderWarehouseInItemDtoList[extra], 'orderLocationCreateReqVOList', locationList)
    },
    // 显示入仓记录
    showWarehouseIn(){
      this.showWarehouseDetail = true
      this.$nextTick(() => {
        this.$refs.warehouseDetail.showDetail(this.order)
      })
    },
    // 想明细更新后将影响和快递单号合并到主商品中
    handleMergeExpressAndPictures(index){
      this.orderWarehouseInItemDtoList?.forEach((item, i) => {
        item.orderWarehouseInDetailsVOList?.forEach(detail => {
          // 合并影像到入仓记录中
          this.pictureUrls = this.pictureUrls.concat(detail.pictureUrls)

          // 合并快递单号到打包记录中
          if(i === index && detail.expressNo?.length){
            item.expressNo += `,${detail.expressNo}`
          }
        })
      })
    }
    /*delimage(index){
      this.pictureUrls.splice(index,1)
    },
    previewImage(url) {
      //uniapp预览轮播图
      uni.previewImage({
        current: 0, //预览图片的下标
        urls: [url] //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
      })
    },*/

  }
}
</script>

<style scoped lang="scss">
@import "../styles/detail.scss";
.img-wrap {
  ::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;
  }
}

.blue{
  color: #007aff !important;
}
.popup-content{
  padding: 30rpx;
  max-width: 90vw;
  max-height: 80vh;
  overflow-y: auto;
  .popup-title{
    font-size: 30rpx;
    font-weight: bold;
  }
  .popup-foot-btn{
    display: flex;
    justify-content: space-around;
  }
}
.card-row{
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
  text{
    margin: 10rpx;
  }
  picker{
    flex: 1;
    height: 55px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .content{
      width: 100%;
      align-items: center;
      .label{
        flex: 1;
      }
    }
  }
}
.delete-btn {
  width: 72px;
  line-height: 30px;
  border: 0.5px solid #007aff;
  text-align: center;
  border-radius: 15px;
  color: #007aff;
  margin-left: auto;
}
.pack-data{
  margin-top: 20rpx;
  margin-bottom: 30rpx;
}
</style>
