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

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

    <div style="margin-top: 20px">
      <span>储位：{{ ($refs.area ? $refs.area.selected : []).join(',') }}</span>
      <el-button type="primary" size="mini" @click="areaVisible = true" style="margin-left: 15px">选择</el-button>
    </div>

    <h2>货物信息</h2>
    <el-table
      :data="order.orderItemVOList || []"
      style="width: 100%">
      <el-table-column
        type="index"
        width="50"
        label="序号">
      </el-table-column>
      <el-table-column
        prop="prodTitleZh"
        label="品名">
        <template v-slot="{row}">
          {{ row.prodTitleZh }}<br>
          {{ row.prodTitleEn }}
        </template>
      </el-table-column>
      <el-table-column
        label="填单货物属性">
        <template v-slot="{row}">
          <span v-if="row.isWarehouseInAdd">非填单货物信息</span>
          <template v-else>
            品牌：{{ ['无牌', '有牌', '中性'][row.brandType] }}<br>
            箱数：{{ row.num }}<br>
            体积：{{ row.volume }}m³<br>
            重量：{{ row.weight }}Kg
          </template>
        </template>
      </el-table-column>
      <el-table-column
        label="入库货物属性">
        <template v-slot="{row}">
          <template v-if="row.warehouseInInfoVO">
            品牌：{{ ['无牌', '有牌', '中性'][row.brandType] }}<br>
            箱数：{{ row.warehouseInInfoVO.cartonsNum }}<br>
            体积：{{ row.warehouseInInfoVO.volume }}m³<br>
            重量：{{ row.warehouseInInfoVO.weight }}Kg
          </template>
          <span v-else>暂无入仓信息</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="expressNo"
        v-slot="{row}"
        label="快递单号">
        {{ row.warehouseInInfoVO ? row.warehouseInInfoVO.expressNo : '' }}
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="最后操作时间">
        <template v-slot="{row}">
          {{ parseTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="diffType"
        v-slot="{row}"
        label="状态">
        <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" v-if="row.warehouseInInfoVO && row.warehouseInInfoVO.cartonsNumDiff">{{ row.warehouseInInfoVO.cartonsNumDiff }}箱</span>
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作">
        <template v-slot="{ row, column, $index }">
          <el-button v-if="isEdit" size="mini" type="text" @click="handleWarehousing($index)">修改</el-button>
          <template v-else-if="orderItemList[$index] && orderItemList[$index].orderWarehouseInBackItemDoList && orderItemList[$index].orderWarehouseInBackItemDoList.length > 0">
            <el-button size="mini" type="text" @click="handleWarehousing($index)">追加</el-button>
            <el-button size="mini" type="text" @click="handleWarehousingReturn(row)">退仓</el-button>
          </template>
          <el-button v-else size="mini" type="text" @click="handleWarehousing($index)">入仓</el-button>
        </template>
      </el-table-column>
    </el-table>

    <h2 v-if="orderSpecialNeeds.length > 0">特殊需求</h2>
    <el-form ref="form" :model="form" label-width="120px">
      <el-form-item :label="item.label" v-for="(item, index) in orderSpecialNeeds" :key="item.value" style="width: 400px">
        <el-input v-model="form.orderSpecialNeedReceivableReqVoList[index].receivableMoney" :placeholder="'请输入' + item.label">
          <el-select v-model="form.orderSpecialNeedReceivableReqVoList[index].receivableMoneyCurrency" placeholder="请选择" slot="append" style="width: 100px">
            <el-option
              v-for="item in currencyList"
              :key="item.id"
              :label="item.titleZh"
              :value="item.id">
            </el-option>
          </el-select>
        </el-input>
      </el-form-item>

      <h2>订单数据</h2>
      <el-form-item label="总方数" style="width: 300px">
        <el-input v-model="form.sumVolume" placeholder="请输入总方数">
          <span slot="append">m³</span>
        </el-input>
      </el-form-item>
      <el-form-item label="总重量" style="width: 300px">
        <el-input v-model="form.sumWeight" placeholder="请输入总重量">
          <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">入仓影像</span>
        </div>
        <div>
          <image-and-video-upload :fileSize="50" :isShowTip="true" v-model="form.urls" ></image-and-video-upload>
        </div>
      </el-card>

      <template v-if="order.parentOrderId && isEdit">
        <h2>标签箱号</h2>

        <div v-for="(item, index) in label.orderLabelDtoList" :key="index" style="margin-bottom: 10px">
          <el-input-number v-model="item.start" controls-position="right"></el-input-number> -
          <el-input-number v-model="item.end" controls-position="right"></el-input-number>
          <el-button icon="el-icon-minus" circle v-show="index !== 0" @click="label.orderLabelDtoList.splice(index, 1)" style="margin-left: 10px"></el-button>
          <el-button icon="el-icon-plus" circle @click="handleLabelAdd(index)"></el-button>
        </div>
        <div style="text-align: center">
          <el-button type="primary" @click="handleLabelSubmit">修改箱号</el-button>
        </div>
      </template>
      <div style="text-align: center;margin-top: 15px" v-if="order.status !== 5">
        <el-button @click="escapeBol = true;" type="primary">转异</el-button>
        <el-button type="primary" @click="finishVisible = true">完成入仓</el-button>
      </div>
    </el-form>

    <warehouse-area-dialog ref="area" :visible.sync="areaVisible" v-model="form.orderLocationCreateReqVOList"
                           :order-id="orderId" :city-id="cityId"></warehouse-area-dialog>

    <edit-dialog :title="title" :customer-id="order.customerId" :visible.sync="warehousingVisible" :warehousing="warehousing" :edit="isEdit"></edit-dialog>

<!--  完成入仓  -->
    <el-dialog
      title="确认入仓"
      :visible.sync="finishVisible"
      width="300px">
      <div style="text-align: center">在完成入仓前，您还可以</div>
      <div style="text-align: center;padding: 15px 0">
        <el-button type="info" @click="areaVisible = true">选择储位</el-button>
        <el-button type="info" @click="isShowPrintTag = true">打印标签</el-button>
      </div>
      <div style="text-align: center">
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="order.orderNo + '订单转异'" center :visible.sync="escapeBol">
      <el-form label-position="top" label-width="200">
        <el-form-item label="原因类型">
          <dict-selector v-model="form.manualExceptionType" form-type="checkbox" :type="DICT_TYPE.MANUAL_EXCEPTION_TYPE" multiple ></dict-selector>
        </el-form-item>
        <el-form-item required label="附件">
          <image-upload v-model="form.exceptionUrls"></image-upload>
        </el-form-item>
        <el-form-item label="详细信息">
          <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="handleSubmit">确认并完成入仓</el-button>
        <el-button @click="escapeBol = false">取消</el-button>
      </span>
    </el-dialog>

    <print-tag v-if="isShowPrintTag" :order-id="orderId" @close="isShowPrintTag = false"></print-tag>

    <print-warehouse-receipt v-if="isShowPrint" :order-id="orderId" @close="isShowPrint = false" />
  </div>
</template>

<script>
import {getCurrencyList} from "@/api/ecw/currency"
import {
  getOrder,
  getOrderWarehouseIn,
  getSpecialListByOrderId, listByOrderId,
  orderWarehouseInFinish, orderWarehouseInUpdateLabel,
  rollbackDelete
} from '@/api/ecw/order'
import orderBaseInfo from "@/components/OrderBaseInfo"
import WarehouseAreaDialog from '@/components/WarehouseAreaDialog'
import editDialog from '@/views/ecw/order/warehousing/components/editDialog'
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'
export default {
  name: "Warehousing",

  components: {
    orderBaseInfo,
    WarehouseAreaDialog,
    editDialog,
    PrintTag,
    PrintWarehouseReceipt,
    imageUpload,
    ImageAndVideoUpload,
  },

  mounted() {
    if(this.$route.query.id){
      this.orderId = parseInt(this.$route.query.id || undefined)
      this.getOrder()
      getOrderWarehouseIn(this.orderId).then(r => this.orderItemList = r.data.reverse())
      getSpecialListByOrderId(this.orderId).then(r => this.specialList = r.data)
      listByOrderId({ orderId: this.orderId }).then(r => this.form.orderLocationCreateReqVOList = r.data)
    }
    getCurrencyList().then(res => this.currencyList = res.data)
  },

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

      label: {
        "orderId": 0,
        "orderLabelDtoList": [
          {
            "end": 0,
            "start": 0
          }
        ]
      }
    }
  },

  methods: {
    include(){
      return (state, arr) => {
        return arr.indexOf(state) > -1
      }
    },
    exclude(){
      return (state, arr) => {
        return arr.indexOf(state) == -1
      }
    },
    handleLabelSubmit(){
      orderWarehouseInUpdateLabel({
        ...this.label,
        orderId: this.orderId
      }).then(r => {
        if (r.code === 0){
          this.$message.success(r.msg || '修改标签箱号成功')
        }
      })
    },
    handleLabelAdd(index){
      this.label.orderLabelDtoList.splice(index + 1, 0, {
        "end": '',
        "start": ''
      })
    },
    getTowSum(){
      let sumVolume = 0
      let sumWeight = 0
      this.order.orderItemVOList.forEach(e => {
        if (e?.warehouseInInfoVO?.volume) sumVolume += e.warehouseInInfoVO.volume
        if (e?.warehouseInInfoVO?.weight) sumWeight += e.warehouseInInfoVO.weight
      })
      this.form.sumVolume = sumVolume
      this.form.sumWeight = sumWeight
    },
    getOrder(){
      getOrder(this.orderId).then(r => {
        this.order = r.data
        this.getTowSum()
      })
    },
    specialHas0(){
      let result = false
      this.form.orderSpecialNeedReceivableReqVoList.forEach(e => {
        if (e.receivableMoney === '0' || e.receivableMoney === ''){
          result = true
        }
      })
      return result
    },
    async handleSubmit() {
      if (this.specialHas0()) {
        const confirm = await this.$confirm('有特需费用为0或未填写，请问是否继续？', '注意', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (confirm !== 'confirm'){
          return
        }
      }
      let p = {
        orderSpecialNeedReceivableReqVoList: this.form.orderSpecialNeedReceivableReqVoList,
        "orderLocationCreateReqVOList": this.form.orderLocationCreateReqVOList,
        "orderId": this.order.orderId,
        urls: this.form.urls
      }
      if (this.escapeBol) {
        p.exceptionUrls = this.form.exceptionUrls.split(',');
        p.descZh = this.form.descZh;
        p.manualExceptionType = this.form.manualExceptionType
      }
      orderWarehouseInFinish(p).then(r => {
        if (r.code === 0) {
          this.escapeBol = false;
          this.finishVisible = false
          this.$confirm(
            '该订单已成功入仓，是否打印？',
            '货物已入仓',
            {
              confirmButtonText: '是',
              cancelButtonText: '否'
            }
          ).then(() => {
            this.isShowPrint = true
          }).catch(() => {
            // this.$store.dispatch('tagsView/delVisitedView')
            this.$message.success('入仓成功')
            this.$tab.closePage()
          })
        }
      })
    },
    handleWarehousing(index) {
      this.warehousing = {...this.order.orderItemVOList[index], ...this.orderItemList[index]}
      this.warehousingVisible = true
    },
    handleWarehousingReturn(item){
      this.$confirm(item.prodTitleZh + '退仓后不可恢复，是否确认退仓？', '确定要退仓？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        rollbackDelete({
          "orderId": item.orderId,
          "orderItemId": item.orderItemId
        }).then(() => {
          this.$message({
            type: 'success',
            message: '货物退仓成功!'
          });

          getOrderWarehouseIn(this.orderId).then(r => this.orderItemList = r.data.reverse())
          this.getOrder()
        })

      }).catch(e => {
      });
    }
  },

  watch: {
    warehousingVisible(val) {
      if (!val){
        this.getOrder()
        getOrderWarehouseIn(this.orderId).then(r => this.orderItemList = r.data.reverse())
      }
    },
    orderSpecialNeeds(val){
      val.forEach(e => {
        this.form.orderSpecialNeedReceivableReqVoList.push({
          "id": e.id,
          "receivableMoney": e.transFee || '',
          "receivableMoneyCurrency": e.transCurrency || 3
        })
      })
    }
  },

  computed: {
    // isAdd() {
    //   return this.$route.path === "/order/warehousing-add"
    // },
    isEdit() {
      return this.$route.path === "/order/warehousing-update"
    },
    title() {
      return 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})
        }
      })
      return result
    },
    cityId(){
      return  this.order?.departureVO?.departureId
    }
  }
}
</script>

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