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

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

    <h2>{{$t('货物信息')}}</h2>
    <el-table
      v-if="order.orderItemVOList && order.orderItemVOList.length > 0 && orderItemList && orderItemList.length > 0"
      :data="order.orderItemVOList || []"
      style="width: 100%">
      <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('打包状态')">
        <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('操作')">
        <template v-slot="{ row, column, $index }">
          <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>
        </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="form.exceptionUrls" ></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>
  </div>
</template>

<script>
import {getCurrencyList} from "@/api/ecw/currency"
import {
   finishStock,
  getOrder,
  getOrderWarehouseIn,
  getSpecialListByOrderId,
  noNeedPack,
  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";

export default {
  name: "Stocking",

  components: {
    Template,
    orderBaseInfo,
    WarehouseAreaDialog,
    PrintTag,
    PrintWarehouseReceipt,
    imageUpload,
    ImageAndVideoUpload,
    Package
  },

  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: []
    }
  },

  methods: {
    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.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.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)
      }
    },
    // 获取打包状态
    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(",")
      }
    }
  }
}
</script>

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