<template>
  <div class="app-container">
        <el-card>
            <div slot="header" class="card-title">{{$t('报价单详情')}}</div>
          <!-- 列表 -->
          <div class="offer-header">
              <span style="font-size: 15px;">{{$t('报价单号')}}：{{list.number}}</span>
              <div class="btns">
                <el-button v-hasPermi="['ecw:offer:update']" size="mini" type="primary" v-if="[4,5,6].indexOf(list.status) == -1"  @click="$router.push('edit?id=' + offerId)">{{$t('编辑')}}</el-button>
                <el-button v-hasPermi="['ecw:offer:loglist']" type="primary" v-if="[1,3,7].indexOf(list.status) > -1"  size="mini" @click="handleAdd">{{$t('跟进')}}</el-button>
                <el-button v-hasPermi="['ecw:offer:result']" type="primary"  v-if="[3,7].indexOf(list.status) > -1" size="mini" @click="toResult">{{$t('结果')}}</el-button>
                <el-button v-hasPermi="['ecw:offer:discount','ecw:offer:commission']" size="mini" v-if="[1,3,7].indexOf(list.status) > -1" type="primary" @click.native="$router.push('/offer/special?offerId=' + offerId)" >{{$t('特价')}}</el-button>
                <el-button v-hasPermi="['ecw:offer:delete']" type="danger" size="mini" @click="handleDelete">{{$t('删除')}}</el-button>
              </div>
          </div>
          <div>
            <div class="title-font">
              <label>{{$t('报价单所属')}}：{{list.relation?list.relation==1?$t('发货人'):$t('收货人'):$t('发货人')}}</label>
            </div>
                <el-descriptions :column="3" border class="card" v-if="list.consignorId">
                    <el-descriptions-item :label="$t('发货人')+':'">
                        {{consignorData.contactsName||$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('手机号')+':'">
                      {{consignorData && consignorData.phoneNew ? (checkCode(consignorData.areaCode) + consignorData.phoneNew)||$t('无'):$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('联系地址')+':'">
                      {{consignorData.address||$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('客户来源')+':'">
                          {{consignorData.source||$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('发货人公司名称')+':'">
                      {{consignorData.company||$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('社交软件')+':'">
                       <dict-tag :type="DICT_TYPE.SOCIAL" :value="consignorData.social" />
                       {{consignorData.socialNumber?('('+consignorData.socialNumber+')'):''}}
                    </el-descriptions-item>
                </el-descriptions>

               <el-descriptions :column="3" border class="card" v-if="list.consigneeId">
                   <el-descriptions-item :label="$t('收货人')+':'">
                    {{consigneeData.contactsName||$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('手机号')+':'">
                      {{consigneeData && consigneeData.phoneNew ?(checkCode(consigneeData.areaCode)+consigneeData.phoneNew)||$t('无'):$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('联系地址')+':'">
                      {{consigneeData.address||$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('客户来源')+':'">
                          {{consigneeData.source||$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('发货人公司名称')+':'">
                      {{consigneeData.company||$t('无')}}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('社交软件')+':'">
                       <dict-tag :type="DICT_TYPE.SOCIAL" :value="consigneeData.social" />
                       {{consigneeData.socialNumber?('('+consigneeData.socialNumber+')'):''}}
                    </el-descriptions-item>
               </el-descriptions>
                <el-descriptions :column="4" class="card">
                    <el-descriptions-item :label="$t('运输方式')">
                         <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="list.transportId" />
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('出货渠道')" v-if="[3,4].indexOf(list.transportId) > -1">
                      {{channelName}}
                    </el-descriptions-item>
                 </el-descriptions>
                 <el-descriptions :column="4" class="card">
                     <el-descriptions-item :label="$t('始发城市')">
                        {{getCity(list.departureId)}}
                     </el-descriptions-item>
                     <el-descriptions-item :label="$t('目的城市')">
                        {{getCity(list.objectiveId)}}
                     </el-descriptions-item>
                  </el-descriptions>
                <el-descriptions :column="4" class="card">
                    <el-descriptions-item :label="$t('线路')">
                      {{getRouterNameById(list.lineId)}}
                    </el-descriptions-item>
                 </el-descriptions>
                 <el-descriptions :column="4" class="card">
                     <el-descriptions-item :label="$t('报价单状态')">
                       <dict-tag :type="DICT_TYPE.ECW_OFFER_STATUS" :value="list.status" />
                     </el-descriptions-item>
                  </el-descriptions>
                  <el-descriptions :column="4" class="card" v-if="list.status==5">
                      <el-descriptions-item :label="$t('输单原因')">
                        {{list.reason}}
                      </el-descriptions-item>
                   </el-descriptions>

          </div>
        </el-card>

        <el-card class="card">
          <div slot="header" class="card-title">{{$t('商品信息')}}</div>
          <div style="overflow: auto;">
          <el-table v-loading="loading" border :data="list.offerProdRespVOList">
                <el-table-column :label="$t('序号')" width="60px" fixed>
                  <template slot-scope="scope">
                      {{scope.$index + 1}}
                  </template>
                </el-table-column>
<!--                <el-table-column :label="商品类型" align="center" prop="goodsType" /> -->
                <el-table-column :label="$t('中文品名')" align="center" prop="prodTitleZh" />
                <el-table-column :label="$t('英文品名')" align="center" prop="prodTitleEn" />
                <el-table-column :label="$t('品牌')" width="100px">
                  <template slot-scope="scope">
                      <dict-tag :value="scope.row.brand" :type="DICT_TYPE.ECW_IS_BRAND" defaultable />
                  </template>
                </el-table-column>
                <el-table-column :label="$t('件数')" width="90px" prop="num" />
                <el-table-column :label="$t('包装单位')">
                  <template slot-scope="scope">
                      <dict-tag :value="scope.row.unit" :type="DICT_TYPE.ECW_PACKAGING_TYPE" defaultable />
                  </template>
                </el-table-column>
                <!-- <el-table-column :label="$t('箱规') + '(m)'" width="120px" prop="boxGauge" /> -->
                <el-table-column :label="$t('体积') + '(m³)'" width="100px" prop="volume" />
                <el-table-column :label="$t('数量')" width="100px" prop="quantity" />
                <el-table-column :label="$t('重量') + '(kg)'" width="100px" prop="weight" />
                <el-table-column :label="$t('货值') + '(RMB)'" width="100px" prop="worth" />
                <el-table-column :label="$t('商品特性')" width="200px" prop="prodAttrName" />
                 <el-table-column :label="$t('是否预付')">
                   <template slot-scope="scope">
                      {{scope.row.isPayAdvance==1?$t('预付'):$t('到付')}}
                   </template>
                 </el-table-column>

                <el-table-column :label="$t('成交价')" width="200px">
                  <template slot-scope="{row}">
                    <template v-if="row.charging ==1">
                      <template v-if="!row.seaFreight">{{ $t('未报价') }}</template>
                      <template>{{$t('全包价')}} {{row.oneSeaFreight}} {{currentcyMap[row.seaFreightCurrency]}} / {{unitMap[row.seaFreightVolume]}}</template>
                    </template>
                    <template v-else-if="!row.seaFreight && !row.clearanceFreight">{{ $t('未报价') }}</template>
                    <template v-else>
                      <div>
                          {{$t('运费')}}：{{row.oneSeaFreight}} {{currentcyMap[row.seaFreightCurrency]}} / {{unitMap[row.seaFreightVolume]}}
                      </div>
                      <div>
                          {{$t('清关费')}}：{{row.oneClearanceFreight}} {{currentcyMap[row.clearanceFreightCurrency]}} / {{unitMap[row.clearanceFreightVolume]}}
                      </div>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
              </div>
        </el-card>
        <el-card class="card">
          <div slot="header" class="card-title">{{$t('费用小计')}}</div>
            <el-descriptions border class="card" :column="5">
              <el-descriptions-item :label="$t('总件数')+':'">
                  {{list.estCostVO?list.estCostVO.totalNum||'0':0}}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('总体积')+':'">
                {{list.estCostVO?(list.estCostVO.totalVolume+'m³')||'0':0}}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('总重量')+':'">
                {{list.estCostVO?(list.estCostVO.totalWeight+'kg')||'0':0}}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('总数量')+':'">
                {{list.estCostVO?list.estCostVO.totalQuantity||'0':0}}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('总货值(RMB)')+':'">
                  {{list.estCostVO?list.estCostVO.totalWorth||'0':0}}
              </el-descriptions-item>
<!--              <el-descriptions-item :label="报价费：">
                {{list.estCostVO?list.estCostVO.insuranceFee||'0':0}}
              </el-descriptions-item> -->
          </el-descriptions>
<!--          <el-descriptions border class="card">
            <el-descriptions-item :label="佣金类型" :span="2" class="card">
                <dict-selector :type="DICT_TYPE.COMMISSION_TYPE" form-type="radio" fomtter="number"  :value="list.commissionType" defaultable />
            </el-descriptions-item>
          </el-descriptions> -->
        </el-card>
        <el-card class="mt-10">
            <div class="card-title" slot="header">{{$t('预计费用')}}</div>

            <el-descriptions :column="5" border>
                <el-descriptions-item :label="$t('保价费')">
                    {{list.estCostVO?list.estCostVO.insuranceFee: 0}} {{$t('美元')}}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('总运费')">
                    <template v-if="freightFeeList.length>0" v-for="item in freightFeeList">
                        <div :key="item.currencyId">{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</div>
                    </template>
                </el-descriptions-item>
                <template v-if="freightFeeList.length==0">
                    0
                </template>
                <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
                <el-descriptions-item :label="$t('总清关费')">
                    <template v-if="clearanceFeeList.length>0" v-for="item in clearanceFeeList">
                        <div :key="item.currencyId">{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</div>
                    </template>
                    <template v-if="clearanceFeeList.length==0">
                        0
                    </template>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('其他费用')">
                   <template v-if="otherFeeList.length>0" v-for="item in otherFeeList">
                       <div :key="item.currencyId">{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</div>
                   </template>
                   <template v-if="otherFeeList.length==0">
                       0
                   </template>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('原价')" :span="2">
                    <template v-if="originalFeeList.length>0" v-for="item in originalFeeList">
                        <div :key="item.currencyId">{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</div>
                    </template>
                    <template v-if="originalFeeList.length==0">
                        0
                    </template>
                </el-descriptions-item>
            </el-descriptions>


            <div class="card-title" style="padding:20px 0;">{{$t('优惠信息')}}</div>
            <el-table :data="couponList" :show-header="false">
                <el-table-column label="">
                    <template slot-scope="scope">
                        {{scope.$index+1}}.
                        {{getProductName(scope.row.prodId)}}
                    </template>
                </el-table-column>
                <el-table-column label="">
                    <template slot-scope="{row}">
                      <dict-tag :type="DICT_TYPE.ECW_COUPON_TYPE" :value="row.type" />
                    </template>
                </el-table-column>
                <el-table-column label="">
                    <template slot-scope="{row}">
                        {{$l(row, 'title')}}
                    </template>
                </el-table-column>
                <el-table-column label="">
                    <template slot-scope="{row}">
                        -{{row.reduceAmount}}
                        {{currentcyMap[row.reduceCurrencyId]}}
                    </template>
                </el-table-column>
                <el-table-column label="">
                    <template slot-scope="{row}">
                        {{$t('有效期至')}}：{{row.endTime ? row.endTime : $t('永久有效')}}
                    </template>
                </el-table-column>
            </el-table>

            <el-descriptions :column="1" class="mt-20">
                <el-descriptions-item :label="$t('优惠费用')"  v-if="couponTotalAmountList && couponTotalAmountList.length>0">
                    <div v-for="(item, discountIndex) in couponTotalAmountList" :key="discountIndex">
                        {{item.totalAmount}} {{currentcyMap[item.currencyId]}}
                    </div>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('预计费用')">
                    <template >
                      <div style="display:flex;flex-direction:column">
                        <div v-for="item in estimatedCosts" :key="item.currencyId">
                          <span>{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</span>
                          </div>
                          </div>
                    </template>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>
        <el-card class="card">
          <div slot="header" class="card-title">{{$t('通用信息')}}</div>
            <el-descriptions :column="4">
              <el-descriptions-item :label="$t('唛头')">
                  {{list.marks||'/'}}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('报关方式')">
                  <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="list.customsType"></dict-tag>
              </el-descriptions-item>
              </el-descriptions>
            <el-descriptions :column="4">
             <el-descriptions-item :label="$t('预计结束时间')">
                  {{list.stopTime||'/'}}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('控货')">
                   {{list.control?$t('是'):$t('否')}}
               </el-descriptions-item>
               <el-descriptions-item :label="$t('竞争对手')">
                  {{list.competitor||'/'}}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('重要程度')">
                    <el-rate v-model="list.importance" disabled></el-rate>
                 </el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="4">
             <el-descriptions-item :label="$t('价格有效期')">
                 {{list.startTime+$t('至')}}{{list.endTime}}
              </el-descriptions-item>
              <el-descriptions-item :label="$t('交货方式')">
                <dict-tag :type="DICT_TYPE.ECW_TRADE_TYPE" :value="list.tradeType"></dict-tag>
                   <span style="margin-left: 10px;">{{list.tradeAdress}}</span>
               </el-descriptions-item>
          </el-descriptions>
          <el-descriptions >
              <el-descriptions-item :label="$t('备注')">
                   {{list.remarks||'/'}}
               </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card class="card" v-if='list.transportVO'>
          <div slot="header" class="card-title">
            <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="list.transportId"></dict-tag>
          </div>
          <div class="line">
            <el-descriptions>
                <el-descriptions-item :label="[3,4].indexOf(list.transportId)>-1?$t('空运路线'):$t('海运路线')">
                    {{getRouterNameById(list.lineId)||'/'}}
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions v-if="[3,4].indexOf(list.transportId) > -1">
               <el-descriptions-item :label="$t('出货渠道')">
                   {{channelName||'/'}}
                </el-descriptions-item>
            </el-descriptions>
          </div>
          <el-descriptions class="card" v-if="[2,3,4].indexOf(list.transportId) > -1">
              <el-descriptions-item :label="$t('是否双清')">
                  <dict-tag :type="DICT_TYPE.ECW_DOUBLE_CLEAR" :value="list.transportVO.doubleClear"></dict-tag>
              </el-descriptions-item>
          </el-descriptions>
          <el-descriptions v-if="[3,4].indexOf(list.transportId) > -1">
              <el-descriptions-item :label="$t('航空公司')">
                 {{airlineCompany ? $l(airlineCompany, 'company') : '/'}}
              </el-descriptions-item>
          </el-descriptions>
          <el-descriptions v-if="list.transportId==2">
              <el-descriptions-item :label="$t('船公司')">
                {{shippingCompany ? $l(shippingCompany, 'company') : '/'}}
              </el-descriptions-item>
          </el-descriptions>
          <el-descriptions v-if="[2,3,4].indexOf(list.transportId) > -1">
              <el-descriptions-item :label="$t('清关证书')">
                 <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="list.transportVO.customsClearCert"></dict-tag>
              </el-descriptions-item>
          </el-descriptions>
          <el-descriptions v-if="[2,3,4].indexOf(list.transportId) > -1">
              <el-descriptions-item :label="$t('清关证书备注')">
                 {{list.transportVO.remarks||'/'}}
              </el-descriptions-item>
          </el-descriptions>
          <el-descriptions class="card" v-if="[3,4].indexOf(list.transportId) > -1">
              <el-descriptions-item :label="$t('是否拆包')">
                 <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="list.transportVO.isUnpack"></dict-tag>
              </el-descriptions-item>
          </el-descriptions>
          <el-descriptions v-if="[3,4].indexOf(list.transportId) > -1">
              <el-descriptions-item :label="$t('单票立刻转运')">
                <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="list.transportVO.isSingleTicketTransport"></dict-tag>

                   <span style="margin-left:10px;color: #0000FF;">{{$t('注：若只有一件，货到仓库立即发，选“是”，多件需仓库集运待发，选“否”')}}</span>
              </el-descriptions-item>

          </el-descriptions>
          <el-descriptions>
              <el-descriptions-item :label="$t('特殊要求')">
                 <dict-selector  form-type="checkbox"  :type="DICT_TYPE.ORDER_SPECIAL_NEEDS" multiple  v-model="list.transportVO.packageType" :disabled="true" />
              </el-descriptions-item>
          </el-descriptions>
          <el-descriptions>
              <el-descriptions-item :label="$t('特殊要求备注')">
                {{list.transportVO.packageRemarks||'/'}}
              </el-descriptions-item>
          </el-descriptions>
        </el-card>

  </div>
</template>

<script>
  import {DICT_TYPE,getDictDatas} from  '@/utils/dict'
  import {getOffer,deleteOffer} from '@/api/ecw/offer'
  import {getProductAttrList} from '@/api/ecw/productAttr'
  import {getCustomerList,getCustomer} from '@/api/ecw/customer'
   import {getChannelList,getChannel} from '@/api/ecw/channel'
   import {getTradeCityList} from '@/api/ecw/region'
   import {getUnitList} from '@/api/ecw/unit'
   import { getOrder } from '@/api/ecw/order'
   import {getCurrencyList} from '@/api/ecw/currency'
   import {getCustomerContactsSelect} from '@/api/ecw/customerContacts'
   import {openedRouterList as getOpenedRouterList} from '@/api/ecw/warehouse'
   import {calculationPrice} from '@/api/ecw/product'
   import {getSupplier, getSupplierPage} from '@/api/ecw/supplier'
   import Decimal from 'decimal.js'
   window.Decimal=  Decimal

  export default {
    name: "detail",
    data() {
      return {
        // 遮罩层
        loading: false,
        list: [],
        types:'package,bag',
        importance:1,
        productAttrList:[],
        offerId:0,
        //发货/收货人信息
        consigneeData:{},
        routerList:[],
        fee:{},
        channelName:'/',
        tradeCityList:[],
        productNames: {},
        currencyList:[],
        unitList:[],
        orderData:[],
        consignorData:{},
        customerSource: getDictDatas(DICT_TYPE.CUSTOMER_SOURCE),
        couponAvailableGroupDtoList: [], // 可用优惠
        couponTotalAmountList: [], // 优惠总额
        // 航空公司
        airlineCompany: null,
        // 船公司
        shippingCompany: null,
      };
    },
    computed:{
      // 根据id获取商品名称（显示优惠列表的时候用）
      getProductName(){
        return prodId => {
          if(!this.list) return this.$t('未知')
          let row = this.list.offerProdRespVOList.find(item => item.prodId == prodId)
          if(!row) return this.$t('未知')
          return this.$l(row, 'prodTitle')
        }
      },
      currentcyMap(){
          let map = {}
          this.currencyList.forEach(item => {
              map[item.id] = this.$i18n.locale=='zh_CN'?item.titleZh:item.titleEn
          })
          return map
      },
      unitMap(){
          let map = {}
          this.unitList.forEach(item => {
              map[item.id] = this.$i18n.locale=='zh_CN'?item.titleZh:item.titleEn
          })
          return map
      },
      // 总有优惠金额
    // 总有优惠金额
   // 总有优惠金额
    couponList(){
        let arr = []
        this.couponAvailableGroupDtoList.forEach(item => {
            if(item.couponAvailableDtoList && item.couponAvailableDtoList.length){
                // 只取第一个
                let it = item.couponAvailableDtoList[0]
                arr.push({
                        prodId: item.prodId,
                        type: it.type,
                        titleZh: it.titleZh,
                        titleEn: it.titleEn,
                        endTime: it.endTime,
                        reduceAmount: it.reduceAmount,
                        reduceCurrencyId: it.reduceCurrencyId
                    })
            }
        })
        return arr
    },
      // 计算返回的费用清单
      feeDtoList(){
          if(this.list&&this.list.estCostVO){
            return this.list.estCostVO.feeDtoList || []
          }else{
            return []
          }
      },
      // 清关费
      clearanceFeeList(){
          return this.feeDtoList.filter(item => item.feeType == 2)
      },
      // 运费
      freightFeeList(){
          return this.feeDtoList.filter(item => item.feeType == 1)
      },
      // 其他费用
      otherFeeList(){
          return this.feeDtoList.filter(item => item.feeType == 3)
      },
      // 原价（清关费 + 运费）
      originalFeeList(){
          let arr = []
          this.clearanceFeeList.forEach(item => {
              let it = {...item}
              let freight = this.freightFeeList.find(fee => fee.currencyId == item.currencyId)
              if(freight){
                  it.amount += freight.amount
              }
              arr.push(it)
          })
          this.freightFeeList.forEach(item => {
              if(!arr.find(items=>items.currencyId==item.currencyId)){
                  let its = {...item}
                  // let freights = this.clearanceFeeList.find(fee => fee.currencyId == item.currencyId)
                  // if(freights){
                  //     its.amount += freights.amount
                  // }
                  arr.push(its)
              }

          })

          return arr
      },
      // 预计费用(原价 - 优惠金额)
      estimatedCosts(){
          let arr = []
          let withInsuranceFee = false
          let withOtherFee = false
          this.originalFeeList.forEach(item => {
              let it = {
                  currencyId: item.currencyId,
                  amount: Decimal(item.amount)
              }
              let coupon = this.couponList.find(coupon => coupon.reduceCurrencyId == item.currencyId)
              if(coupon){
                  it.amount = it.amount.minus(coupon.reduceAmount)
              }
              // if(this.list.otherFee && this.list.otherFeeCurrencyId == item.currencyId){
              //     it.amount = it.amount.plus(this.list.otherFee)
              //     withOtherFee = true
              // }
              let otherFee = this.otherFeeList.find(fee => fee.currencyId == item.currencyId)
              if(otherFee){
                  it.amount = it.amount.plus(otherFee.amount || 0)
                  withOtherFee = true
              }
              // 保价费（美元）
              if(item.currencyId == 1 && this.fee && this.fee.insuranceFee){
                  it.amount = it.amount.plus(this.fee.insuranceFee)
                  withInsuranceFee = true
              }
              arr.push(it)
          })

          // 如果没有累加其他费用，则另外增加货币
          if(!withOtherFee && this.list.otherFee){
              let fee = {
                  currencyId: this.list.otherFeeCurrencyId,
                  amount: Decimal(this.list.otherFee)
              }

              // 如果保价费跟其他费用是同一种货币（都是美元）
              if(!withInsuranceFee && this.fee && this.fee.insuranceFee && this.list.otherFeeCurrencyId == 1){
                  fee.amount = fee.amount.plus(this.fee.insuranceFee)
              }
              arr.push(fee)
            }
            // 没有累加保价费(没有美元计价)但是有保价费则需要加上去
            if(!withInsuranceFee && this.fee && this.fee.insuranceFee){
                arr.push({
                    currencyId: 1,
                    amount: Decimal(this.fee.insuranceFee)
                })
            }
            this.otherFeeList.forEach(item => {
                if(!arr.find(items=>items.currencyId==item.currencyId)){
                    let its = {...item}
                    // let freights = this.clearanceFeeList.find(fee => fee.currencyId == item.currencyId)
                    // if(freights){
                    //     its.amount += freights.amount
                    // }
                    arr.push(its)
                }

            })
            return arr
      }
    },
    created() {
      getCurrencyList().then(res => this.currencyList = res.data)
      getUnitList().then(res => this.unitList = res.data)
      getTradeCityList().then(res => this.tradeCityList = res.data)
      getProductAttrList().then(res => this.productAttrList = res.data)
      if(this.$route.query.offerId){
        this.offerId = this.$route.query.offerId
        this.getList();
      }
    },
    methods: {
      sourceLabel(data){
        let label=''
        var source = this.customerSource.find(item=>item.value==data)
        if(source) label = this.$i18n.locale=='zh_CN'?source.label:source.labelEn
        return label
      },
      checkCode(data){
        if(!data){
          return ''
        }
        if(data.indexOf('+')==-1){
        	return '+'+data
        }
        return data
      },
      getOrderData(id) {
        let that = this
        that.loading = true;
        // 执行查询
        getOrder(id).then(response => {
          that.orderData = response.data;
        });
      },
      getProductListWithDefaultValue(){
          let arr = []
          this.list.offerProdRespVOList.forEach(item => {
              let tmp = {
                "brand":item.brand,
                "unit":item.unit,
                "prodId":item.prodId,
                "num":item.num,
                "quantity":item.quantity,
                "volume":item.volume,
                "weight":item.weight,
                "worth":item.worth,
                "brandType":item.brandType||0,
                "prodAttrIds":item.prodAttrIds
              }
              arr.push(tmp)
          })
          return arr
      },
      // 计算商品运费
      calculationPrice(){
          calculationPrice({
              lineId: this.list.lineId,
              transportId: this.list.transportId,
              channelId: this.list.channelId,
              prodConditionParamList: this.getProductListWithDefaultValue(),
              consigneeCustomerContactsId: this.list.consigneeCustomerContactsId,
              consignorCustomerContactsId: this.list.consignorCustomerContactsId,
              customsType: this.list.customsType,
              isCargoControl: this.list.control,
              orderType: this.list.orderType,
          }).then(res => {
              this.$set(this, 'fee', res.data.costDto)
              if(res.data.availableDto){
                this.$set(this, 'couponTotalAmountList', res.data.availableDto.couponTotalAmountList)
                this.$set(this, 'couponAvailableGroupDtoList', res.data.availableDto.couponAvailableGroupDtoList)
              }
          }).finally(() => {
              this.calculating = false
          })
      },
      /** 查询列表 */
      getList() {
        let that = this
        that.loading = true;
        // 执行查询
        getOffer(that.offerId).then(response => {
          that.list = response.data;
          if(that.list.channelId){
            that.getChannelData()
          }
          that.calculationPrice()
          // if(that.list.orderId){
          //   that.getOrderData(that.list.orderId)
          // }
          getCustomerContactsSelect({ids: [that.list.consignorId, that.list.consigneeId].join(',')}).then((res) => {
               let consignor = res.data.list.find(item => item.customerContactsId == that.list.consignorId)
               if(consignor) that.consignorData=consignor
               let consignee = res.data.list.find(item => item.customerContactsId == that.list.consigneeId)
               if(consignee) that.consigneeData=consignee
               that.getCnsigneeData()
          })
          that.list.offerProdRespVOList.forEach((item)=>{
            var arr = item.prodAttrIds.split(',')
            var prodAttrName = []
            arr.forEach((itemValue)=>{
                 var prodAttrCenter = this.productAttrList.filter(items=>items.id==itemValue)
                 if(prodAttrCenter.length>0){
                   prodAttrName.push(this.$i18n.locale=='zh_CN'?prodAttrCenter[0].attrName:prodAttrCenter[0].attrNameEn)
                 }
            })
            if(prodAttrName.length>1){
              item.prodAttrName = prodAttrName.join(',')
            }else if(prodAttrName.length==1){
              item.prodAttrName = prodAttrName[0]
            }else{
              item.prodAttrName = ''
            }
          })

          that.loading = false;

          that.getOpenedRouterList()

          if(this.list.transportVO.airlineCompany){
            getSupplier(this.list.transportVO.airlineCompany).then(res=>{
              if(res.data){
                this.airlineCompany = res.data.companyZh
              }
            })
          }
          if(this.list.transportVO.shippingCompany){
            getSupplier(this.list.transportVO.shippingCompany).then(res=>{
              if(res.data){
                this.shippingCompany = res.data.companyZh
              }
            })
          }
        });
      },
      getCity(id){
        var city = ''
        this.tradeCityList.forEach((item)=>{
          if(item.id == id){
            city = this.$i18n.locale=='zh_CN'?item.titleZh:item.titleEn
          }
        })
        return city
      },
      getChannelData(){
        getChannel(this.list.channelId).then(res=>{
          this.channelName = res.data.nameZh
        })
      },
      // 获取路线
      getOpenedRouterList(){
          let params = {}
          if(this.list.departureId){
              params.startCityId = this.list.departureId
          }
          if(this.list.objectiveId){
              params.destCityId = this.list.objectiveId
          }
          getOpenedRouterList(params).then(res => this.routerList = res.data)
      },
      // 根据线路id显示线路名称
      getRouterNameById(routerId){
            let router = this.routerList.find(item => item.id == routerId)
            if(router){
                return this.$i18n.locale=='zh_CN'?router.startTitleZh:router.startTitleEn + ' >>>' + this.$i18n.locale=='zh_CN'?router.destTitleZh:router.destTitleEn
            }
            return '-'
      },
      // 获取发货/收货人
      getCnsigneeData(){
        let that = this
         if(that.consigneeData&&that.consigneeData.customerId){
            getCustomer(that.consigneeData.customerId).then(result=>{
                result.data.source = this.sourceLabel(result.data.source)
                that.$set(that.consigneeData,'source',result.data.source)
                that.$set(that.consigneeData,'address',result.data.address)

            })
        }
        if(that.consignorData&&that.consignorData.customerId){
            getCustomer(that.consignorData.customerId).then(ress=>{
              ress.data.source = this.sourceLabel(ress.data.source)
                that.$set(that.consignorData,'source',ress.data.source)
                that.$set(that.consignorData,'address',ress.data.address)
            })
          }
      },
      /** 跟进按钮操作 */
      handleAdd() {
        this.$router.push({
          path: "/offer/logList",
          query:{
            offerId:this.offerId,
            relationId:this.list.consignorId
          }
        });
      },
      toResult(){
        this.$router.push({
          path: "/offer/result",
          query:{
            offerId:this.offerId,
            number:this.list.number
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete() {
        const offerId = this.offerId;
        this.$confirm(this.$t('是否确认删除报价单管理编号为')+'"' + offerId + '"'+this.$t('的数据项')+'?').then(function() {
            return deleteOffer(offerId);
          }).then(() => {
            this.$router.push({
              path: "/offer/result"
            });
            this.$message.success(this.$t("删除成功"));
          }).catch(() => {});
      },
    }
  }
</script>

<style scoped>
  .card-title{
      font-size: 18px;
      font-weight: bold;
       margin-top: 10px;
  }
  .offer-header{
    padding-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .line{
    display: flex;
    align-items: center;
  }
  .line el-descriptions{
    flex: 1;
  }
  .btn{
    width: 60%;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
  .title-font{
    font-size: 16px;
    font-weight: 600;
    margin-top: 20px;
  }
  .title-font label{
    margin-right: 20px;
  }
  .card{
    margin-top: 20px;
  }
</style>
