<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="card-title">{{ $t("报价单号") }}:{{ list.number }} - <dict-tag :type="DICT_TYPE.ECW_OFFER_STATUS" :value="list.status" /></div>
      <!-- 列表 -->
      <div class="offer-header">
        <span style="font-size: 15px"></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="handleAddOffer">{{ $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" :labelStyle="{ width: '110px' }">
          <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" :labelStyle="{ width: '110px' }">
          <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>
      </div>
    </el-card>
    <el-card class="card">
      <div slot="header" class="card-title">{{ $t("运输") }}</div>
      <div style="overflow: auto">
        <el-descriptions :column="4" border class="card" :labelStyle="{ width: '120px' }">
          <el-descriptions-item :label="$t('始发仓')" :contentStyle="{ width: '16%' }">{{ $l(list.logisticsInfoDto, "startTitle") }}</el-descriptions-item>
          <el-descriptions-item :label="$t('目的仓')" :contentStyle="{ width: '25%' }"> {{ $l(list.logisticsInfoDto, "destCountryTitle") }} - {{ $l(list.logisticsInfoDto, "destCityTitle") }} - {{ $l(list.logisticsInfoDto, "destTitle") }} </el-descriptions-item>
          <el-descriptions-item :label="$t('运输方式')" :contentStyle="{ width: '16%' }">
            <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="list.transportId" />
          </el-descriptions-item>
          <el-descriptions-item v-if="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, list.transportId).cssClass == 'channel'" :label="$t('出货渠道')">{{ list.channelName }}</el-descriptions-item>
          <el-descriptions-item :label="$t('服务')">
            <el-tag v-if="list.serviceType && list.serviceType.indexOf('1') > -1">
              {{ $t("集运") }}
            </el-tag>
            <el-tag v-if="list.serviceType && list.serviceType.indexOf('2') > -1">
              {{ $t("海外仓") }}
            </el-tag>
          </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 show-summary :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="$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.oneSeaFreight">{{ $t("未报价") }}</template>
                <template>{{ $t("全包价") }} {{ row.oneSeaFreight }} {{ currentcyMap[row.seaFreightCurrency] }} / {{ unitMap[row.seaFreightVolume] }}</template>
              </template>
              <template v-else-if="!row.oneSeaFreight && !row.oneClearanceFreight">{{ $t("未报价") }}</template>
              <template v-else>
                <div>{{ $t("运费") }}:{{ row.oneSeaFreight }} {{ currentcyMap[row.seaFreightCurrency] }} / {{ unitMap[row.seaFreightVolume] }}</div>
                <div v-if="row.oneClearanceFreight">{{ $t("清关费") }}:{{ row.oneClearanceFreight }} {{ currentcyMap[row.clearanceFreightCurrency] }} / {{ unitMap[row.clearanceFreightVolume] }}</div>
                <div v-else>{{ $t("清关费未报价") }}</div>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </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 }} {{ selectedRouter ? currentcyMap[selectedRouter.currencyUnit || 1] : "" }} </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>
    <customer-follow ref="customerFollow" v-if="customerFollowVisible" @close="customerFollowVisible = false" :customerService="curData.salesmanId" :customerNumber="curData.customerNumber" :offerId="offerId" />
  </div>
</template>

<script>
import { DICT_TYPE, getDictDatas, getDictData } 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

import CustomerFollow from "@/views/ecw/customer/components/customerFollow"
export default {
  name: "detail",
  components: { CustomerFollow },
  data() {
    return {
      DICT_TYPE,
      getDictData,
      customerFollowVisible: false,
      // 遮罩层
      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,
      curData: {}
    }
  },
  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")
      }
    },
    selectedRouter() {
      // otherService 1 送货上门,2非控货订单代收货款
      if (!this.list.lineId) return null
      return this.routerList.find((item) => item.id == this.list.lineId)
    },
    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 = {
          src: this.$t("清关费"),
          currencyId: item.currencyId,
          amount: Decimal(item.amount)
        }
        let freight = this.freightFeeList.find((fee) => fee.currencyId == item.currencyId)
        if (freight) {
          it.amount = it.amount.plus(freight.amount)
        }
        arr.push(it)
      })
      // 判断是否有运费单位不在清关费里的
      this.freightFeeList.forEach((item) => {
        if (!arr.find((arrItem) => arrItem.currencyId == item.currencyId)) {
          arr.push({
            src: this.$t("未计算的运费"),
            currencyId: item.currencyId,
            amount: Decimal(item.amount)
          })
        }
      })
      return arr
    },
    // 预计费用(原价 - 优惠金额)
    estimatedCosts() {
      let arr = []
      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)
        }
        arr.push(it)
      })
      // 累加保价费
      const insuranceFeeIndex = arr.findIndex((item) => item.currencyId == this.insuranceFeeCurrency)
      const insuranceFee = this.list && this.list.estCostVO && this.list.estCostVO.insuranceFee
      if (insuranceFeeIndex > -1) {
        arr[insuranceFeeIndex].amount = arr[insuranceFeeIndex].amount.plus(insuranceFee || 0)
      } else {
        arr.push({
          currencyId: this.insuranceFeeCurrency,
          amount: Decimal(insuranceFee || 0)
        })
      }

      // 累加其他费用
      const otherFeeIndex = arr.findIndex((item) => item.currencyId == this.list.otherFeeCurrencyId)
      if (otherFeeIndex > -1) {
        arr[otherFeeIndex].amount = arr[otherFeeIndex].amount.plus(this.list.otherFee || 0)
      } else {
        if (this.list.otherFee > 0) {
          arr.push({
            currencyId: this.list.otherFeeCurrencyId,
            amount: Decimal(this.list.otherFee || 0)
          })
        }
      }
      return arr
    },
    // 保价费单位(路线里设置,默认美元)
    insuranceFeeCurrency() {
      return this.selectedRouter?.currencyUnit || 1
    }
  },
  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 = parseInt(this.$route.query.offerId)
      this.getList()
    }
  },
  methods: {
    handleAddOffer() {
      this.curData = this.list
      this.customerFollowVisible = true
      this.$nextTick(() => {
        this.$refs["customerFollow"].handleAdd()
      })
    },
    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;
}

/deep/.el-table__fixed-footer-wrapper tbody td.el-table__cell .cell {
  font-size: 18px;
  font-weight: bold;
}
/deep/.el-table__footer-wrapper tbody td.el-table__cell .cell {
  font-size: 18px;
  font-weight: bold;
}
</style>