<!--备货-->
<template>
  <div class="app-container">
    <h2>{{ title }}-{{ order.orderNo }}</h2>

    <order-base-info :order="order" stocking></order-base-info>

    <div class="flex items-center">
			<div class="flex-1 page-title">{{$t('货物信息')}}</div>
      <el-button type="primary" @click="showNewProductDialog=true">{{$t('添加新品名')}}</el-button>
    </div>

    <!--
    未入仓的不显示 https://zentao.test.jdshangmen.com/bug-view-5292.html
    -->
    <el-table
      v-if="order.orderItemVOList && order.orderItemVOList.length > 0 && orderItemList && orderItemList.length > 0"
      :data="order.orderItemVOList || []"
      default-expand-all
      style="width: 100%">
      <!--入仓记录-->
      <el-table-column type="expand">
        <template slot-scope="props">
          <div style="padding-left: 80px" v-if="orderWarehouseInList(props.row.orderItemId).length">
            <el-table :data="orderWarehouseInList(props.row.orderItemId)">
              <el-table-column :label="$t('序号')" width="80px">
                <template slot-scope="{row, column, $index}">
                  {{$index + 1}}
                </template>
              </el-table-column>
              <el-table-column prop="cartonsNum" :label="$t('箱数')" width="60px"></el-table-column>
              <el-table-column prop="areaName" :label="$t('入仓类型')">
                <template v-slot="{row}">
                  <dict-tag :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" :value="row.specificationType"></dict-tag>
                </template>
              </el-table-column>
              <el-table-column prop="areaName" :label="$t('包装类型')">
                <template v-slot="{row}">
                  <dict-tag :type="DICT_TYPE.ECW_PACKAGING_TYPE" :value="row.unit"></dict-tag>
                </template>
              </el-table-column>
              <el-table-column prop="areaName" :label="$t('长') + '(cm)'" width="70px">
                <template v-slot="{row}">{{row.boxGauge.split('*')[0]}}</template>
              </el-table-column>
              <el-table-column prop="areaName" :label="$t('宽') + '(cm)'" width="70px">
                <template v-slot="{row}">{{row.boxGauge.split('*')[1]}}</template>
              </el-table-column>
              <el-table-column prop="areaName" :label="$t('高') + '(cm)'" width="70px">
                <template v-slot="{row}">{{row.boxGauge.split('*')[2]}}</template>
              </el-table-column>
              <el-table-column prop="volume" :label="$t('体积')+'(m³)'"></el-table-column>
              <el-table-column prop="weight" :label="$t('重量')+'(kg)'"></el-table-column>
              <el-table-column prop="quantityAll" :label="$t('数量') + '(个)'"></el-table-column>
              <el-table-column prop="expressNo" :label="$t('快递单号')"></el-table-column>
              <el-table-column prop="createTime" :label="$t('首次入仓时间')">
                <template v-slot="{row}">{{parseTime(row.inTime)}}</template>
              </el-table-column>
              <el-table-column prop="areaName" :label="$t('储位')">
                <template v-slot="{row}">
                  {{row.orderLocationStr4Merge}}
                </template>
              </el-table-column>
              <el-table-column prop="areaName" :label="$t('影像')">
                <template v-slot="{row}">
                  <el-button type="text" @click="showMedia(props.row)">{{$t('查看')}}</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="areaName" :label="$t(' ')" width="220px">
                <template v-slot="{row}">
                  <WarehouseRecordDetail v-model="row.orderWarehouseInDetailsVOList" @input="saveDetail(props.row)" />
                  <el-button class="pl-5 pr-5" size="mini" type="primary" @click="package(props.row, $t('修改打包'))">{{$t('修改')}}</el-button>
                  <el-button class="pl-5 pr-5" size="mini" type="danger" @click="package(props.row, $t('修改打包'))">{{$t('删除')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        type="index"
        width="50"
        :label="$t('序号')">
      </el-table-column>
      <el-table-column
        prop="prodTitleZh"
        :label="$t('品名')">
        <template v-slot="{row}">
          {{ row.prodTitleZh }}<br>
          {{ row.prodTitleEn }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('填单货物属性')">
        <template v-slot="{row}">
          <span v-if="row.isWarehouseInAdd">{{$t('非填单货物信息')}}</span>
          <template v-else>
            {{$t('品牌')}}：{{ [$t('无牌'), $t('有牌'), $t('中性')][row.brandType] }}<br>
            {{$t('箱数')}}：{{ row.num }}<br>
            {{$t('体积')}}：{{ row.volume }}m³<br>
            {{$t('重量')}}：{{ row.weight }}Kg
          </template>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('入库货物属性')">
        <template v-slot="{row}">
          <template v-if="row.warehouseInInfoVO">
            {{$t('品牌')}}：{{ row.brandName }}<br>
            {{$t('箱数')}}：{{ row.warehouseInInfoVO.cartonsNum }}<br>
            {{$t('体积')}}：{{ row.warehouseInInfoVO.volume }}m³<br>
            {{$t('重量')}}：{{ row.warehouseInInfoVO.weight }}Kg
          </template>
          <span v-else>{{$t('暂无入仓信息')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="expressNo"
        v-slot="{row}"
        :label="$t('快递单号')">
        {{ row.expressNo || (row.warehouseInInfoVO ? row.warehouseInInfoVO.expressNo : '') }}
      </el-table-column>
      <el-table-column
        v-slot="{row}"
        :label="$t('商品特性')">
        <template v-if="row.prodAttrIds">
          {{showAttr(row.prodAttrIds)}}
        </template>
      </el-table-column>

      <el-table-column
        prop="createTime"
        :label="$t('最后操作时间')">
        <template v-slot="{row}">
          {{ parseTime(row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="diffType"
        v-slot="{row}"
        :label="$t('状态')">
        <dict-tag
          v-if="row.warehouseInInfoVO && row.warehouseInInfoVO.diffType"
          :type="DICT_TYPE.ORDER_WAREHOUSE_IN_STATUS"
          :value="row.warehouseInInfoVO.diffType"
          class="red"
          :class="{green: row.warehouseInInfoVO.diffType === 4}"
        />
        <span :class="{red: row.itemStatus === 3}" v-else>{{ row.itemStatus === 3 ? ($t('少了') + row.num + $t('箱')) : $t('待入仓') }}</span>
        <span class="red" v-if="row.warehouseInInfoVO && row.warehouseInInfoVO.cartonsNumDiff">{{ row.warehouseInInfoVO.cartonsNumDiff }}{{$t('箱')}}</span>
      </el-table-column>
      <el-table-column
        prop="createTime"
        :label="$t('打包状态')" width="100">
        <template v-slot="{row}">
          <dict-tag :type="DICT_TYPE.ORDER_ITEM_PACK_STATUS" :value="wareItemPackStatus(row.orderItemId)" />
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        :label="$t('操作')" width="220">
        <template v-slot="{ row, column, $index }">
          <!--没有入仓记录的不显示打包按钮 https://zentao.test.jdshangmen.com/bug-view-5389.html-->
          <el-button-group v-if="orderWarehouseInList(row.orderItemId).length">
            <template v-if="wareItemPackStatus(row.orderItemId) == 1">
              <el-button size="mini" type="warning" @click="noNeedPack(row)">{{$t('无需打包')}}</el-button>
              <el-button size="mini" type="primary" @click="package(row, $t('打包'))">{{$t('打包')}}</el-button>
            </template>

            <el-button v-else size="mini" type="primary" @click="package(row, $t('修改打包'))">{{$t('修改打包')}}</el-button>
            <el-button size="mini" type="danger" @click="rollback(row)">{{$t('退仓')}}</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!--<h2 v-if="orderSpecialNeeds.length > 0">{{$t('特殊需求')}}</h2>-->
    <el-form ref="form" :model="form" label-width="200px">
      <!--<el-form-item :label="$i18n.locale === 'en_US' ? item.labelEn : item.label" v-for="(item, index) in orderSpecialNeeds" :key="item.value" style="width: 600px">
        <el-input v-model="form.orderSpecialNeedReceivableReqVoList[index].receivableMoney" :placeholder="$t('请输入') + ($i18n.locale === 'en_US' ? item.labelEn : item.label)">
          <el-select v-model="form.orderSpecialNeedReceivableReqVoList[index].receivableMoneyCurrency" :placeholder="$t('请选择')" slot="append" style="width: 100px">
            <el-option
              v-for="item in currencyList"
              :key="item.id"
              :label="$i18n.locale === 'en_US' ? item.titleEn : item.titleZh"
              :value="item.id">
            </el-option>
          </el-select>
        </el-input>
      </el-form-item>-->

      <h2>{{$t('订单数据')}}</h2>
      <el-form-item :label="$t('总方数')" style="width: 380px">
        <el-input v-model="form.sumVolume" :placeholder="$t('请输入总方数')" readonly>
          <span slot="append">m³</span>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('总重量')" style="width: 380px">
        <el-input v-model="form.sumWeight" :placeholder="$t('请输入总重量')" readonly>
          <span slot="append">kg</span>
        </el-input>
      </el-form-item>

      <el-card style="margin-top: 15px;">
        <div slot="header" class="clearfix">
          <span style="font-size: 18px">{{$t('入仓影像')}}</span>
        </div>
        <div>
          <image-and-video-upload :fileSize="50" :isShowTip="true" v-model="pictureUrls" readonly ></image-and-video-upload>
        </div>
      </el-card>
      <div style="text-align: center;margin-top: 15px">
        <el-button @click="escapeBol = true;" type="primary">{{$t('转异')}}</el-button>
        <el-button type="primary" @click="handleSubmit">{{$t('完成备货')}}</el-button>
      </div>
    </el-form>

    <el-dialog :title="order.orderNo + $t('订单转异')" center :visible.sync="escapeBol">
      <el-form label-position="top" label-width="200" ref="exceptionForm" :model="form" :rules="exceptionRules">
        <el-form-item :label="$t('异常类型')" prop="manualExceptionType">
          <dict-selector v-model="form.manualExceptionType" form-type="checkbox" :type="DICT_TYPE.STOCK_UP_EXCEPTION_TYPE" multiple ></dict-selector>
        </el-form-item>
        <el-form-item :label="$t('附件')">
          <!--<image-upload v-model="form.exceptionUrls"></image-upload>-->
          <image-and-video-upload :fileSize="50" :isShowTip="true" v-model="form.exceptionUrls" ></image-and-video-upload>
        </el-form-item>
        <el-form-item :label="$t('详细信息')">
          <el-input v-model="form.descZh" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button  type="primary" @click="handleException">{{$t('确认并完成打包')}}</el-button>
        <el-button @click="escapeBol = false">{{$t('取消')}}</el-button>
      </span>
    </el-dialog>

    <print-tag v-if="isShowPrintTag" :order-id="orderId" @close="isShowPrintTag = false"></print-tag>
    <package
      :order="order"
      :order-item-a="packageOrderItem"
      :order-item-b="packageWarehouseItem"
      :title="packageTitle"
      v-if="!!packageOrderItem"
      @close="onPackageClose"
    ></package>
		<new-product
			:order="order"
			v-if="showNewProductDialog"
			@close="onPackageClose"
		></new-product>
    <media-dialog v-if="curPictrues" :value="curPictrues" @close="curPictrues=null"></media-dialog>
  </div>
</template>

<script>
import {getCurrencyList} from "@/api/ecw/currency"
import {
  finishPacked,
  finishStock,
  getOrder,
  getOrderWarehouseIn,
  getSpecialListByOrderId,
  noNeedPack, rollbackDelete,
  warehousePictureList
} from '@/api/ecw/order'
import orderBaseInfo from "@/components/OrderBaseInfo"
import WarehouseAreaDialog from '@/components/WarehouseAreaDialog'
import {DICT_TYPE} from "@/utils/dict"
import PrintTag from "@/views/ecw/order/components/PrintTag"
import PrintWarehouseReceipt from "@/views/ecw/order/components/PrintWarehouseReceipt"
import imageUpload from "@/components/ImageUpload";
import {parseTime} from "@/utils/ruoyi"
import ImageAndVideoUpload from '@/components/ImageAndVideoUpload'
import Package from './components/Package'
import Template from "@/views/cms/template/index.vue";
import {getProductAttrList} from "@/api/ecw/productAttr";
import MediaDialog from "@/views/ecw/order/stocking/components/MediaDialog.vue";
import WarehouseRecordDetail from "@/views/ecw/order/warehousing/components/WarehouseRecordDetail.vue";
import {formatTime} from "../../../../utils";

export default {
  name: "Stocking",

  components: {
    WarehouseRecordDetail,
    MediaDialog,
    Template,
    orderBaseInfo,
    WarehouseAreaDialog,
    PrintTag,
    PrintWarehouseReceipt,
    imageUpload,
    ImageAndVideoUpload,
    Package,
    NewProduct: () => import('@/views/ecw/order/stocking/components/NewProduct.vue')
  },

  mounted() {
    if(this.$route.query.id){
      this.orderId = parseInt(this.$route.query.id || undefined)
      this.getOrderItemList()
      getSpecialListByOrderId(this.orderId).then(r => this.specialList = r.data)

      this.getOrder()
    }
    getCurrencyList().then(res => this.currencyList = res.data)
    getProductAttrList().then(res => this.productAttrList = res.data)
  },

  data() {
    return {
      parseTime,
      DICT_TYPE,
      areaVisible: false,
      finishVisible: false,
      warehousingVisible: false,
      form: {
        exceptionUrls:[],
        descZh:'',
        manualExceptionType:[],
        sumVolume: '',
        sumWeight: '',
      },
      currencyList:[],
      order: {},
      orderId: undefined,
      orderItemList: [],
      specialList: [],
      warehousing: undefined,
      isShowPrintTag: false,
      isShowPrint: false,
      escapeBol:false,

      label: {
        "orderId": 0,
        "orderLabelDtoList": [
          {
            "end": 0,
            "start": 0
          }
        ]
      },
      exceptionRules: {
        manualExceptionType: [
          { required: true, message: '请勾选原因类型', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value.length <= 0) {
                callback(new Error('请勾选原因类型'))
              }
              callback()
            }, trigger: 'change'
          }
        ]
      },
      // 打包弹层的标题
      packageTitle: null,
      // 当前打包的订单商品项
      packageOrderItem: null,
      // 打包商品的入仓商品项
      packageWarehouseItem: null,
      productAttrList: [],
      // 当前查看的影像
      curPictrues: null,
      // 是否显示添加新品弹窗
      showNewProductDialog: false
    }
  },

  methods: {
    formatTime,
    getOrderItemList(){
      this.orderItemList = []
      return getOrderWarehouseIn(this.orderId).then(r => this.orderItemList = r.data)
    },
    getList(){
      this.getOrder()
      this.getOrderItemList()
    },
    getWarehousePictureList(){
      return warehousePictureList({
        bizId: this.order.orderId,
        type: 1
      }).then(r =>{
        this.form.urls = r.data.map(i =>i.url)
      })
    },
    include(){
      return (state, arr) => {
        return arr.indexOf(state) > -1
      }
    },
    exclude(){
      return (state, arr) => {
        return arr.indexOf(state) == -1
      }
    },
    getOrder(){
      return getOrder(this.orderId).then(r => {
        // 获取渠道可出特性文案用户订单基础信息显示
        r.data.channelAttrName = this.showAttr(r.data.channelAttrId)
        this.order = r.data
        this.form.sumVolume = this.order.sumVolume
        this.form.sumWeight = this.order.sumWeight
      }).then(() => {
        // this.getLabelByOrder()
        this.getWarehousePictureList()
      })
    },
    // 提交转异
    handleException() {
      this.$refs.exceptionForm.validate((valid) => {
        if (valid) {
          this.handleSubmit()
        } else {
          this.$message.warning('请勾选原因类型')
        }
      })
    },
    // 完成备货
    async handleSubmit() {
      let unpackProds = []
      this.orderItemList.forEach(item => {
        // 有入仓记录且未打包
        if(item.orderWarehouseInBackItemDoList.length && item.packStatus == 1){
          unpackProds.push(this.$l(item, 'prodTitle'))
        }
      })
      if(unpackProds.length){
        return this.$alert(`商品${unpackProds.join(',')}未完成打包,无法完成备货`, this.$t('提示'))
      }

      let form = {...this.form}
      form.orderId = this.orderId
      form.manualExceptionType = form.manualExceptionType.join(',')
      finishStock(form).then(res => {
        return this.$alert(this.$t('操作成功'))
      }).then(() => {
        this.$tab.closePage()
      })
    },
    // 显示打包弹层
    package(row, title = null){
      this.packageOrderItem = row
      this.packageWarehouseItem = this.orderItemList.find(item => item.orderItemId === row.orderItemId)
      this.packageTitle = title || this.$t('打包')
    },
    // 无需打包
    noNeedPack(row){
      noNeedPack(row.orderItemId).then(res => {
        this.$message.success(this.$t('操作成功'))
        this.getList()
      })
    },
    onPackageClose(){
      this.packageOrderItem=null;
      this.packageOrderItem=null;
      this.showNewProductDialog = false
      this.getList()
    },
    showMedia(orderItem){
      console.log('查看影像', orderItem)
      const wareItem = this.wareItem(orderItem.orderItemId)
      if(!wareItem.pictureUrls){
        return this.$message.info(this.$t('暂无影像'))
      }
      this.curPictrues = wareItem.pictureUrls || []
    },
    // 保存箱明细
    saveDetail(row){
      const wareItem = this.wareItem(row.orderItemId)
      const orderWarehouseInItemDtoList = wareItem.orderWarehouseInBackItemDoList
      orderWarehouseInItemDtoList.map(item =>{
        item.orderLocationCreateReqVOList = item.orderLocationBackVOList || []
        return item
      })
      const data = {
        orderId: row.orderId,
        orderItemId: row.orderItemId,
        orderWarehouseInItemDtoList: orderWarehouseInItemDtoList,
        pictureUrls: wareItem.pictureUrls || []
      }
      finishPacked(data).then(res => {
        this.$message.success(this.$t('操作成功'))
      })
    },
    // 退仓
    async rollback(orderItem){
      this.$confirm(this.$l(orderItem, 'prodTitle') + this.$t("退仓后不可恢复，是否确认退仓？"), this.$t('提示')).then(() => {
        return rollbackDelete({
          orderId: this.orderId,
          orderItemId: orderItem.orderItemId,
          isPackagingRollback: true
        })
      }).then(res =>{
        this.$message.success(this.$t('操作成功'))
        this.getList()
      })
    }
  },
  watch: {
    /*orderSpecialNeeds(val){
      val.forEach(e => {
        this.form.orderSpecialNeedReceivableReqVoList.push({
          "id": e.id,
          "receivableMoney": e.transFee || '',
          "receivableMoneyCurrency": e.transCurrency || 3
        })
      })
    }*/
  },

  computed: {
    // 根据orderItemId获取入仓item
    wareItem(){
      return orderItemId => {
        return this.orderItemList.find(item => item.orderItemId == orderItemId)
      }
    },
    // 根据orderItemId获取入仓记录
    orderWarehouseInList(){
      return (orderItemId) => {
        return this.wareItem(orderItemId)?.orderWarehouseInBackItemDoList || []
      }
    },
    // 获取打包状态
    wareItemPackStatus(){
      return orderItemId => {
        return this.wareItem(orderItemId)?.packStatus
      }
    },
    title() {
      return this.$i18n.locale === 'en_US' ? this.$route.meta.titleEn : this.$route.name
    },
    orderSpecialNeedsDict() {
      return this.$store.state.dict.dictDatas.order_special_needs
    },
    orderSpecialNeeds(){
      const result = []
      this.specialList.forEach(e => {
        const t = this.orderSpecialNeedsDict.find(f => f.value === e.advanceType)
        if(t) {
          result.push({...e, label: t.label, labelEn: t.labelEn})
        }
      })
      return result
    },
    warehouseId(){
      return this.order?.logisticsInfoDto?.startWarehouseId
    },
    // 显示特性
    showAttr(){
      return attrIds => {
        if(!attrIds) return ''
        let attrArr = attrIds.split(",").map(item => +item)
        let arr = []
        this.productAttrList.forEach(item => {
          if(attrArr.indexOf(item.id) > -1) arr.push(this.$l(item, 'attrName'))
        })
        return  arr.join(",")
      }
    },
    // 全部入仓记录的入仓影像
    pictureUrls(){
      let urls = []
      this.orderItemList.forEach(item => {
        console.log('pictureUrls', item.pictureUrls)
        urls = urls.concat(item.pictureUrls || [])
      })
      return urls
    }
  }
}
</script>

<style scoped lang="scss">
@import "src/assets/styles/element-variables";
.red{
  color: $--color-danger;
}
.green{
  color: $--color-success;
}
</style>
