<template>
  <div class="app-container" v-if="order">
    <el-card class="card">
      <div slot="header" class="card-title">
        {{$t('订单编号')}}:{{order.orderNo}}
        <template v-if="order.tidanNo"> - {{order.tidanNo}}</template>
        <template v-else-if="order.containerNumber"> - {{order.containerNumber}}</template>
      </div>
      <el-row :gutter="20">
        <el-col :span="8" v-if="order.consignorVO">
          <el-descriptions class="margin-top" border :title="$t('发货人')" :column="1" :labelStyle="{width:'150px'}">
            <el-descriptions-item :label="$t('发货人')">{{order.consignorVO.name}}</el-descriptions-item>
            <el-descriptions-item :label="$t('发货人电话')">
              +{{order.consignorVO.countryCode}} {{order.consignorVO.phone}}
            </el-descriptions-item>
            <el-descriptions-item :label="$t('发货人邮箱')">{{order.consignorVO.email}}</el-descriptions-item>
            <el-descriptions-item :label="$t('发货人公司名称')">
              {{order.consignorVO.company}}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="16" v-if="order.consigneeVO">
          <el-descriptions class="margin-top" border :title="$t('收货人')" :column="2" :labelStyle="{width:'150px'}">
            <el-descriptions-item :label="$t('收货人')">{{order.consigneeVO.name}}</el-descriptions-item>
            <el-descriptions-item :label="$t('收货人电话')">
              +{{order.consigneeVO.countryCode}} {{order.consigneeVO.phone}}
            </el-descriptions-item>
            <el-descriptions-item :label="$t('收货人邮箱')">{{order.consigneeVO.email}}</el-descriptions-item>
            <el-descriptions-item :label="$t('收货人公司名称')">
              {{order.consigneeVO.company}}
            </el-descriptions-item>
            <el-descriptions-item :label="$t('收货方式')">
              <dict-tag :type="DICT_TYPE.ECW_HARVEST_METHOD" :value="order.consigneeVO.harvestMethod" />
            </el-descriptions-item>
            <el-descriptions-item :label="$t('收货地区')">
              {{region}}
            </el-descriptions-item>
            <el-descriptions-item :label="$t('收货地址')">
              {{order.consigneeVO.address}}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <el-descriptions class="margin-top" border :column="1" :labelStyle="{width:'150px'}">
        <el-descriptions-item :label="$t('付款人')">
         
          <el-link v-if="order.drawee == 3" @click.native="showDarweeDialog=true" type="primary">自定义</el-link>
          <dict-tag v-else :type="DICT_TYPE.DRAWEE" :value="order.drawee"></dict-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="card">
      <el-descriptions border :title="$t('物流信息')" :column="2">
        <el-descriptions-item :label="$t('始发仓')">{{order.logisticsInfoDto.startTitleZh}}</el-descriptions-item>
        <el-descriptions-item :label="$t('目的仓')">{{order.logisticsInfoDto.destTitleZh}}</el-descriptions-item>
        <!-- <el-descriptions-item :label="$t('地址')" :span="2">{{order.logisticsInfoDto.startAddressZh}}</el-descriptions-item> -->
        <el-descriptions-item :label="$t('运输方式')" :span="2">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="order.transportId" />
        </el-descriptions-item>
        <el-descriptions-item :label="$t('出货渠道')" :span="2">{{channelName}}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="card">
      <el-descriptions class="mr-10" border :title="$t('基础信息')" :column="2">
        <el-descriptions-item :label="$t('唛头')">{{order.marks}}</el-descriptions-item>
        <el-descriptions-item :label="$t('送货时间')" v-if="!order.isExternalWarehouse">{{order.deliveryDate}}</el-descriptions-item>
        <el-descriptions-item :label="$t('是否控货')">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="order.isCargoControl" />
        </el-descriptions-item>
        <el-descriptions-item :label="$t('填单信息')">
          {{order.costVO.totalNum}}{{$t('箱')}}
          {{order.costVO.totalWeight}}Kg
          {{order.costVO.totalVolume}}m³
          {{order.costVO.totalQuantity}}{{$t('个')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('仓库实测')">
          {{order.sumNum}}{{$t('箱')}}
          {{order.sumWeight}}Kg
          {{order.sumVolume}}m³
          {{order.sumQuantity}}{{$t('个')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('收款数据')">
          {{order.sumNum}}{{$t('箱')}}
          {{order.vweight}}Kg
          {{order.wvolume}}m³
          {{order.sumQuantity}}{{$t('个')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('入仓类型')">
          <dict-tag :type="DICT_TYPE.ECW_WAREHOUSING_TYPE" :value="order.warehouseType" />
        </el-descriptions-item>
        <el-descriptions-item :label="$t('单证报关')">
          <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="order.customsType" />
        </el-descriptions-item>
        <el-descriptions-item :label="$t('出单方式')">
          <dict-tag :type="DICT_TYPE.ECW_SUING_METHOD" :value="order.issuingMethod" />
        </el-descriptions-item>
        <el-descriptions-item :label="$t('代收货款')">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="order.isCollection" />
          <template v-if="order.isCollection == 1">({{order.collectionProxy}}{{currencyMap[order.collectionProxyCurrency]}})</template>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('集运仓库')">
          {{order.isExternalWarehouse ? $t('外部仓') : $t('自有仓') }}
          <template v-for="(item, index) in order.externalWarehouseDtoList" >
            <div v-if="item.estLoadingTime || item.loadingAddress" :key="index">
              {{$t('装柜时间')}}: {{item.estLoadingTime}}
              {{$t('装柜地址')}}:{{item.loadingAddress}}
            </div>
          </template>

        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="card">
      <el-tabs v-model="activeName">
        <el-tab-pane :label="$t('货物详情')" name="first">
          <el-table :data="order.orderItemVOList" border style="width: 100%">
            <el-table-column :label="$t('序号')" width="90px">
              <template slot-scope="scope">{{scope.$index + 1}}</template>
            </el-table-column>
            <el-table-column prop="prodTitleZh" :label="$t('中文品名')" />
            <el-table-column prop="prodTitleEn" :label="$t('英文品名')" />
            <el-table-column prop="brand" :label="$t('品牌')"  width="90px">
              <template slot-scope="{row}">
                <template v-if="row.brandName">{{row.brandName}}</template>
                <dict-tag v-else :type="DICT_TYPE.ECW_IS_BRAND" :value="row.brandType" />
              </template>
            </el-table-column>
            <el-table-column prop="num" :label="$t('填单件数')"  width="90px"/>
            <el-table-column prop="sumNum" :label="$t('入仓件数')"  width="90px">
              <template slot-scope="{row}">
                <el-link type="primary" @click.native="showWarehouseLogs(row)">{{row.warehouseInInfoVO ? row.warehouseInInfoVO.cartonsNum : 0}}</el-link>
                <div v-if="row.warehouseInInfoVO && row.warehouseInInfoVO.isMultiSpecification">({{$t('多规格')}})</div>
              </template>
            </el-table-column>
            <el-table-column prop="unit" :label="$t('单位')" width="90px">
              <template slot-scope="{row}">
                <dict-tag :type="DICT_TYPE.ECW_PACKAGING_TYPE" :value="row.unit" />
              </template>
            </el-table-column>

            <el-table-column prop="worth" :label="$t('货值')"  width="120px"/>
            <el-table-column prop="" :label="$t('材质')">
              <template slot-scope="{row}">
                <dict-tag :type="DICT_TYPE.ECW_PRODUCT_MATERIAL" :value="row.material" />
              </template>
            </el-table-column>
            <el-table-column prop="volume" :label="$t('体积') + '(m³)'"  width="90px">
              <template slot-scope="{row}">
                {{order.inWarehouseState > 1 && row.warehouseInInfoVO ? row.warehouseInInfoVO.volume : row.volume}}
              </template>
            </el-table-column>
            <el-table-column prop="weight" :label="$t('重量') + '(kg)'"  width="90px">
              <template slot-scope="{row}">
                {{order.inWarehouseState > 1 && row.warehouseInInfoVO ? row.warehouseInInfoVO.weight : row.weight}}
              </template>
            </el-table-column>
            <el-table-column prop="warehouseInInfoVO.quantityAll" :label="$t('数量') + '(个)'"  width="90px">
              <template slot-scope="{row}">
                {{(order.inWarehouseState > 1 && row.warehouseInInfoVO) ? row.warehouseInInfoVO.quantityAll : row.quantity}}
              </template>
            </el-table-column>
            <el-table-column prop="" :label="$t('费用类型')">
              <template slot-scope="{row}">
                <dict-tag :type="DICT_TYPE.ECW_PAY_ADVANCE" :value="row.isPayAdvance" />
              </template>
            </el-table-column>
            <el-table-column prop="" :label="$t('成交单价')"  width="220px">
              <template slot-scope="{row}">

                <template v-if="row.charging ==1">
                  <template v-if="!row.seaFreight">未报价</template>
                  <el-link type="primary" @click="showFeeDetail(row, 'clearance')" v-else>{{$t('全包价')}} {{row.oneSeaFreight}} {{currencyMap[row.seaFreightCurrency]}} / {{unitMap[row.seaFreightVolume]}}</el-link>
                </template>
                <template v-else-if="!row.seaFreight && !row.clearanceFreight">未报价</template>
                <template v-else>
                  <el-link type="primary" @click="showFeeDetail(row, 'freight')">
                      {{$t('运费')}}:{{row.oneSeaFreight}} {{currencyMap[row.seaFreightCurrency]}} / {{unitMap[row.seaFreightVolume]}}
                  </el-link>
                  <el-link type="primary" @click="showFeeDetail(row, 'clearance')">
                      {{$t('清关费')}}:{{row.oneClearanceFreight}} {{currencyMap[row.clearanceFreightCurrency]}} / {{unitMap[row.clearanceFreightVolume]}}
                  </el-link >
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane :label="$t('订单动态')" name="second">
          <el-timeline v-if="order.orderTimeVOList && order.orderTimeVOList.length" :reverse="true">
            <el-timeline-item v-for="(activity, index) in order.orderTimeVOList" :key="index" :timestamp="activity.timestamp">
              {{ activity.titleZh }}
            </el-timeline-item>
          </el-timeline>
          <el-result v-else icon="info " :title="$t('暂无数据')" :subTitle="$t('暂无订单动态数据')" />
        </el-tab-pane>
        <el-tab-pane :label="$t('运单资料/提货单')" name="three">
          <!--inWarehouseState 1待入库,2多了,3少了,4到齐-->
          <el-button type="text" @click="showWarehouseReceipt=true" :disabled="order.inWarehouseState == 0 && order.shipmentState == 0">{{$t('查看入仓单')}}</el-button>
          <el-button type="text" @click.native="showLadingBill=true" :disabled="!order.ladingState">{{$t('查看提货单')}}</el-button>
          <el-button :disabled="!order.packingListUrl" type="text" @click="downloadPackingList">{{$t('装箱单')}}</el-button>
        </el-tab-pane>
        <el-tab-pane :label="$t('费用明细')" name="four">
          <el-table :data="feeList">
            <el-table-column :label="$t('订单号')" prop="orderNo"></el-table-column>
            <el-table-column :label="$t('运输方式')">
              <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="order.transportId" />
            </el-table-column>
            <el-table-column :label="$t('出货渠道')">
              {{channelName}}
            </el-table-column>
            <el-table-column :label="$t('始发地')" prop="orderNo">
              {{departure.titleZh || '-'}}
            </el-table-column>
            <el-table-column :label="$t('目的地')">
              {{objective.titleZh || '-'}}
            </el-table-column>
            <el-table-column :label="$t('品名')" prop="titleZh"></el-table-column>
            <el-table-column :label="$t('箱数')" prop="num">
              <template slot-scope="{row}">
                {{row.num || '-'}}
              </template>
            </el-table-column>
            <el-table-column :label="$t('体积/重量')">
              <template slot-scope="{row}">
               {{row.volume || '-'}} / {{row.weight || '-'}}
              </template>
            </el-table-column>
            <el-table-column :label="$t('收款类型')">
              <template slot-scope="{row}">
                <dict-tag :type="DICT_TYPE.PAYMENT_TYPE" :value="row.collectionType" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('收入类型')">
              <template slot-scope="{row}">
                <dict-tag :type="DICT_TYPE.FEE_TYPE" :value="row.feeType" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('单价金额')" prop="unitPrice">
              <template slot-scope="{row}">
                {{row.unitPrice}}{{currencyMap[row.currencyId]}}
              </template>
            </el-table-column>
            <el-table-column :label="$t('总金额')" prop="totalAmount">
              <template slot-scope="{row}">
                {{row.totalAmount}}{{currencyMap[row.currencyId]}}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <print-warehouse-receipt v-if="showWarehouseReceipt" :order-id="order.orderId" @close="showWarehouseReceipt=false" />
    <print-lading-bill v-if="showLadingBill" :order-id="order.orderId" :transport-type="order.transportId" @close="showLadingBill=false" />
    <warehouse-detail :order="order" :orderItemId="showWarehouseInItemId" v-if="showWarehouseInItemId" @close="showWarehouseInItemId=null" />
    <el-dialog :title="$t('付款人')" :visible.sync="showDarweeDialog" v-if="order && order.customDraweeVOList">
      <el-table :data="order.customDraweeVOList" v-if="order.drawee==3" >
        <el-table-column :label="$t('费用类型')" prop="label" width="200px">
          <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_CUSTOM_DRAWEE" :value="row.name"/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('付款人')" width="300px">
            <template slot-scope="{row}">
                <dict-tag :type="DICT_TYPE.DRAWEE" :value="row.value" />
            </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="$t('费用详情')" :visible="!!showFeeDetailDialog" :before-close="closeFeeDetail">
      <el-row v-if="feeDetail">
        <el-col :span="12">
          <div>{{feeDetail.charging ? $t('全包价') : $t('运费')}}</div>
          <div v-for="item in feeDetail.freight">
            {{item.label}}: {{item.value}} 
            <template v-if="item.currency">
              {{currencyMap[item.currency]}} / {{unitMap[item.volume]}} <span v-if="item.remark">【{{item.remark}}】</span>
            </template>
          </div>
        </el-col>
        <el-col :span="12" v-if="feeDetail.charging != 1">
          <div>{{$t('清关费')}}</div>
          <div v-for="item in feeDetail.clearance">
            {{item.label}}: {{item.value}}
            <template v-if="item.currency">
              {{currencyMap[item.currency]}} / {{unitMap[item.volume]}} <span v-if="item.remark">【{{item.remark}}】</span>
            </template>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getOrder } from '@/api/ecw/order'
import { getDictDatas, DICT_TYPE } from '@/utils/dict';
import PrintWarehouseReceipt from './components/PrintWarehouseReceipt'
import PrintLadingBill from './components/PrintLadingBill'
import {getUnitList} from '@/api/ecw/unit'
import {getCurrencyList} from '@/api/ecw/currency'
import {getReceivableListByOrderId} from '@/api/ecw/receipt'
import { getChannel } from '@/api/ecw/channel';
import {listByIds} from '@/api/ecw/region'
import WarehouseDetail from './components/WarehouseDetail';
import {getProductBrank} from '@/api/ecw/productBrank'
import { parseTime } from '@/utils/ruoyi';

export default {
  name: "detail",
  components: {
    PrintWarehouseReceipt, PrintLadingBill, WarehouseDetail
  },
  filters: {
    customsTypeFilter(e, customsTypeList) {
      if (e) return customsTypeList.find(item => item.value == e).label
    },
    transportFilter(e, transportList) {
      if (e) return transportList.find(item => item.value == e).label
    }
  },
  data() {
    return {
      showDarweeDialog: false,
      // 遮罩层
      loading: false,
      order: null,
      activeName: 'first',
      orderId: 17,
      tableData: [],
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      activities: [],
      customsTypeList: getDictDatas(DICT_TYPE.ECW_CUSTOMS_TYPE), //报关类型
      transportList: getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE), //运输方式
      showWarehouseReceipt: false, // 是否显示打印入仓单
      showLadingBill: false, // 是否显示打印提单
      currencyList: [],
      unitList:[],
      feeList: [],
      channelName: '/',
      region: '',
      orderWarehouseIn: null, // 入仓详情
      showWarehouseInItemId: null, // 当前显示的入仓
      showFeeDetailDialog: null, // 是否显示费用详情弹层
      feeDetail: null, // 费用详情
    }
  },
  computed:{
    currencyMap(){
        let map = {}
        this.currencyList.forEach(item => {
            map[item.id] = item.titleZh
        })
        return map
    },
    unitMap(){
        let map = {}
        this.unitList.forEach(item => {
            map[item.id] = item.titleZh
        })
        return map
    },
    objective(){
      if(this.order && this.order.objectiveVO){
        return JSON.parse(this.order.objectiveVO.objective)
      }
      return {}
    },
    departure(){
      if(this.order && this.order.departureVO){
        return JSON.parse(this.order.departureVO.departure)
      }
      return {}
    }
  },
  watch:{
    activeName(val){
      if(!this.feeList.length && val == 'four'){
        this.loadFeeList()
      }
    },
    'order.channelId'(){
      this.getChannel()
    },
    'order.consigneeVO'(val){
      if(!val) return '-'
      listByIds({ids: [val.country, val.province, val.city].join(',')}).then(res => {
        console.log('listById', res)
        let region = ''
        res.data.forEach(item => {
          region += " " + item.titleZh
        })
        this.region = region
      })
    }
  },
  created() {
    if (this.$route.query.orderId) {
      this.orderId = this.$route.query.orderId
      this.getOrder();
    }

    getCurrencyList().then(res => this.currencyList = res.data)
    getUnitList().then(res => this.unitList = res.data)
  },
  methods: {
    // 显示费用详情
    showFeeDetail(row, type){
      this.showFeeDetailDialog = true
      const freight = [], clearance = []

      let freightFields = []
      let clearanceFields = []

      const brandType = row.warehouseInInfoVO ? row.feeType : row.brandType
      // 不是特价则显示其他字段
      freightFields = [
        // {field: 'oneSeaFreight', label: '成交单价'},
        {field: 'originalSeaFreight', label: this.$t('默认单价(无牌无液无电)')},
        // {field: 'brandFreightPrice', label: this.$t('品牌加价')},
        {field: 'liquidFreightPrice', label: this.$t('液体加价')},
        {field: 'electrifiedFreightPrice', label: this.$t('带电加价')},
        {field: 'discountFreightPrice', label: this.$t('优惠活动减免')},
        {field: 'plainCommission', label: this.$t('明佣')}
      ]

      // 品牌加价
      if(row['brandFreightPrice'] && row['brandFreightPrice'] > 0){
        freightFields.push({field: 'brandFreightPrice', label: brandType == 1 ? this.$t('有品牌加价') : this.$t('中性品牌加价')})
      }

      // 有减免金额才显示优惠后单价
      if(row['discountFreightPrice'] && row['discountFreightPrice'] > 0){
        freightFields.push({field: 'afterDiscountSeaFreight', label: this.$t('优惠后单价')})
      }
      freightFields.push({field: 'oneSeaFreight', label: this.$t('成交单价')})
      console.log({freightFields})
      freightFields.forEach(item => {
        if(row[item.field]){
          freight.push({
            label: item.label,
            value: row[item.field],
            currency: row.seaFreightCurrency,
            volume: row.seaFreightVolume,
            remark: row.specialPriceType && item.field == 'oneSeaFreight' ? this.$t('特价') : null
          })
        }
      })

      clearanceFields = [
        {field: 'originalClearanceFreight', label: this.$t('默认单价(无牌无液无电)')},
        // {field: 'brandClearanceFeePrice', label: this.$t('品牌加价')},
        {field: 'liquidClearanceFeePrice', label: this.$t('液体加价')},
        {field: 'electrifiedClearanceFeePrice', label: this.$t('带电加价')},
        {field: 'discountClearanceFeePrice', label: this.$t('优惠活动减免')}
      ]
      // 品牌加价
      if(row['brandClearanceFeePrice'] && row['brandClearanceFeePrice'] > 0){
        freightFields.push({field: 'brandClearanceFeePrice', label: brandType == 1 ? this.$t('有品牌加价') : this.$t('中性品牌加价')})
      }
      if(row['discountClearanceFeePrice'] && row['discountClearanceFeePrice'] > 0){
        clearanceFields.push({field: 'afterDiscountClearanceFreight', label: this.$t('优惠后单价')})
      }
      clearanceFields.push({field: 'oneClearanceFreight', label: this.$t('成交单价')})
      clearanceFields.forEach(item => {
        if(row[item.field]){
          clearance.push({
            label: item.label,
            value: row[item.field],
            currency: row.clearanceFreightCurrency,
            volume: row.clearanceFreightVolume,
            remark: row.specialPriceType && item.field == 'oneClearanceFreight' ? this.$t('特价') : null
          })
        }
      })
    

      freight.push({
        label: '价格更新时间',
        value: parseTime(row.updateTime)
      })
      clearance.push({
        label: '价格更新时间',
        value: parseTime(row.updateTime)
      })
      this.feeDetail = {freight, clearance, charging: row.charging}

    },
    closeFeeDetail(){
      this.showFeeDetailDialog = null
    },
    /** 查询列表 */
    getOrder() {
      let that = this
      that.loading = true;
      // 执行查询
      getOrder(that.orderId).then(response => {
        that.order = response.data;
        // this.loadBrand()
      });
    },
    /* loadBrands(){
      let brandIds = []
      this.form.orderItemVOList.forEach(item => {
        if(item.brand){
          brandIds.push(item.brand)
        }
      })
      if(!brandIds.length) return
      Array.form(new Set(brandIds)).forEach(brandId => {
        getProductBrank(brandId).then(res => {
          this.brands.push(res.dat)
        })
      })
    }, */
    getChannel(){
      if(!this.order || !this.order.channelId || this.order.transportId == 1 || this.order.transportId == 2) return
      getChannel(this.order.channelId).then(res => {
        this.channelName = res.data.nameZh
      })
    },
    loadFeeList(){
      getReceivableListByOrderId({id: this.orderId}).then(res => {
        this.feeList = res.data
      })
    },
    downloadPackingList(){
      window.open(this.order.packingListUrl)
    },
    // 显示入仓记录
    showWarehouseLogs(row){
      this.showWarehouseInItemId = row.orderItemId
    },
    getWarehouseIn(){
      getOrderWarehouseIn(this.order.id).then(res => {
        this.orderWarehouseIn = res.data
      })
    }
  }
};
</script>

<style scoped>
.card {
  margin-bottom: 20px;
}
.card-title{
  font-size: 18px;
  font-weight: bold;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>