<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" inline :validate-on-rule-change="false">
      <el-card>
        <div slot="header" class="card-title">
          {{ $route.path.indexOf("create") > -1 ? $t("新建报价单") : $t("编辑报价单") }}
        </div>
        <el-form-item :label="$t('销售阶段')" prop="saleStage">
          <el-select v-model="form.saleStage" clearable :placeholder="$t('请选择')">
            <el-option v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_SALE_STAGE)" :key="dict.value" :label="isChinese ? dict.label : dict.labelEn" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <br>
        <el-form-item :label="$t('所属人')" prop="relation">
          <!-- <el-radio-group v-model="form.relation" > -->
          <el-radio-group v-model="form.relation" id="relation" @change="handleChangeRelation">
            <el-radio :label="1">{{ $t("发件人") }}</el-radio>
            <el-radio :label="2">{{ $t("收件人") }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="form-section">
          <el-form-item :label="$t('发货人')" prop="consignorId">
            <div class="contact">
              <el-input v-model="form.consignorName" id="defaultContactName" :placeholder="$t('选择或新建')" disabled style="width: 120px" />

              <img src="@/assets/svg/contacts.svg" class="phonebook" @click="contactChooseType = 'consignor'" />
              <img src="@/assets/svg/contact_create.svg" class="phonebook" @click="quickCreateType = '0'" />
            </div>
          </el-form-item>
          <el-form-item :label="$t('发货人电话')" prop="consignorPhone">
            <!-- <area-code-selector v-model="form.consignorCountryCode" class="w-200 mr-10" disabled /> -->

            <el-input id="defaultContactPhone" :value="`${form.consignorCountryCode ? '+' + form.consignorCountryCode : ''} ${form.consignorPhone || ''}`" class="w-200" disabled />
            <!-- <el-input v-if="$route.query.type==1 && form.relation==1" v-model="$route.query.customer.defaultContactPhone" class="w-200" disabled/>

                    <el-input v-else :value="`${form.consignorCountryCode ? '+' + form.consignorCountryCode : ''} ${form.consignorPhone || ''}`" class="w-200" disabled/> -->
          </el-form-item>
          <el-form-item :label="$t('发货人公司')" prop="consignorCompany">
            <!-- 修改从客户列表按钮进来的 -->
            <el-input v-model="form.consignorCompany" id="company" disabled class="w-200" />
            <!-- <el-input v-if="$route.query.type==1 && form.relation==1"  v-model="$route.query.customer.company" disabled  class="w-200"/>
                    <el-input v-else v-model="form.consignorCompany" disabled  class="w-200"/> -->
          </el-form-item>
          <el-form-item label="Email" prop="consignorEmail">
            <el-input v-model="form.consignorEmail" id="defaultEmail" disabled class="w-200" />
            <!-- <el-input v-if="$route.query.type==1 && form.relation==1"  v-model="$route.query.customer.defaultEmail" disabled  class="w-200"/>
                    <el-input v-else v-model="form.consigneeEmail" disabled  class="w-200"/> -->
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('收货人')" prop="consigneeId">
            <div class="contact">
              <!-- <el-input v-model="form.consigneeName" :placeholder="$t('请选择或新建')" :disabled="true"  style="width:120px"/> -->
              <el-input v-model="form.consigneeName" id="defaultContactName2" :placeholder="$t('请选择或新建')" :disabled="true" style="width: 120px" />

              <img src="@/assets/svg/contacts.svg" class="phonebook" @click="contactChooseType = 'consignee'" />
              <img src="@/assets/svg/contact_create.svg" class="phonebook" @click="quickCreateType = '1'" />
            </div>
          </el-form-item>
          <el-form-item :label="$t('收货人电话')" prop="consigneePhone">
            <!-- <area-code-selector v-model="form.consigneeCountryCode" class="w-200 mr-10" disabled/> -->
            <el-input id="defaultContactPhone2" :value="`${form.consigneeCountryCode ? '+' + form.consigneeCountryCode : ''} ${form.consigneePhone || ''}`" disabled class="w-200" />
          </el-form-item>
          <el-form-item :label="$t('收货人公司')" prop="consigneeCompany">
            <el-input id="company2" v-model="form.consigneeCompany" :disabled="true" class="w-200" />
            <!-- <el-input v-if="$route.query.type==1 && form.relation==2"  v-model="$route.query.customer.company" disabled  class="w-200"/>
                    <el-input v-else v-model="form.consignorCompany" disabled  class="w-200"/> -->
          </el-form-item>
          <el-form-item label="Email" prop="consigneeEmail">
            <el-input id="defaultEmail2" v-model="form.consigneeEmail" :disabled="true" class="w-200" />
            <!-- <el-input v-if="$route.query.type==1 && form.relation==2"  v-model="$route.query.customer.defaultEmail" disabled  class="w-200"/>
                    <el-input v-else v-model="form.consigneeEmail" disabled  class="w-200"/> -->
          </el-form-item>
        </div>

        <el-form-item :label="$t('客户状态')" prop="customerStatus">
          <el-select v-model="form.customerStatus" clearable :placeholder="$t('请选择')" class="w-200">
            <el-option v-for="dict in getDictDatas(DICT_TYPE.ECW_OFFER_CUSTOMER_STATUS)" :key="dict.value" :label="isChinese ? dict.label : dict.labelEn" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('货物状态')" prop="cargoStatus">
          <el-select v-model="form.cargoStatus" clearable :placeholder="$t('请选择')" class="w-200">
            <el-option v-for="dict in getDictDatas(DICT_TYPE.ECW_OFFER_CARGO_STATUS)" :key="dict.value" :label="isChinese ? dict.label : dict.labelEn" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('询盘来源')" prop="inquirySource">
          <el-select v-model="form.inquirySource" clearable :placeholder="$t('请选择')" class="w-200">
            <el-option v-for="dict in getDictDatas(DICT_TYPE.ECW_OFFER_INQUIRY_SOURCE)" :key="dict.value" :label="isChinese ? dict.label : dict.labelEn" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('客户经理')" prop="followUpSalesmanId">
          <el-select filterable v-model="form.followUpSalesmanId" :placeholder="$t('请选择客户经理')">
            <el-option v-for="item in serviceUserList" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- <el-descriptions :column="3" border>
                <el-descriptions-item :label="$t('*发货人')" :labelStyle="labelStyle" >
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consignorId" required :error="$t('发货人不能为空')">
                        <customer-contact-selector v-model="form.consignorId" @change="consignor = $event" type="1" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('手机号')" :labelStyle="labelStyle">
                    {{consignor.areaCode}} {{consignor.phoneNew || this.$t('无')}}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('发货人公司名称')" :labelStyle="labelStyle">
                    {{consignor.company || this.$t('无')}}
                </el-descriptions-item>
                <el-descriptions-item label="Email" :labelStyle="labelStyle">
                    {{consignor.email || this.$t('无')}}
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions :column="3" border>
                <el-descriptions-item :label="$t('收货人')" :labelStyle="labelStyle">

                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consigneeId" required :error="$t('收货人不能为空')">
                        <customer-contact-selector v-model="form.consigneeId" @change="consignee = $event" type="2" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('手机号')" :labelStyle="labelStyle">
                    {{consignee.areaCode}} {{consignee.phoneNew}}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('发货人公司名称')" :labelStyle="labelStyle">
                    {{consignee.company || this.$t('无')}}
                </el-descriptions-item>
                <el-descriptions-item label="Email" :labelStyle="labelStyle">
                    {{consignee.email || this.$t('无')}}
                </el-descriptions-item>
            </el-descriptions> -->
      </el-card>
      <el-card class="mt-10">
        <div slot="header" class="card-title">{{ $t("运输") }}</div>
        <div class="form-section">
          <el-form-item :label="$t('运输方式')" prop="transportId">
            <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="form.transportId" class="w-200" />
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('始发城市')" prop="departureId">
            <el-select v-model="form.departureId" :placeholder="$t('请选择始发地')" class="w-200">
              <el-option v-for="item in exportCityList" :label="$l(item, 'title')" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的国')" prop="destCountryId">
            <el-select v-model="form.destCountryId" :placeholder="$t('请选择目的国')" class="w-200">
              <el-option v-for="item in AddressProvince" :key="item.guojia" :label="item.guojiaName" :value="item.guojia" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的城市')" prop="objectiveId">
            <el-select v-model="form.objectiveId" :placeholder="$t('请选择目的地')" class="w-200">
              <el-option v-for="item in AddressCity" :key="item.shi" :label="item.shiName" :value="item.shi" />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('选择线路')" prop="lineId">
            <!-- <el-input :value="getRouterNameById(form.lineId)" readonly :placeholder="$t('请在右侧选择线路')"></el-input> -->
            <el-input :value="selectedRouter ? $l(selectedRouter, 'startTitle') + ' > ' + $l(selectedRouter, 'destTitle') : ''" disabled :placeholder="$t('请在右侧选择线路')" class="w-200"></el-input>
          </el-form-item>
          <select size="5" v-model="form.lineId" style="min-width: 300px; border: 1px solid #dcdfe6; border-radius: 4px">
            <template v-for="item in routerList">
              <option :value="item.id" :key="item.id">{{ $l(item, "startTitle") }} >> {{ $l(item, "destTitle") }}</option>
            </template>
          </select>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('出货渠道')" v-if="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass == 'channel'" prop="channelId">
            <selector :disabled="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass != 'channel'" v-model="form.channelId" :options="channelList" value-field="channelId" :label-field="$l('name')" class="w-200"></selector>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('增值服务')" v-if="routeOtherServices.indexOf('1') > -1 || routeOtherServices.indexOf('4') > -1">
            <el-checkbox-group v-model="form.serviceType">
              <el-checkbox label="1" v-if="routeOtherServices.indexOf('1') > -1">{{ $t("集运服务") }}</el-checkbox>
              <el-checkbox label="2" v-if="routeOtherServices.indexOf('4') > -1">{{ $t("海外仓") }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </el-card>
      <el-card class="mt-10">
        <div slot="header" class="card-title">
          <div class="card-name">{{ $t("商品") }}</div>
        </div>
        <el-table :data="form.prodCreateReqVOList" border class="product-list">
          <el-table-column :label="$t('序号')" width="60px" fixed>
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('中文品名')" width="160px">
            <template slot="header" slot-scope="scope"> {{ $t("中文品名") }} <span class="red">*</span> </template>
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`prodCreateReqVOList.${scope.$index}.prodId`"
                :rules="{
                  required: true,
                  message: $t('请选择产品'),
                  trigger: 'blur'
                }"
                class="mb-0 mr-0"
              >
                <product-selector v-model="scope.row.prodId" @change="onProductChange(scope.row, $event)" :disabled="!canAddProduct" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('英文品名')" width="160px">
            <template slot="header" slot-scope="scope"> {{ $t("英文品名") }} <span class="red">*</span> </template>
            <template slot-scope="{ row }">
              <product-selector lang="En" v-model="row.prodId" @change="onProductChange(row, $event)" :disabled="!canAddProduct" />
            </template>
          </el-table-column>
          <el-table-column width="100px">
            <template slot="header" slot-scope="scope"> {{ $t("品牌") }}</template>
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`prodCreateReqVOList.${scope.$index}.brand`"
                :rules="{
                  required: true,
                  message: $t('请选择品牌'),
                  trigger: 'blur'
                }"
                class="mb-0 mr-0"
              >
                <dict-selector v-model="scope.row.brand" :type="DICT_TYPE.ECW_IS_BRAND" defaultable @input="calculationPrice" :disabled="!canAddProduct" />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column :label="$t('件数')" width="90px">
            <template slot="header" slot-scope="scope"> {{ $t("件数") }}</template>
            <template slot-scope="{ row }">
              <el-input v-model.number="row.num" @input="calculationPrice" :disabled="!canAddProduct" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('包装单位')" width="100px">
            <template slot="header" slot-scope="scope"> {{ $t("包装单位") }}</template>
            <template slot-scope="{ row }">
              <dict-selector v-model="row.unit" :type="DICT_TYPE.ECW_PACKAGING_TYPE" defaultable @input="calculationPrice" :disabled="!canAddProduct" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('数量') + '(个)'">
            <template slot-scope="{ row }">
              <el-input v-model="row.quantity" @input="calculationPrice" :disabled="!canAddProduct" />
            </template>
          </el-table-column>
          <el-table-column width="100px">
            <template slot="header" slot-scope="scope"> {{ $t('总体积') + '(m³)' }}</template>
            <template slot-scope="scope">
              <el-form-item
                style="margin-bottom: 0;"
                label=""
                :prop="`prodCreateReqVOList.${scope.$index}.volume`"
              >
                <el-input v-model="scope.row.volume" @input="calculationPrice" :disabled="!canAddProduct" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('总重量') + '(kg)'" width="100px">
            <template slot="header" slot-scope="scope"> {{ $t('总重量') + '(kg)' }}</template>
            <template slot-scope="scope">
              <el-form-item
                style="margin-bottom: 0;"
                label=""
                :prop="`prodCreateReqVOList.${scope.$index}.weight`"
              >
                <el-input v-model="scope.row.weight" @input="calculationPrice" :disabled="!canAddProduct" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('总货值') + '(RMB)'" width="120px">
            <template slot="header" slot-scope="scope"> {{ $t("总货值") }}(RMB)</template>
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop2="`prodCreateReqVOList.${scope.$index}.worth`"
                :rules2="{
                  // required: true, message: $t('货值不能为空'), trigger: 'blur'
                }"
                class="mb-0 mr-0"
              >
                <el-input v-model="scope.row.worth" @input="calculationPrice" :disabled="!canAddProduct" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('商品特性')" width="250px">
            <template slot-scope="{ row }">
              <el-checkbox-group v-model="row.prodAttrArr" @change="onProductAttrChange(row, $event)" :disabled="!canAddProduct">
                <el-checkbox v-for="item in productAttrList" :label="item.id" :key="item.id">{{ $l(item, "attrName") }}</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-table-column>
          <el-table-column :label="$t('运费')" width="200px">
            <template slot-scope="{ row }">
              <template v-if="row.fee && row.fee.charging == 1">
                <template v-if="!row.fee.oneFreight">{{ $t("未报价") }}</template>
                <template v-else>
                  {{ $t("全包价") }}：{{ row.fee.oneFreight }} {{ currencyMap[row.fee.freightCurrency] }} /
                  {{ unitMap[row.fee.freightVolume] }}
                </template>
              </template>
              <template v-else-if="!row.fee || (!row.fee.oneFreight && !row.fee.oneClearanceFee)">{{ $t("未报价") }}</template>
              <template v-else-if="(row.fee.oneClearanceFee!=row.fee.groupDto.orgClearanceFeePrice)&&row.fee.specialPriceType">
                <div style="color: red;font-weight: 700;">
                  {{ $t("原价") }}
                </div>
                <div>
                  {{ $t("运费") }}：{{ row.fee.groupDto.orgClearanceFeePrice }} {{ currencyMap[row.fee.freightCurrency] }} /
                  {{ unitMap[row.fee.freightVolume] }}
                </div>
                <div>
                  {{ $t("清关费") }}：{{ row.fee.groupDto.orgFreightPrice }} {{ currencyMap[row.fee.clearanceFeeCurrency] }} /
                  {{ unitMap[row.fee.clearanceFeeVolume] }}
                </div>
                <div style="color: red;font-weight: 700;">
                  {{ $t("特价") }}
                </div>
                <div>
                  {{ $t("运费") }}：{{ row.fee.oneFreight }} {{ currencyMap[row.fee.freightCurrency] }} /
                  {{ unitMap[row.fee.freightVolume] }}
                </div>
                <div>
                  {{ $t("清关费") }}：{{ row.fee.oneClearanceFee }} {{ currencyMap[row.fee.clearanceFeeCurrency] }} /
                  {{ unitMap[row.fee.clearanceFeeVolume] }}
                </div>
              </template>
              <template v-else-if="row.fee">
                <div>
                  {{ $t("运费") }}：{{ row.fee.oneFreight }} {{ currencyMap[row.fee.freightCurrency] }} /
                  {{ unitMap[row.fee.freightVolume] }}
                </div>
                <div>
                  {{ $t("清关费") }}：{{ row.fee.oneClearanceFee }} {{ currencyMap[row.fee.clearanceFeeCurrency] }} /
                  {{ unitMap[row.fee.clearanceFeeVolume] }}
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column :label="$t('是否预付')">
            <template slot-scope="{ row }">
              <dict-tag v-if="row.fee" :type="DICT_TYPE.ECW_PAY_ADVANCE" :value="row.fee.isPayAdvance" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('商品链接')" width="200px" align="center">
            <template slot-scope="{ row }">
              <el-link type="primary" :href="row.link" target="_blank" style="display: block">{{ row.link }}</el-link>
              <el-button type="primary" size="mini" @click="setLink(row)" :disabled="!canAddProduct">
                {{ row.link ? $t("编辑商品链接") : $t("添加商品链接") }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column :label="$t('快递单号')" width="100px">
            <template slot-scope="{ row }">
              <el-input v-model="row.expressNo" placeholder="" :disabled="!canAddProduct" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" width="180px" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="delProduct(scope.$index)">{{ $t("删除") }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="card-title">
          <div class="card-name">
            <div class="card-title" style="float: left">{{ $t("合计") }}</div>
            <div class="card-title" style="float: left;margin-left: 470px;">{{ sum.totalNum.toFixed() || 0 }}</div>
            <div class="card-title" style="float: left;margin-left: 700px;position: absolute;">{{ sum.totalQuatity.toFixed() || 0 }}</div>
            <div class="card-title" style="float: left;margin-left: 780px;position: absolute;">{{ sum.totalVolume.toFixed() || 0 }}</div>
            <div class="card-title" style="float: left;margin-left: 870px;position: absolute;">{{ sum.totalWeight.toFixed() || 0 }}</div>
            <div class="card-title" style="float: left;margin-left: 970px;position: absolute;">{{ sum.totalWorth.toFixed() || 0 }}</div>
          </div>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="addProduct()" :disabled="!canAddProduct"></el-button>
        </div>
        <!--
        </el-card>
        <el-card  class="mt-10"> -->
<!--        <div class="card-title" style="padding: 20px 0">{{ $t("合计") }}</div>-->
<!--        <el-descriptions :column="4" border>-->
<!--          <el-descriptions-item :label="$t('总件数')">-->
<!--            {{ sum.totalNum.toFixed() || 0 }}-->
<!--          </el-descriptions-item>-->
<!--          <el-descriptions-item :label="$t('总体积')"> {{ sum.totalVolume.toFixed() || 0 }}m³ </el-descriptions-item>-->
<!--          <el-descriptions-item :label="$t('总重量')"> {{ sum.totalWeight.toFixed() || 0 }}kg </el-descriptions-item>-->
<!--          <el-descriptions-item :label="$t('总数量')">-->
<!--            {{ sum.totalQuatity.toFixed() || 0 }}-->
<!--          </el-descriptions-item>-->

<!--          <el-descriptions-item :label="$t('总货值') + '(RMB)'"> {{ sum.totalWorth.toFixed() || 0 }}{{ $t("元") }} </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('保价费')">
            {{ fee.insuranceFee || 0 }}
            {{ selectedRouter ? currencyMap[selectedRouter.currencyUnit || 1] : "" }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('总运费')">
            <template v-for="item in freightFeeList">
              <div :key="item.currencyId">{{ item.amount || 0 }}{{ currencyMap[item.currencyId] }}</div>
            </template>
          </el-descriptions-item>
          <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
          <el-descriptions-item :label="$t('总清关费')">
            <template v-for="item in clearanceFeeList">
              <div :key="item.currencyId">{{ item.amount || 0 }}{{ currencyMap[item.currencyId] }}</div>
            </template>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('其他费用')">
            <el-input v-model="form.otherFee" placeholder="" class="w-100 mr-10"></el-input>
            <selector v-model="form.otherFeeCurrencyId" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable class="w-100" />
          </el-descriptions-item>
          <el-descriptions-item :label="$t('预计费用')" :span="1">
            <div>
              <template v-for="item in estimatedCosts">
                <div :key="item.currencyId">{{ item.amount || 0 }}{{ currencyMap[item.currencyId] }}</div>
              </template>
            </div>
          </el-descriptions-item>
<!--          <el-descriptions-item :label="$t('原价')" :span="2">-->
<!--            <template v-for="item in originalFeeList">-->
<!--              <div :key="item.currencyId">{{ item.amount || 0 }}{{ currencyMap[item.currencyId] }}</div>-->
<!--            </template>-->
<!--          </el-descriptions-item>-->
        </el-descriptions>

<!--        <div class="card-title" style="padding: 20px 0">-->
<!--          {{ $t("优惠信息") }}-->
<!--        </div>-->
<!--        <el-table :data="couponList" :show-header="false" :empty-text="$t('暂无优惠')">-->
<!--          <el-table-column label="">-->
<!--            <template slot-scope="scope">-->
<!--              {{ scope.$index + 1 }}.-->
<!--              {{ $l(productNames[scope.row.prodId], "title") || $t("未知") }}-->
<!--            </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 }}-->
<!--              {{ currencyMap[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">
            <div v-for="(item, discountIndex) in couponTotalAmountList" :key="discountIndex">{{ item.totalAmount }} {{ currencyMap[item.currencyId] }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="mt-10">
        <div class="card-title" slot="header">{{ $t("通用") }}</div>
        <div class="form-section">
          <el-form-item :label="$t('唛头')" prop="marks">
            <el-input v-model="form.marks"  @blur="trimMarks" placeholder="" class="w-200"></el-input>
          </el-form-item>
          <el-form-item :label="$t('报关方式')" prop="customsType" label-width="200px">
            <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="form.customsType" form-type="radio" defaultable />
          </el-form-item>
        </div>
        <div class="form-section">
<!--          <el-form-item :label="$t('预计结束时间')" prop="stopTime">-->
<!--            &lt;!&ndash; <el-date-picker v-model="form.stopTime" value-format="yyyy-MM-dd HH:mm:ss" class="w-200"></el-date-picker> &ndash;&gt;-->
<!--            <el-date-picker v-model="form.stopTime" value-format="yyyy-MM-dd" class="w-200" :picker-options="stopDate"></el-date-picker>-->
<!--          </el-form-item>-->
          <el-form-item :label="$t('预计发货时间')" prop="estimatedShippingTime">
            <!-- <el-date-picker v-model="form.stopTime" value-format="yyyy-MM-dd HH:mm:ss" class="w-200"></el-date-picker> -->
            <el-date-picker v-model="form.estimatedShippingTime" value-format="yyyy-MM-dd" class="w-200" :picker-options="stopDate"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('是否控货')" prop="control" label-width="200px">
            <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" v-model="form.control" form-type="radio" />
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('竞争对手')" prop="competitor">
            <el-select filterable clearable v-model="form.competitor" :placeholder="$t('请选择')" class="w-200" @change="changeCompetitor">
              <el-option v-for="item in competitorList" :key="item.id" :label="item.name" :value="item.name" />
              <el-option :label="$t('其他')" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('重要程度')" prop="importance" label-width="200px">
            <el-rate v-model="form.importance"></el-rate>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('价格有效时间')" prop="startTime">
            <!-- <el-date-picker v-model="form.startTime" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" class="w-200"></el-date-picker> -->
            <el-date-picker v-model="form.startTime" placeholder="" value-format="yyyy-MM-dd" class="w-200" :picker-options="startDate"></el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="endTime">
            <!-- <el-date-picker v-model="form.endTime" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" class="w-200"></el-date-picker> -->
            <el-date-picker v-model="form.endTime" placeholder="" value-format="yyyy-MM-dd" class="w-200" :picker-options="endDate"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('交货方式')">
            <!--
                        接口要求数据为整数，所以增加trade_type类型的字典，用1234代码以下不同类型
                        FOB(离岸价)，CIF(到岸价)，CNF(成本加运费)，EXW(出厂价)
                    -->
            <dict-selector :type="DICT_TYPE.ECW_TRADE_TYPE" fomtter="number" v-model="form.tradeType" class="w-200" />
          </el-form-item>
          <el-form-item :label="$t('交货地址')">
            <el-input v-model="form.tradeAdress" :placeholder="$t('港口或地点')"></el-input>
          </el-form-item>
          <br>
          <el-form-item :label="$t('厂家')" prop="manufacturer">
            <el-input v-model="form.manufacturer" type="textarea" style="width: 410px; height: 50px"></el-input>
          </el-form-item>
          <el-form-item :label="$t('厂家电话')" prop="manufacturerPhone">
            <el-input v-model="form.manufacturerPhone"  type="textarea" style="width: 410px; height: 50px"></el-input>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('优惠信息')" :span="2" prop="specialOffers">
            <el-input v-model="form.specialOffers" :rows ="6" type="textarea" placeholder="" style="width: 410px; height: 100px"></el-input>
          </el-form-item>
          <el-form-item :label="$t('备注')" :span="2" prop="remarks">
            <el-input v-model="form.remarks" :rows ="6" type="textarea" placeholder="" style="width: 410px; height: 100px"></el-input>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="mt-10" v-if="transport">
        <div class="card-title" slot="header">
          <div class="card-name">
            {{ $t("其他") }}
          </div>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="qiTaTag=!qiTaTag"></el-button>
        </div>
        <!-- <el-form-item :label="$t('快递单号')">
                <el-input v-model="form.number" :placeholder="$t('请输入购买商品的快递单号')"></el-input>
            </el-form-item> -->
        <el-form-item :label="$t('特殊要求')" v-show="qiTaTag">
          <dict-selector v-model="form.transportVO.packageTypeArr" form-type="checkbox" :type="DICT_TYPE.ORDER_SPECIAL_NEEDS" multiple />
        </el-form-item>
        <br />
        <el-form-item :label="$t('特殊要求备注')" v-show="qiTaTag">
          <el-input v-model="form.transportVO.packageRemarks"></el-input>
        </el-form-item>
        <br />
        <el-form-item :label="$t('是否双清')" v-if="[2, 3, 4].indexOf(+form.transportId) > -1" v-show="qiTaTag">
          <dict-selector v-model="form.transportVO.doubleClear" form-type="radio" :type="DICT_TYPE.ECW_DOUBLE_CLEAR" />
        </el-form-item>
        <el-form-item :label="$t('航空公司')" v-if="[3, 4].indexOf(+form.transportId) > -1" v-show="qiTaTag">
          <!--待查询备选数据-->
          <!-- <el-select placeholder="" v-model="form.airlineCompany">
                </el-select> -->
          <supplier-selector v-model="form.transportVO.airlineCompany" companyType="10" />
        </el-form-item>

        <el-form-item :label="$t('船公司')" v-if="[2].indexOf(+form.transportId) > -1" v-show="qiTaTag">
          <!-- <el-select placeholder="" v-model="form.shippingCompany">
                </el-select> -->
          <supplier-selector v-model="form.transportVO.shippingCompany" companyType="9" />
        </el-form-item>
        <!--
        <div class="form-section">
          <el-form-item
            :label="$t('清关证书')"
            v-if="[2, 3, 4].indexOf(+form.transportId) > -1"
          >
            <dict-selector
              v-model="form.transportVO.customsClearCert"
              form-type="radio"
              :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
              formatter="bool"
            />
          </el-form-item>
          <el-form-item
            :label="$t('清关证书备注')"
            v-if="[2, 3, 4].indexOf(+form.transportId) > -1"
          >
            <el-input v-model="form.transportVO.remarks"></el-input>
          </el-form-item>

          <el-form-item
            :label="$t('是否拆包')"
            v-if="[3, 4].indexOf(+form.transportId) > -1"
          >
            <dict-selector
              v-model="form.transportVO.isUnpack"
              form-type="radio"
              :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
              formatter="bool"
            />
          </el-form-item>
        </div>
        <el-form-item
          :label="$t('单票立刻转运')"
          v-if="[3, 4].indexOf(+form.transportId) > -1"
        >
          <dict-selector
            v-model="form.transportVO.isSingleTicketTransport"
            form-type="radio"
            :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
            formatter="bool"
          />
          <span style="margin-left: 10px">{{
            $t(
              "注：若只有一件，货到仓库立即发，选“是”，多件需仓库集运待发，选“否”"
            )
          }}</span>
        </el-form-item>
        -->
      </el-card>

      <el-form-item label="" class="mt-20">
        <!-- 非草稿状态显示为编辑按钮 -->
        <el-button v-if="form.offerId && form.status != 2" type="primary" @click="submitForm(2)">{{ $t("编辑") }}</el-button>

        <template v-else>
          <el-button type="primary" @click="submitForm(2)">{{ $t("保存草稿") }}</el-button>
          <!-- 草稿 -->
          <el-button type="primary" @click="submitForm(3)">{{ $t("确认报价") }}</el-button>
          <!-- 需求确认 -->
        </template>
        <el-button @click="$store.dispatch('tagsView/delCurrentView')">{{ $t("取消") }}</el-button>
      </el-form-item>
    </el-form>

    <choose-contact-dialog v-if="!!contactChooseType" :type="2" @choose="onContactChoose" @close="contactChooseType = null" />
    <quick-create-customer v-if="quickCreateType" :type="quickCreateType" @success="onContactChoose" @close="quickCreateType = null" />
  </div>
</template>

<script>
import { createOffer, updateOffer, getOffer } from "@/api/ecw/offer"
import ProductSelector from "@/components/ProductSelector"
import { getProductAttrList } from "@/api/ecw/productAttr"
import { getChannelList } from "@/api/ecw/channel"
import Selector from "@/components/Selector"
import { openedRouterList as getOpenedRouterList } from "@/api/ecw/warehouse"
import { getTradeCityList } from "@/api/ecw/region"
import { getDictData } from "@/utils/dict"
import { getCurrencyList } from "@/api/ecw/currency"
import { getUnitList } from "@/api/ecw/unit"
import { calculationPrice } from "@/api/ecw/product"
import SupplierSelector from "@/components/SupplierSelector"
import ChooseContactDialog from "@/components/ChooseContactDialog"
import QuickCreateCustomer from "@/components/QuickCreateCustomer"
import { getCustomerContactsSelect } from "@/api/ecw/customerContacts"
import Decimal from "decimal.js"
import getQuote from "@/views/ecw/customer/index.vue"
import { getRegionList } from "@/api/ecw/order"
import { competitorListAll, addCompetitor } from "@/api/ecw/customer"
import { getCustomerContactsListByCustomer } from "@/api/ecw/customerContacts"
import { parse } from "querystring"
import { listServiceUser } from "@/api/system/user"

window.Decimal = Decimal
const createDefaultForm = () => {
  return {
    sendstatus: 0,
    type: [],
    control: false,
    isCargoControl: false,
    prodCreateReqVOList: [],
    transportVO: {},
    serviceType: [],
    saleStage: 1
  }
}
export default {
  name: "EcwOfferEdit",
  components: {
    ProductSelector,
    Selector,
    SupplierSelector,
    ChooseContactDialog,
    QuickCreateCustomer
  },
  data() {
    return {
      // 遮罩层
      // form: {
      //   relation: 1, // CustomerLevel 的初始值
      // },
      type: this.$route.query.type,
      contacts: null,
      contactsList: [],
      loading: true,
      // productList:[], // 商品信息
      productAttrList: [], // 商品属性
      channelList: [], // 出货取到
      routerList: [],
      tradeCityList: [],
      consignor: {}, // 发货人
      consignee: {}, // 收货人
      transportList: [],
      currencyList: [],
      unitList: [],
      // couponList: [],
      fee: {}, // 费用
      // 表单参数
      form: {
        relation: null,
        ...createDefaultForm()
      },
      // 表单校验

      labelStyle: "width:120px",
      productNames: {}, // 品名id和名称对应关系
      couponAvailableGroupDtoList: [], // 可用优惠
      couponTotalAmountList: [], // 优惠总额
      contactChooseType: null, // 联系人选择对象consignor(发货人) 或者 consignee（收货人）
      quickCreateType: null, // 快速新建客户类型，1发货人，2收货人
      getOpenedRouterListHandler: undefined,
      //预计结束时间，用于日历框校验
      stopDate: {
        disabledDate: (time) => {
          return Date.now() - 8.64e7 >= time.getTime() // 加- 8.64e7则表示包当天
        }
      },
      //有效起始时间
      startDate: {
        disabledDate: (time) => {
          return Date.now() - 8.64e7 >= time.getTime() // 加- 8.64e7则表示包当天
        }
      },
      //有效结束时间
      endDate: {
        disabledDate: (time) => {
          if (this.form.startTime) {
            return (
              //限制日期范围
              new Date(this.form.startTime).getTime() - 8.64e7 >= time.getTime() || time.getTime() >= new Date().setDate(new Date().getDate() + 30)
            )
          } else {
            // 加- 8.64e7则表示包当天
            return Date.now() - 8.64e7 >= time.getTime() || time.getTime() >= new Date().setDate(new Date().getDate() + 30)
          }
        }
      },
      AddressProvince: [],
      AddressCity: [],
      competitorList: [],
      qiTaTag: false,
      serviceUserList: []
    }
  },
  computed: {
    // computedStandard() {
    //   let customer = JSON.parse(this.$route.query.customer)

    //   console.log(customer, "zs")

    //   if (this.$route.query.type == 1) {
    //     // 使用计算属性动态设置 'Standard' 的值
    //     const type = customer.type
    //     if (type) {
    //       // 客户类型不为空时
    //       const types = type.split(",")
    //       if (types.includes("0")) {
    //         this.form.relation = 1
    //       } else {
    //         this.form.relation = 2
    //       }
    //     }
    //     switch (this.form.relation) {
    //       case 1:
    //         if (customer.defaultContactName != null) {
    //           this.form.consignorName = customer.defaultContactName
    //           this.form.consigneeName = ""
    //           this.form.consignorId = customer.defaultContactId
    //         }
    //         if (customer.company != null) {
    //           this.form.consignorCompany = customer.company
    //           this.form.consigneeCompany = ""
    //         }
    //         if (customer.defaultContactPhone != null) {
    //           this.form.consignorPhone = customer.defaultContactPhone
    //           this.form.consigorCountryCode = customer.defaultCountryCode
    //           this.form.consigneePhone = ""
    //           this.form.consigeeCountryCode = ""
    //         }
    //         if (customer.defaultEmail != null) {
    //           this.form.consignorEmail = customer.defaultEmail
    //           this.form.consigneeEmail = ""
    //         }
    //         return

    //       case 2:
    //         if (customer.defaultContactName != null) {
    //           this.form.consignorName = ""
    //           this.form.consigneeName = customer.defaultContactName
    //           this.form.consigneeId = customer.defaultContactId
    //         }
    //         if (customer.company != null) {
    //           this.form.consignorCompany = ""
    //           this.form.consigneeCompany = customer.company
    //         }
    //         if (customer.defaultContactPhone != null) {
    //           this.form.consignorPhone = ""
    //           this.form.consignorCountryCode = ""
    //           this.form.consigneePhone = customer.defaultContactPhone
    //         }
    //         if (customer.defaultEmail != null) {
    //           this.form.consignorEmail = ""
    //           this.form.consigneeEmail = customer.defaultEmail
    //         }
    //         return

    //       default:
    //         return ""
    //     }
    //   }
    // },
    isChinese() {
      return this.$i18n.locale === "zh_CN"
    },
    rules() {
      let rules = {
        marks: [
          {
            validator: (rule, value, callback) => {
              if (value && !/[a-zA-Z]/.test(value.charAt(0))) {
                return callback(new Error(this.$t("唛头必须以字母开头")))
              }
              callback()
            },
            trigger: "blur"
          }
        ],
        lineId: [{ required: true, message: this.$t("请选择线路") }],
        /* consignorId:    [{ required: true, message: this.$t("发货人不能为空"),}],
            consigneeId:    [{ required: true, message: this.$t("收货人不能为空")}], */
        // startTime: [{ required: true, message: this.$t("有效期开始时间不能为空") }],
        // endTime: [{ required: true, message: this.$t("有效期结束时间不能为空") }],
        transportId: [{ required: true, message: this.$t("选择运输方式") }],
        // departureId: [{required: true, message: this.$t('请选择始发城市')}],
        destCountryId: [{ required: true, message: this.$t("请选择目的国家") }],
        channelId: [{ required: true, message: this.$t("选择出货渠道") }],
        // stopTime: [{ required: true, message: this.$t("不能为空") }],
        estimatedShippingTime: [{ required: true, message: this.$t("不能为空") }],
        relation: [{ required: true, message: this.$t("请选择所属人") }],
        saleStage:  [{ required: true, message: this.$t("销售阶段不能为空") }],
        followUpSalesmanId: [{ required: true, message: this.$t("客户经理不能为空") }],
        // control: [{ required: true, message: this.$t("请选择是否控货") }],
        // importance: [
        //   { required: true, message: this.$t("请选择重要程度") },
        //   { type: "number", min: 1, message: this.$t("请选择重要程度") }
        // ]
        remarks: [
          { max: 500, message: '500max', trigger: 'blur' }
        ],
        specialOffers: [
          { max: 200, message: '200max', trigger: 'blur' }
        ],
        manufacturer: [
          { max: 100, message: '100max', trigger: 'blur' }
        ],
        manufacturerPhone: [
          { max: 50, message: '50max', trigger: 'blur' }
        ]
      }
      if (this.form.relation == 1) {
        rules.consignorId = [{ required: true, message: this.$t("发货人不能为空") }]
      }
      if (this.form.relation == 2) {
        rules.consigneeId = [{ required: true, message: this.$t("收货人不能为空") }]
      }
      return rules
    },
    exportCityList() {
      return this.tradeCityList.filter((item) => item.type == 2)
    },
    importCityList() {
      return this.tradeCityList.filter((item) => item.type == 1)
    },
    getDictData() {
      return (type, value) => getDictData(type, value) || {}
    },
    // 根据线路id显示线路名称
    getRouterNameById() {
      return (routerId) => {
        let router = this.routerList.find((item) => item.id == routerId)

        if (router) {
          return router.startTitleZh + " > " + router.destTitleZh
        }
        return "-"
      }
    },
    // 根据渠道id显示渠道名
    getChannelNameById() {
      return (channelId) => {
        return this.channelList.find((item) => item.channelId == channelId)?.nameZh
      }
    },
    // 当前运输方式
    transport() {
      return this.transportList.find((item) => item.value == this.form.transportId)
    },
    selectedRouter() {
      // otherService 1 送货上门，2非控货订单代收货款
      if (!this.form.lineId) return null
      return this.routerList.find((item) => item.id == this.form.lineId)
    },
    currencyMap() {
      let map = {}
      this.currencyList.forEach((item) => {
        map[item.id] = this.$l(item, "title")
      })
      return map
    },
    unitMap() {
      let map = {}
      this.unitList.forEach((item) => {
        map[item.id] = this.$l(item, "title")
      })
      return map
    },
    sum() {
      let sum = {
        totalNum: new Decimal(0),
        totalVolume: new Decimal(0),
        totalWeight: new Decimal(0),
        totalWorth: new Decimal(0),
        totalQuatity: new Decimal(0)
      }
      this.form.prodCreateReqVOList.forEach((item) => {
        sum.totalNum = sum.totalNum.plus(item.num || 0)
        sum.totalVolume = sum.totalVolume.plus(item.volume || 0)
        sum.totalWeight = sum.totalWeight.plus(item.weight || 0)
        sum.totalWorth = sum.totalWorth.plus(item.worth || 0)
        sum.totalQuatity = sum.totalQuatity.plus(item.quantity || 0)
      })
      return sum
    },
    // 总有优惠金额
    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,
            reduceTotalAmount: it.reduceTotalAmount,
            reduceAmount: it.reduceAmount,
            reduceCurrencyId: it.reduceCurrencyId
          })
        }
      })
      return arr
    },
    // 计算返回的费用清单
    feeDtoList() {
      return this.fee.feeDtoList || []
    },

    // 清关费
    clearanceFeeList() {
      return this.feeDtoList.filter((item) => item.feeType == 2)
    },
    // 运费
    freightFeeList() {
      return this.feeDtoList.filter((item) => item.feeType == 1)
    },
    // 原价（清关费 + 运费）
    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.reduceTotalAmount)
        }
        arr.push(it)
      })

      // 累加保价费
      const insuranceFeeIndex = arr.findIndex((item) => item.currencyId == this.insuranceFeeCurrency)
      if (insuranceFeeIndex > -1) {
        arr[insuranceFeeIndex].amount = arr[insuranceFeeIndex].amount.plus(this.fee.insuranceFee || 0)
      } else {
        arr.push({
          currencyId: this.insuranceFeeCurrency,
          amount: Decimal(this.fee.insuranceFee || 0)
        })
      }

      // 累加其他费用
      const otherFeeIndex = arr.findIndex((item) => item.currencyId == this.form.otherFeeCurrencyId)
      if (otherFeeIndex > -1) {
        arr[otherFeeIndex].amount = arr[otherFeeIndex].amount.plus(this.form.otherFee || 0)
      } else {
        if (this.form.otherFee > 0) {
          arr.push({
            currencyId: this.form.otherFeeCurrencyId,
            amount: Decimal(this.form.otherFee || 0)
          })
        }
      }

      return arr
    },
    // 路线开通的服务
    routeOtherServices() {
      if (!this.selectedRouter || !this.selectedRouter.otherService) return []
      return this.selectedRouter.otherService.split(",")
    },
    // 保价费单位（路线里设置，默认美元）
    insuranceFeeCurrency() {
      return this.selectedRouter?.currencyUnit || 1
    },
    // 是否可以添加商品
    canAddProduct() {
      if (!this.form.lineId) {
        return false
      }
      // 如果是海空联运或者空运专线则必须选择渠道
      if (this.transport && this.transport.cssClass == "channel" && !this.form.channelId) {
        return false
      }
      return true
    }
  },
  watch: {
    // 始发地
    "form.departureId"() {
      this.getOpenedRouterList()
    },
    "form.destCountryId"(destCountryId) {
      if (destCountryId != null) {
        getRegionList(2, destCountryId).then(({ data }) => {
          this.AddressCity = data
        })
      } else {
        getRegionList(4, 4).then(({ data }) => {
          this.AddressCity = data
        })
      }
    },
    // 目的地
    async "form.objectiveId"() {
      await this.$nextTick()
      await this.getChannelList()
      this.getOpenedRouterList()
    },
    "form.transportId"(transportId, oldTransportId) {
      // 海空联运默认数据
      if (transportId == 4) {
        this.$set(
          this.form.transportVO,
          Object.assign(this.form.transportVO, {
            doubleClear: "1",
            customsClearCert: false,
            isUnpack: false,
            isSingleTicketTransport: false,
            packageTypeArr: [],
            packageType: ""
          })
        )
      }
      this.getOpenedRouterList()

      // 更换运输方式之后，之前选择的路线会失效，需要重新选择
      if (oldTransportId && oldTransportId != transportId && transportId != this.selectedRouter?.transportType) {
        console.log("重置路线", oldTransportId, transportId, this.selectedRouter?.transportType)
        this.$set(this.form, "lineId", undefined)
      }
    },
    async "form.channelId"() {
      await this.getTradeCity()
      this.getOpenedRouterList()
      this.calculationPrice("form.channelId")
    },
    async "form.lineId"(lineId) {
      let router = this.routerList.find((item) => item.id == lineId)
      if (router) {
        this.$set(this.form, "departureId", router.startCityId)
        this.$set(this.form, "destCountryId", router.destCountryId)
        this.$set(this.form, "objectiveId", router.destCityId)
      }

      await this.$nextTick()
      await this.getChannelList()
      await this.getTradeCity()
      await this.calculationPrice("form.lineId")
    },
    "form.transportVO.packageTypeArr"(val) {
      this.$set(this.form.transportVO, "packageType", (val || []).join(","))
    },

    // 选择的路线变化后，需要判断是否开通了对应的服务，如果没开通需要取消对应的服务选择
    selectedRouter(val) {
      if (!val) return
      ;["1", "4"].forEach((service) => {
        if (this.routeOtherServices.indexOf(service) < 0 && this.form.serviceType.indexOf(service == 4 ? 2 : service) > -1) {
          this.form.serviceType.splice(
            this.form.serviceType.findIndex((item) => item == (service == 4 ? 2 : service)),
            1
          )
        }
      })
    }
  },
  activated() {
    if (this.$route.query.id && this.form.offerId !== this.$route.query.id) {
      console.log("编辑报价单跳转")
    // if (this.$route.query.id) {
      this.getOffer()
    }
    if (this.$route.query.copyId && this.form.copyId !== this.$route.query.copyId) {
      console.log("copy报价单跳转")
    // if (this.$route.query.copyId) {
      this.getOffer()
    }
    if (this.$route.query.type && this.$route.query.type == 1) {
      console.log("客户页面跳转")
        this.getCustomerContactsListByCustomer()
    }
  },
  async created() {
    await this.getChannelList()
    await this.getTradeCity()
    getProductAttrList().then((res) => (this.productAttrList = res.data))
    getCurrencyList().then((res) => (this.currencyList = res.data))
    getUnitList().then((res) => (this.unitList = res.data))
    this.transportList = this.getDictDatas(this.DICT_TYPE.ECW_TRANSPORT_TYPE)
    getRegionList(1, 1).then((res) => (this.AddressProvince = res.data))
    getRegionList(4, 4).then((res) => (this.AddressCity = res.data))
    competitorListAll().then((res) => (this.competitorList = res.data))
    listServiceUser().then((r) => {
      this.serviceUserList = r.data
        if (this.$route.query.id || this.$route.query.copyId) {
        } else if (this.$route.query.type && this.$route.query.type == 1) {
        } else {
          for (var a in r.data) {
            if(r.data[a].id == this.$store.state.user.id) {
              this.$set(this.form, "followUpSalesmanId", r.data[a].id)
            }
          }
        }
    })
    if (this.$route.query.id || this.$route.query.copyId) {
      console.log("编辑或复制报价单转进")
      this.getOffer()
    } else if (this.$route.query.type && this.$route.query.type == 1) {
      console.log("客户转进")
      this.getCustomerContactsListByCustomer()
    }else {
      console.log("新增报价单转进")
      // alert(this.$route.query.customer.defaultContactPhone)
      this.addProduct()
    }

  },
  methods: {
    handleChangeRelation(val) {
      if(val==1) {
        this.form.consigneeName = ""
        this.form.consigneeCompany = ""
        this.form.consigneePhone = ""
        this.form.consigneeCountryCode = ""
        this.form.consigneeEmail = ""
        this.form.consigneeId = ""
      } else {
        this.form.consignorName = ""
        this.form.consignorCompany = ""
        this.form.consignorPhone = ""
        this.form.consignorCountryCode = ""
        this.form.consignorEmail = ""
        this.form.consignorId = ""
      }
    },
    async getChannelList() {
      let query = {
        cityId: this.form.objectiveId,
        lineId: this.form.lineId
      }
      this.channelList = (await getChannelList(query)).data || []
    },
    async getTradeCity() {
      let query = {}
      if (this.form.channelId) {
        query.channelId = this.form.channelId
      }
      this.tradeCityList = (await getTradeCityList(query)).data || []
    },
    getCustomerContactsListByCustomer(){
       getCustomerContactsListByCustomer({ customerId: parseInt(this.$route.query.customerId || 0) }).then((res) =>{
        this.customer = res.data.find((item) => item.isDefault)
        if (this.$route.query.customerType) {
          // 客户类型不为空时
          const types = this.$route.query.customerType.split(",")
          console.log("客户类型:", types)
          if (types.includes("0")) {
            this.form.relation = 1
          } else {
            this.form.relation = 2
          }
          // 根据客户联系人id选择客户信息
          getCustomerContactsSelect({
            ids: [this.customer.customerContactsId].join(",")
          }).then(({ data }) => {
            // 设置收货人或者发货人，相反需要清空另一个框的值
            this.onContactAssignValueBackToDisplay(data.list.find((item) => item.customerContactsId == this.customer.customerContactsId), this.form.relation == 1 ? "consignor" : "consignee")
            this.handleChangeRelation(this.form.relation)
          })

        }
      })

    },
    getOffer() {
      //加了是否从全部客户列表中报价按钮进来的判断
      if (this.$route.query.type !== 1) {
        getOffer(this.$route.query.id || this.$route.query.copyId).then((res) => {
          console.log("报价单信息", res.data)
          let formData = res.data
          formData.serviceType = formData.serviceType ? formData.serviceType.split(",").filter((item) => item != "") : []
          console.log(formData.serviceType)
          console.log(formData)
          formData.prodCreateReqVOList = []
          if (formData.transportVO && formData.transportVO.packageType) {
            formData.transportVO.packageTypeArr = formData.transportVO.packageType.split(",").filter((item) => item && item != "")
          }
          if (res.data.offerProdRespVOList) {

            res.data.offerProdRespVOList.forEach((item) => {
              formData.prodCreateReqVOList.push({
                goodsType: item.goodsType,
                brand: item.brand,
                unit: item.unit,
                channelId: item.channelId,
                lineId: item.lineId,
                prodId: item.prodId,
                num: item.num,
                quantity: item.quantity,
                boxGauge: item.boxGauge,
                volume: item.volume,
                transportId: item.transportId,
                weight: item.weight,
                worth: item.worth,
                specialPriceType: item.specialPriceType,
                oneSeaFreight: item.oneSeaFreight,
                orgFreightPrice: item.originalSeaFreight,
                originalSeaFreight: item.originalSeaFreight,
                oneClearanceFee: item.oneClearanceFreight,
                oneClearanceFreight: item.oneClearanceFreight,
                orgClearanceFeePrice: item.originalClearanceFreight,
                originalClearanceFreight: item.originalClearanceFreight,
                freightVolume: item.seaFreightVolume,
                seaFreightVolume: item.seaFreightVolume,
                clearanceFeeVolume: item.clearanceFreightVolume,
                clearanceFreightVolume: item.clearanceFreightVolume,
                charging: item.charging,
                freightCurrency: item.seaFreightCurrency,
                seaFreightCurrency: item.seaFreightCurrency,
                freight: item.seaFreight,
                clearanceFeeCurrency: item.clearanceFreightCurrency,
                clearanceFreightCurrency: item.clearanceFreightCurrency,
                clearanceFee: item.clearanceFreight,
                prodAttrArr:
                  item.prodAttrIds && item.prodAttrIds != ""
                    ? item.prodAttrIds
                        .split(",")
                        .filter((item) => item != "")
                        .map((item) => +item)
                    : []
              })
            })
          }

          if (this.$route.query.copyId) {
            formData.offerId = null
            formData.startTime = ""
            formData.endTime = ""
            formData.stopTime = ""
            formData.estimatedShippingTime = ""
            // 复制报价单状态重置为草稿
            formData.status = 2
          }

          formData.channelId = formData.channelId || null
          formData.followUpSalesmanId = formData.followUpSalesmanId?formData.followUpSalesmanId*1:''
          this.$set(this, "form", formData)
          console.log("报价单归属", this.form.relation == 1? "发货人":"收货人")
          // 接口只返回了发货人和收货人ID，还需要调用接口获取详细信息回显
          getCustomerContactsSelect({
            ids: [res.data.consigneeId, res.data.consignorId].join(",")
          }).then(({ data }) => {
            this.onContactAssignValueBackToDisplay(data.list.find((item) => item.customerContactsId == res.data.consigneeId), "consignee")
            this.onContactAssignValueBackToDisplay(data.list.find((item) => item.customerContactsId == res.data.consignorId), "consignor")
          })
        })
      }
    },
    onContactAssignValueBackToDisplay(contact, contactChooseType) {
      if (!contact) return
      this.$set(this.form, contactChooseType + "Company", contact.company)
      this.$set(this.form, contactChooseType + "Id", contact.customerContactsId)
      this.$set(this.form, contactChooseType + "CountryCode", contact.areaCode)
      this.$set(this.form, contactChooseType + "Email", contact.email)
      this.$set(this.form, contactChooseType + "Name", contact.contactsName)
      this.$set(this.form, contactChooseType + "Phone", contact.phoneNew)
    },

    onContactChoose(contact) {
      if (!contact) return
      if (!this.contactChooseType && !this.quickCreateType) return
      if (!this.contactChooseType && this.quickCreateType) {
        this.contactChooseType = this.quickCreateType == 0 ? "consignor" : "consignee"
      }

      this.$set(this.form, this.contactChooseType + "Company", contact.company)
      this.$set(this.form, this.contactChooseType + "Id", contact.customerContactsId)
      this.$set(this.form, this.contactChooseType + "CountryCode", contact.areaCode)
      this.$set(this.form, this.contactChooseType + "Email", contact.email)
      // this.$set(this.form, this.contactChooseType + 'Id', contact.customerId)
      this.$set(this.form, this.contactChooseType + "Name", contact.contactsName)
      this.$set(this.form, this.contactChooseType + "Phone", contact.phoneNew)
      this.contactChooseType = null
      this.quickCreateType = null
    },
    onProductChange(row, product) {
      // row.goodsType = product ? product.typeId : null
      row.prodAttrArr = !product
        ? []
        : product.attrId
            .split(",")
            .filter((item) => item !== "")
            .map((item) => +item)
      if (product) {
        this.$set(this.productNames, product.id, {
          titleZh: product.titleZh,
          titleEn: product.titleEn
        })
      }

      this.calculationPrice("onProductChange")
    },
    /* onLineChange(row){
        this.calculationPrice()
        // this.updateEnabledTransports()
    }, */
    onChannelChange(row) {
      this.calculationPrice("onChannelChange")
    },
    onProductAttrChange(row, attr) {
      this.calculationPrice("onProductAttrChange")
    },
    addProduct(data) {
      this.form.prodCreateReqVOList.push(data || { prodAttrArr: [] })
    },
    // 计算商品运费
    /* getProductFee(row){
        if(!row.prodId || !row.transportId || !row.lineId || !row.num || !row.weight)return false
        if(row.prodAttrArr){
            row.prodAttrIds = row.prodAttrArr.join(',')
        }
        getProductFeeList(row).then(res => {
            this.$set(row, 'fee', res.data[0] || {})
        })
    }, */
    // 获取路线
    getOpenedRouterList() {
      let params = {}
      if (this.form.departureId) {
        params.startCityId = this.form.departureId
      }
      if (this.form.objectiveId) {
        params.destCityId = this.form.objectiveId
      }
      if (this.form.transportId) {
        params.transportType = this.form.transportId
      }
      if (this.form.channelId) {
        params.channelId = this.form.channelId
      }
      // 如果没有任何条件，不请求接口
      if (!params.startCityId && !params.destCityId && !params.transportType && !params.channelId) return false
      getOpenedRouterList(params).then((res) => (this.routerList = res.data))
    },
    // 计算体积
    calcVolume(row) {
      if (!row.boxGauge || !row.num) return false
      try {
        row.volume = (eval(row.boxGauge) * row.num).toFixed(2)
      } catch (e) {
        row.volume = ""
      }
    },
    // 删除一条产品
    delProduct(index) {
      this.$confirm(this.$t("确定删除此条内容么？")).then((res) => {
        this.form.prodCreateReqVOList.splice(index, 1)
      })
    },
    /** 提交按钮 */
    submitForm(status) {
      this.$refs["form"].validate((valid, errors) => {
        if (!valid) {
          return this.$showFormValidateErrors(errors)
        }

        this.form.prodCreateReqVOList.map((item) => {
          item.prodAttrIds = item.prodAttrArr.join(",")
          item.lineId = this.form.lineId
          item.channelId = this.form.channelId
          item.transportId = this.form.transportId
        })

        if (this.form.transportVO?.packageTypeArr) {
          this.form.transportVO.packageType = this.form.transportVO.packageTypeArr.join(",")
        }

        let endTime = new Date(this.form.endTime)
        let startTime = new Date(this.form.startTime)

        if (endTime.getTime() < startTime.getTime()) {
          return this.$message.error(this.$t("价格有效结束时间不能小于开始时间"))
        }

        let time2 = new Date().setDate(new Date().getDate() + 30)

        if (endTime > time2) {
          return this.$message.error(this.$t("价格有效结束时间不能超过当前时间30天"))
        }

        // 修改的提交
        if (this.form.offerId != null) {
          let data = Object.assign({}, this.form, {
            // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
            prodUpdateReqVOList: this.getProductListWithDefaultValue(),
            serviceType: this.form.serviceType.join(",")
          })
          if (data.status < 3) {
            data.status = status
          }
          updateOffer(data).then((response) => {
            this.$modal.msgSuccess(this.$t("修改成功"))
            this.$redirect("index")
          })
          return
        }
        let data = null
        if (this.$route.query.type == 1) {
          console.log(JSON.stringify(this.contactsList))
          data = Object.assign({}, this.form, {
            prodCreateReqVOList: this.getProductListWithDefaultValue(),
            status,
            serviceType: this.form.serviceType.join(",")
          })
        } else {
          data = Object.assign({}, this.form, {
            prodCreateReqVOList: this.getProductListWithDefaultValue(),
            status,
            serviceType: this.form.serviceType.join(",")
          })
        }

        console.log(data)

        // 添加的提交
        createOffer(data).then((response) => {
          // 重置表单内容

          this.$set(this, "form", { ...createDefaultForm() })
          this.routerList = []
          this.$nextTick(() => {
            console.log("清理表单校验和路线")
            this.addProduct()
            this.$refs.form.clearValidate()
          })
          this.$modal.msgSuccess(this.$t("新增成功"))
          this.$redirect("index")
        })
      })
    },
    setLink(row) {
      this.$prompt(this.$t("请输入商品链接"), { inputValue: row.link }).then(({ value }) => {
        this.$set(row, "link", value)
      })
    },
    // 计算商品运费
    calculationPrice(tag) {
      let calcable = true
      if (!this.form.prodCreateReqVOList.length) return
      this.form.prodCreateReqVOList.forEach((item) => {
        if (!item.prodId) {
          console.log("产品未选择", item)
          calcable = false
        }
        item.brandType = item.brand
      })
      if (this.calculating || !calcable) {
        console.log("不满足费用计算条件，清空已获取的费用信息")
        this.form.prodCreateReqVOList.forEach((item) => {
          delete item.fee
        })
        this.fee = {}
        return false
      }
      this.calculating = true

      console.log("calculationPrice")

      calculationPrice({
        lineId: this.form.lineId,
        transportId: this.form.transportId,
        channelId: [3, 4].indexOf(this.form.transportId) > -1 ? this.form.channelId : undefined,
        prodConditionParamList: this.getProductListWithDefaultValue(),
        consigneeCustomerContactsId: this.form.consigneeCustomerContactsId,
        consignorCustomerContactsId: this.form.consignorCustomerContactsId,
        customsType: this.form.customsType,
        isCargoControl: this.form.control,
        orderType: this.form.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)
          }

          this.form.prodCreateReqVOList.map((item, index) => {
            console.log("============================")
            console.log(item)
            console.log("============================")
            var a = null
            if(res.data.prodCostDtoList[index]) {
              a = res.data.prodCostDtoList[index]
              a['specialPriceType'] = item.specialPriceType
            }
            this.$set(item, "fee", a)
          })
        })
        .finally(() => {
          this.calculating = false
        })
    },
    // 体积。件数，数量，重量为选填，但是接口确实必填，所以生成一个副本并赋予默认值
    getProductListWithDefaultValue() {
      let arr = []
      this.form.prodCreateReqVOList.forEach((item) => {
        let tmp = { ...item }
        tmp.prodAttrIds = tmp.prodAttrArr.join(",")
        if (!tmp.volume) tmp.volume = 0
        if (!tmp.weight) tmp.weight = 0
        if (!tmp.quantity) tmp.quantity = 0
        if (!tmp.num) tmp.num = 0
        if (!tmp.worth) tmp.worth = 0
        arr.push(tmp)
      })
      return arr
    },
    changeCompetitor(val) {
      if (val == 0) {
        this.$prompt("请输入主要竞争对手", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then((data) => {
          console.log(data)
          addCompetitor({
            name: data.value
          }).then((r) => {
            this.$message.success("添加成功！")
            competitorListAll().then((res) => {
              this.competitorList = res.data
              this.$nextTick(() => {
                this.form.competitor = r.data.name
              })
            })
          })
        })
      }
    },
    // 去掉唛头首尾空格
    trimMarks(){
      this.form.marks = this.form.marks.trim()
    }
  }
}
</script>
<style lang="scss" scoped>
.card-title {
  font-size: 18px;
  display: flex;
  .card-name {
    flex: 1;
  }
}
.form-section {
  .contact {
    display: flex;
    align-items: center;
    img.phonebook {
      width: 30px;
      height: 30px;
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
::v-deep .product-list .el-form-item__error {
  position: static;
}
::v-deep th.el-table__cell .cell {
  white-space: nowrap;
  .red {
    color: red;
  }
}
</style>
