<template>
  <div>
    <div style="display: flex; align-items: flex-end">
      <img
        src="@/assets/setting/user.png"
        alt
        style="width: 26px; height: 26px"
      >
      <span
        style="
          font-size: 18px;
          font-weight: bold;
          color: #333333;
          line-height: 26px;
          margin-left: 5px;
        "
      >{{ $t("delivery.header") }}</span>
    </div>
    <div style="display: flex; align-items: flex-end; margin-top: 5px; margin-bottom: 20px">
      <div style="width: 75px; height: 4px; background: #396fff" />
      <div
        style="
          width: 75px;
          height: 1px;
          background: #fff;
          border: 1px solid #acacac;
        "
      />
    </div>

    <el-form ref="form" :model="form" :rules="rules" :validate-on-rule-change="false">
      <section-title lang-key="delivery.header">
          {{$t('delivery.consigneeName')}}
          <el-radio-group v-if="noConsignee" v-model="hasConsignee">
            <el-radio :label="true">{{$t('delivery.yes')}}</el-radio>
            <el-radio :label="false">{{$t('delivery.no')}}</el-radio>
          </el-radio-group>
      </section-title>

      <!--收货人-->
      <el-row :gutter="20" style="margin-top: 30px" v-if="hasConsignee">
        <el-col :span="12">
          <el-form-item
            :label="$t('delivery.name')"
            prop="consigneeName"
          >
            <el-input
              :disabled="!hasConsignee"
              v-model="form.consigneeName"
              :placeholder="$t('delivery.consigneeNameNotice')"
              style="width: 200px"
            />
            <el-button
              style="margin-left: 5px"
              type="text"
              @click="openConsignee"
              :disabled="!hasConsignee"
            >{{ $t("delivery.openConsignee") }}</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
              :label="$t('delivery.consigneePhone')"
              prop="consigneePhone"
          >
            <el-select
                :disabled="!hasConsignee"
                v-model="form.countryCode"
                style="width: 100px"
                @change="(val) => changeArea(val, form.consigneePhone)"
            >
              <el-option
                  v-for="item in countryList"
                  :key="item.id"
                  :label="'+' + item.tel"
                  :value="item.tel"
              >
                <span>{{ "+" + item.tel + " " + $l(item, "name") }}</span>
              </el-option>
            </el-select>
            <el-input
                :disabled="!hasConsignee"
                v-model="form.consigneePhone"
                :placeholder="$t('delivery.consigneePhoneNotice')"
                style="width: 180px"
                @blur="(val) => changeArea(form.countryCode, form.consigneePhone)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button circle icon="el-icon-circle-plus" v-if="!showFullConsignee" @click="showFullConsignee=true"></el-button>
          <el-button circle icon="el-icon-remove" v-else @click="showFullConsignee=false"></el-button>
        </el-col>
      </el-row>

      <el-row :gutter="5" v-if="showFullConsignee && hasConsignee">
        <el-col :span="6">
          <el-form-item
              :label="$t('orderdetail.consigneeNameEn')"
              prop="consigneeNameEn"
          >
            <el-input
                :disabled="!hasConsignee"
                v-model="form.consigneeNameEn"
                :placeholder="$t('delivery.consigneeNameNoticeEn')"
                style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('delivery.consigneeCompany')">
            <el-input
              :disabled="!hasConsignee"
              v-model="form.consigneeCompany"
              :placeholder="$t('delivery.consigneeCompanyNotice')"
              style="width: 150px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('orderdetail.consigneeCompanyEn')">
            <el-input
              :disabled="!hasConsignee"
              v-model="form.consigneeCompanyEn"
              :placeholder="$t('delivery.consigneeCompanyNoticeEn')"
              style="width: 150px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="Email">
            <el-input
                :disabled="!hasConsignee"
              v-model="form.consigneeEmail"
              :placeholder="$t('delivery.emailNotice')"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-card style="margin-top:20px;">
        <template #header>
          <section-title :title="$t('delivery.transportTitle')"></section-title>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item
            :label="$t('delivery.transport')"
            :label-style="{width: '100px'}"
          >
            <span
              slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.transport") }}</span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="transportId"
              required
              :error="$t('delivery.transportNotice')"
            >
              <dict-selector
                v-model="form.transportId"
                :type="DICT_TYPE.ECW_TRANSPORT_TYPE"
                :placeholder="$t('请选择运输方式')"
                clearable
              />
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions :column="3" border>
          <!--始发城市-->
          <el-descriptions-item
            :label="$t('delivery.departure')"
            :label-style="{width: '100px'}"
          >
            <span
              slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.departure") }}</span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="departureId"
              required
              :error="$t('delivery.departureRules')"
            >
              <el-select
                v-model="form.departureId"
                :placeholder="$t('delivery.departureNotice')"
                clearable
              >
                <el-option
                  v-for="item in exportCityList"
                  :key="item.id"
                  :label="$l(item, 'title')"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>

          <!--目的国-->
          <el-descriptions-item
              :label="$t('delivery.objective')"
              :label-style="{width: '100px'}"
          >
            <span
                slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.destCountry") }}</span>
            <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0"
                prop="destCountryId"
                required
                :error="$t('delivery.destCountryNotice')"
            >
              <el-select
                  v-model="form.destCountryId"
                  :placeholder="$t('delivery.destCountryNotice')"
                  clearable
                  @change="handleChangeDestCountry"
              >
                <el-option
                    v-for="item in showDestCountryLis"
                    :key="item.guojia"
                    :label="$l(item, 'guojiaName')"
                    :value="item.guojia"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>

          <!--目的城市-->
          <el-descriptions-item
            :label="$t('delivery.objective')"
            :label-style="{width: '100px'}"
          >
            <span
              slot="label"
            >{{ $t("delivery.objective") }}</span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="objectiveId"
              :error="$t('delivery.objectiveRules')"
            >
              <el-select
                v-model="form.objectiveId"
                :placeholder="$t('delivery.objectiveNotice')"
                clearable
                @change="handleChangeDestCity"
              >
                <el-option
                  v-for="item in showDestCityList"
                  :key="item.shi"
                  :label="$l(item, 'shiName')"
                  :value="item.shi"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>

          <!--路线-->
          <el-descriptions-item
            :label="$t('delivery.router')"
            :span="3"
            :label-style="{width: '100px'}"
          >
            <span
              slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.router") }}</span>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-input
                  :value="
                    selectedRouter
                      ? $l(selectedRouter, 'startTitle') +
                        ' > ' +
                        $l(selectedRouter, 'destTitle')
                      : ''
                  "
                  disabled
                  :placeholder="$t('delivery.routerNotice')"
                />
              </el-col>
              <el-col :span="12">
                <select v-model="form.lineId" size="5" style="min-width: 300px" @change="handleChangeLineId">
                  <template v-for="item in routerList">
                    <option :key="item.id" :value="item.id">
                      {{ $l(item, "startTitle") }} >> {{ $l(item, "destTitle") }}
                    </option>
                  </template>
                </select>
              </el-col>
            </el-row>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="
              getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId)
                .cssClass == 'channel'
            "
            :label="$t('delivery.channel')"
            :label-style="{width: '100px'}"
          >
            <span slot="label">{{ $t("delivery.channel") }}</span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="channelId"
            >
              <selector
                v-model="form.channelId"
                :disabled="
                  getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId)
                    .cssClass != 'channel'
                "
                :options="channelList"
                value-field="channelId"
                :label-field="$l(null, 'name')"
                clearable
              />
            </el-form-item>
          </el-descriptions-item>

          <!--服务-->
          <el-descriptions-item :label="$t('delivery.addServices')"
                                v-if="selectedRouter && (routeOtherServices.indexOf('1') > -1 || routeOtherServices.indexOf('4') > -1)">
            <el-checkbox-group v-model="form.type">
              <el-checkbox label="1"
                           v-if="(!selectedRouter || routeOtherServices.indexOf('1') > -1)"
              >{{ $t("delivery.orderType1") }}</el-checkbox>
              <el-checkbox label="2"
                           v-if="!selectedRouter || routeOtherServices.indexOf('2') > -1"
              >{{ $t("delivery.orderType2") }}</el-checkbox>
            </el-checkbox-group>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card class="mt-10">
        <div slot="header" class="card-title">
          <!--<div style="display: flex">
            <div
              style="
                width: 6px;
                height: 26px;
                background: #659fd5;
                border-radius: 0px 6px 6px 0px;
              "
            />
            <span
              style="
                font-size: 22px;
                font-weight: 500;
                color: #333;
                line-height: 26px;
                margin-left: 5px;
              "
            >{{ $t("delivery.goods") }}</span>
          </div>-->
          <section-title :title='$t("delivery.goods")'></section-title>
          <div>
            <el-button
              type="primary"
              round
              size="mini"
              :disabled="!canAddProduct"
              @click="addProduct(null)"
            >{{ $t("delivery.addPro") }}</el-button>
            <el-button
              v-if="false"
              type="primary"
              round
              size="mini"
              :disabled="!canAddProduct"
              @click="showBatchImportDialog = true"
            >{{ $t("delivery.addPros") }}</el-button>
          </div>
        </div>
        <el-table :data="form.orderItemVOList" class="product-list">
          <el-table-column :label="$t('delivery.index')" width="60px" fixed>
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('delivery.proZh')" width="160px">
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template slot="header" slot-scope="scope">
              <span class="red">*</span>{{ $t("delivery.proZh") }}
            </template>
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`orderItemVOList.${scope.$index}.prodId`"
                :rules="{
                  required: true,
                  message: $t('delivery.proRules'),
                  trigger: 'blur',
                }"
                class="mb-0 mr-0"
              >
                <product-selector
                  v-model="scope.row.prodId"
                  :disabled="!canAddProduct"
                  title="titleZh"
                  @change="onProductChange(scope.row, $event)"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('delivery.proEn')" width="160px">
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template slot="header" slot-scope="scope">
              <span class="red">*</span>{{ $t("delivery.proEn") }}
            </template>
            <template slot-scope="scope">
              <product-selector
                v-model="scope.row.prodId"
                :disabled="!canAddProduct"
                title="titleEn"
                @change="onProductChange(scope.row, $event)"
              />
            </template>
          </el-table-column>
          <!-- <el-table-column label="商品类型" width="160px">
                <template slot-scope="{row}">
                    <selector disabled v-model="row.goodsType" :options="productAttrList" label-field="attrName" value-field="id"></selector>
                </template>
              </el-table-column> -->

          <el-table-column :label="$t('delivery.brand')" width="100px">
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template slot="header" slot-scope="scope">
              <span class="red">*</span>{{ $t("delivery.brand") }}
            </template>
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`orderItemVOList.${scope.$index}.brandType`"
                :rules="{
                  required: true,
                  message: '请选择品牌',
                  trigger: 'blur',
                }"
                class="mb-0 mr-0"
              >
                <dict-selector
                  v-model="scope.row.brandType"
                  :type="DICT_TYPE.ECW_IS_BRAND"
                  defaultable
                  :disabled="!canAddProduct"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('delivery.num')" width="100px">
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template slot="header" slot-scope="scope">
              <span class="red">*</span>{{ $t("delivery.num") }}
            </template>
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`orderItemVOList.${scope.$index}.num`"
                :rules="{
                  required: true,
                  message: $t('请输入件数'),
                  trigger: 'blur',
                }"
                class="mb-0 mr-0"
              >
                <el-input-number
                  v-model="scope.row.num"
                  :controls="false"
                  :min="1"
                  :precision="0"
                  :disabled="!canAddProduct"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('delivery.unit')">
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template slot="header" slot-scope="scope">
              <span class="red">*</span>{{ $t("delivery.unit") }}
            </template>
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`orderItemVOList.${scope.$index}.unit`"
                :rules="{
                  required: true,
                  message: $t('请选择包装单位'),
                  trigger: 'blur',
                }"
                class="mb-0 mr-0"
              >
                <dict-selector
                  v-model="scope.row.unit"
                  :type="DICT_TYPE.ECW_PACKAGING_TYPE"
                  defaultable
                  :disabled="!canAddProduct"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('delivery.quantity') + '(个)'"
            width="100px"
          >
            <template slot-scope="{ row }">
              <el-input-number
                v-model="row.quantity"
                :disabled="!canAddProduct"
                :controls="false"
                :min="0"
                :precision="0"
              />
            </template>
          </el-table-column>
          <!-- <el-table-column label="箱规(m)" width="120px">
                <template slot-scope="{row}">
                    <el-input v-model="row.boxGauge" @input="calcVolume(row)" />
                </template>
              </el-table-column> -->
          <el-table-column
            :label="$t('delivery.volume') + '(m³)'"
            width="100px"
          >
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`orderItemVOList.${scope.$index}.volume`"
                :rules="[
                  {
                    validator: validatorPositiveNumber,
                    message: $t('体积错误'),
                    trigger: 'blur',
                  },
                ]"
                class="mb-0 mr-0"
              >
                <el-input
                  v-model="scope.row.volume"
                  :disabled="!canAddProduct"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('delivery.weight') + '(kg)'"
            width="100px"
          >
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`orderItemVOList.${scope.$index}.weight`"
                :rules="[
                  {
                    validator: validatorPositiveNumber,
                    message: $t('重量错误'),
                    trigger: 'blur',
                  },
                ]"
                class="mb-0 mr-0"
              >
                <el-input
                  v-model="scope.row.weight"
                  :disabled="!canAddProduct"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('delivery.worth') + '(RMB)'"
            width="100px"
          >
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template slot="header" slot-scope="scope">
              <span class="red">*</span>{{ $t("delivery.worth") }}(RMB)
            </template>
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="`orderItemVOList.${scope.$index}.worth`"
                :rules="[
                  {
                    required: true,
                    message: $t('delivery.worthRules'),
                    trigger: 'blur',
                  },
                  {
                    validator: validatorPositiveNumber,
                    message: $t('货值错误'),
                    trigger: 'blur',
                  },
                ]"
                class="mb-0 mr-0"
              >
                <el-input-number
                  v-model="scope.row.worth"
                  :disabled="!canAddProduct"
                  :controls="false"
                  :min="0"
                  :precision="0"
                  @input="calculationPrice"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('delivery.prodAttrArr')" width="250px">
            <template slot-scope="{ row }">
              <el-checkbox-group
                v-model="row.prodAttrArr"
                :disabled="!canAddProduct || row.prodAttrArr.indexOf(4) != -1"
                @change="onProductAttrChange(row, $event)"
              >
                <el-checkbox
                  v-for="item in productAttrList"
                  :key="item.id"
                  :label="item.id"
                >{{ $l(item, "attrName") }}</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-table-column>

          <!-- <el-table-column label="运费" width="200px">
            <template slot-scope="{row}">
              <template v-if="row.fee && row.fee.charging == 1">
                全包价：{{ row.fee.freight }} {{ currentcyMap[row.fee.freightCurrency] }} / {{ unitMap[row.fee.freightVolume] }}
              </template>
              <template v-else-if="row.fee">
                <div>
                  运费：{{ row.fee.freight }} {{ currentcyMap[row.fee.freightCurrency] }} / {{ unitMap[row.fee.freightVolume] }}
                </div>
                <div>
                  清关费：{{ row.fee.clearanceFee }} {{ currentcyMap[row.fee.clearanceFeeCurrency] }} / {{ unitMap[row.fee.clearanceFeeVolume] }}
                </div>
              </template>
            </template>
          </el-table-column> -->
          <el-table-column :label="$t('delivery.isPayAdvance')">
            <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('delivery.link')"
            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)">
                {{
                  row.link ? $t("delivery.linkedit") : $t("delivery.linkadd")
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column :label="$t('快递单号')" width="100px">
            <template slot-scope="{ row }">
              <el-input v-model="row.expressNo" :disabled="!canAddProduct" />
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('common.action')"
            width="80px"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="delProduct(scope.$index)"
              >{{ $t("common.delete") }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--
        </el-card>
        <el-card  class="mt-10"> -->
        <div class="card-title">
          <div style="display: flex">
            <div
              style="
                width: 6px;
                height: 26px;
                background: #659fd5;
                border-radius: 0px 6px 6px 0px;
              "
            />
            <span
              style="
                font-size: 22px;
                font-weight: 500;
                color: #333;
                line-height: 26px;
                margin-left: 5px;
              "
            >{{ $t("delivery.sum") }}</span>
          </div>
        </div>
        <el-descriptions :column="4" border>
          <el-descriptions-item :label="$t('delivery.totalNum')">
            {{ sum.totalNum || 0 }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('delivery.totalWorth') + '(RMB)'">
            {{ sum.totalWorth || 0 }}{{ $t("delivery.rmb") }}
          </el-descriptions-item>
          <!--报价费币种 lanbm 2024-05-14 修改BUG-->
          <el-descriptions-item :label="$t('delivery.insuranceFee')">
            {{ fee.insuranceFee || 0 }}
            <template v-if="fee.insuranceCurrencyId == 1">
              {{ $t("delivery.dollar") }}
            </template>
            <template v-else>(RMB)</template>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="mt-10">
        <div slot="header" class="card-title">
          <section-title :title='$t("delivery.common")'></section-title>
        </div>

        <el-descriptions :column="3" border>
          <!--唛头-->
          <el-descriptions-item :label="$t('delivery.marks')">
            <span
              slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.marks") }}</span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="marks"
              required
              :error="$t('delivery.marksRules')"
            >
              <el-input v-model="form.marks" placeholder="" class="w-150" @blur="trimMarks" />
            </el-form-item>
          </el-descriptions-item>
          <!--单证报关-->
          <el-descriptions-item :label="$t('delivery.customsType')" :span="2">
            <span
                slot="label"
            ><span style="color: red">*</span>
              {{ $t("delivery.customsType") }}
              <el-tooltip
                  :content="$t('delivery.customsTypeNotice')"
                  placement="top"
              >
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0"
                prop="customsType"
                required
            >
              <dict-selector
                  v-model="form.customsType"
                  :type="DICT_TYPE.ECW_CUSTOMS_TYPE"
                  defaultable
                  form-type="radio"
              />
            </el-form-item>
          </el-descriptions-item>

          <!--控货-->
          <el-descriptions-item :label="$t('delivery.isCargoControl')">
            <span
              slot="label"
            ><span style="color: red">*</span>
              {{ $t("delivery.isCargoControl") }}
              <el-tooltip
                :content="$t('delivery.isCargoControlNotice')"
                placement="top"
              >
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="isCargoControl"
              required
            >
              <dict-selector
                v-model="form.isCargoControl"
                :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                formatter="bool"
                form-type="radio"
                :disabled="!hasConsignee"
              />
            </el-form-item>
          </el-descriptions-item>

          <!--付款人-->
          <el-descriptions-item :label="$t('delivery.drawee')">
            <span
                slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.drawee") }}</span>
            <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0"
                prop="drawee"
                required
            >
              <dict-selector
                  v-model="form.drawee"
                  :type="DICT_TYPE.DRAWEE"
                  defaultable
                  form-type="radio"
              />
            </el-form-item>

            <!--自定义付款人-->
            <div v-if="form.drawee == 3">
              <template v-for="(item, index) in customDraweeList" v-key="index">
                <el-form-item :key="index" :label="item.label">
                  <dict-selector
                      v-model="item.value"
                      :type="DICT_TYPE.DRAWEE"
                      :filter="(e) => e.value == '1' || e.value == '2'"
                      form-type="radio"
                  />
                </el-form-item>
              </template>
            </div>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('delivery.displayBillLading')" >
            <el-form-item prop="displayBillLadingPrice" class="mb-0">
              <el-radio-group v-model="form.displayBillLadingPrice">
                <el-radio :label="true">{{$t('delivery.display')}}</el-radio>
                <el-radio :label="false">{{$t('delivery.notDisplay')}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-descriptions-item>

          <!--入仓类型-->
          <el-descriptions-item :label="$t('delivery.warehouseType')">
            <span
                slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.warehouseType") }}</span>
            <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0"
                prop="warehouseType"
                required
            >
              <dict-selector
                  class="w-150"
                  v-model="form.warehouseType"
                  :type="DICT_TYPE.ECW_WAREHOUSING_TYPE"
                  defaultable
              />
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item :label="$t('delivery.externalWarehouse')" :span="2">
            <el-form-item prop="isExternalWarehouse" class="mb-0">
              <el-checkbox label="" v-model="form.isExternalWarehouse" @change="form.isExternalWarehouse=$event" :disabled="false"></el-checkbox>
            </el-form-item>
            <div v-if="form.isExternalWarehouse">
              <div v-for="(item, index) in form.externalWarehouseDtoList" :key="index"
                   style="border-bottom: 1px solid #ccc; margin-bottom: 10px">
                <div class="flex-1">
                  <el-form-item :label="$t('delivery.loadingTime')"
                                :prop="'externalWarehouseDtoList.' + index + '.estLoadingTime'"
                                :rules="{
                              required: true, message: '装货时间不能为空', trigger: 'blur'
                              }"
                  >
                    <el-date-picker v-model="item.estLoadingTime" value-format="yyyy-MM-dd HH:mm:ss" class="w-150"></el-date-picker>
                  </el-form-item>
                </div>
                <div class="flex-1">
                  <el-form-item :label="$t('delivery.loadingAddress')"
                                :prop="'externalWarehouseDtoList.' + index + '.loadingAddress'"
                                :rules="{
                              required: true, message: '装货地址不能为空', trigger: 'blur'
                              }"
                  >
                    <el-input v-model="item.loadingAddress" placeholder="" class="w-150"></el-input>
                  </el-form-item>
                </div>
              </div>
              <div>
                <el-button size="mini" type="primary" icon="el-icon-plus" @click="form.externalWarehouseDtoList.push({})"></el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" :disabled="form.externalWarehouseDtoList.length <= 1"
                           @click="form.externalWarehouseDtoList.splice(form.externalWarehouseDtoList.length-1, 1)"></el-button>
              </div>
            </div>
          </el-descriptions-item>
          <!--预计送货日期-->
          <el-descriptions-item :label="$t('delivery.deliveryDate')" v-if="!form.isExternalWarehouse">
            <span
                slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.deliveryDate") }}</span>
            <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0"
                prop="deliveryDate"
                required
                :error="$t('delivery.deliveryDateRules')"
            >
              <el-date-picker
                  class="w-150"
                  v-model="form.deliveryDate"
                  value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item v-else-if="collectionProxy"><!--占位，防止错乱--></el-descriptions-item>

          <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
          <el-descriptions-item
            v-if="collectionProxy"
            :label="$t('delivery.isCollection')"
            :span="2"
          >
            <span
              slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.isCollection") }}</span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="isCollection"
              required
            >
              <dict-selector
                v-model="form.isCollection"
                :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                formatter="bool"
                form-type="radio"
                @input="selectCollectionProxy"
              />
            </el-form-item>
            <!--代收货款金额-->
            <el-form-item
                v-if="collectionProxy && showCollectionProxy"
                :label="$t('delivery.collectionProxy')"
            >
              <el-input-number
                  v-model="form.collectionProxy"
                  min="0"
                  :controls="false"
                  style="width: 200px"
              />
              <selector
                  v-model="form.collectionProxyCurrency"
                  :options="currencyList"
                  label-field="titleZh"
                  value-field="id"
                  defaultable
                  style="width: 100px"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item v-else-if="!form.isExternalWarehouse" :span="2"><!--占位--></el-descriptions-item>
          <!--收货方式-->
          <el-descriptions-item :label="$t('delivery.harvestMethod')">
            <span
                slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.harvestMethod") }}</span>
            <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0"
                prop="harvestMethod"
                required
            >
              <dict-selector
                  class="w-150"
                  v-model="form.harvestMethod"
                  :type="DICT_TYPE.ECW_HARVEST_METHOD"
                  :filter="(item) => item.value == 1 || homeDeliveryService"
                  defaultable
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :span="2"><!--报价单字段已在群里确认不需要--></el-descriptions-item>

          <!--收货地址-->
          <el-descriptions-item
              v-if="homeDeliveryService && form.harvestMethod == 2"
              :label="$t('delivery.deliveryaddress')">
            <span
                slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.deliveryaddress") }}</span>
            <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0"
                prop="city"
            >
              <area-selector
                  input-width="150px"
                  :country="form.consigneeVO ? form.consigneeVO.country : undefined"
                  :province="form.consigneeVO ? form.consigneeVO.province : undefined"
                  :city="form.consigneeVO ? form.consigneeVO.city : undefined"
                  @countryChange="onAreaChange('country', $event)"
                  @provinceChange="onAreaChange('province', $event)"
                  @cityChange="onAreaChange('city', $event)"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
              v-if="homeDeliveryService && form.harvestMethod == 2"
              :label="$t('delivery.addressdetail')"
              :span="2"
          >
            <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0"
                prop="consigneeAddress"
                required
            >
              <el-input v-model="form.consigneeAddress" placeholder="" />
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card class="mt-10">
        <template #header>
          <section-title :title="$t('delivery.other')"></section-title>
        </template>
        <el-descriptions :column="2" :label-style="{width: '100px'}" border>
          <el-descriptions-item>
            <span
                slot="label"
            >
              {{ $t("delivery.packageType") }}
              <el-tooltip
                  :content="$t('delivery.packageTypeNotice')"
                  placement="top"
              >
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <!--特殊要求 / 包装类型-->
            <el-form-item prop="packageType" class="mb-0">
              <dict-selector
                  v-model="form.packageType"
                  form-type="checkbox"
                  :type="DICT_TYPE.ORDER_SPECIAL_NEEDS"
                  multiple
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('特殊要求备注')">
            <!--包装备注-->
            <el-form-item prop="packageRemarks" class="mb-0">
              <el-input v-model="form.packageRemarks" type="textarea" class="w-150" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :span="2" :label="$t('delivery.number')">
            <!--快递单号-->
            <el-form-item prop="number" class="mb-0">
              <el-input
                  v-model="form.number"
                  :placeholder="$t('delivery.numberNotice')"
                  class="w-150"
              ></el-input>
              <el-button
                  class="ml-10"
                  type="default"
                  @click="getOrderCourierNumber"
              >{{ $t("delivery.getNumber") }}</el-button>
            </el-form-item>
          </el-descriptions-item>
          <template v-if="isAir">
            <el-descriptions-item :label="$t('delivery.customsClearCert')">
              <!--清关证书-->
              <el-form-item prop="customsClearCert" class="mb-0">
                <dict-selector
                    v-model="form.customsClearCert"
                    form-type="radio"
                    :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                    fomatter="bool"
                    defaultable
                />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('delivery.clearCertRemark')">
              <!--清关证书备注-->
              <el-form-item prop="remarks" class="mb-0">
                <el-input v-model="form.remarks" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('delivery.isUnpack')">
              <!--是否拆包-->
              <el-form-item prop="isUnpack" class="mb-0">
                <dict-selector
                    v-model="form.isUnpack"
                    form-type="radio"
                    :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                    fomatter="bool"
                />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('delivery.isSingleTicketTransport')">
              <!--单票立刻转运-->
              <el-form-item prop="isSingleTicketTransport" class="mb-0">
                <dict-selector
                    v-model="form.isSingleTicketTransport"
                    form-type="radio"
                    :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                    fomatter="bool"
                />
                <span style="margin-left: 10px; color: red">{{
                    $t("delivery.notice")
                  }}</span>
              </el-form-item>
            </el-descriptions-item>
          </template>

          <!--出单方式,新的原型没有提现，暂时隐藏显示-->
          <el-descriptions-item :label="$t('delivery.issuingMethod')" v-if="false">
            <span
              slot="label"
            ><span style="color: red">*</span>{{ $t("delivery.issuingMethod") }}</span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="issuingMethod"
              required
            >
              <dict-selector
                v-model="form.issuingMethod"
                :type="DICT_TYPE.ECW_SUING_METHOD"
                defaultable
                form-type="radio"
              />
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!--下面这部分根据原型没有展示，暂时隐藏-->
      <el-card v-if="false" class="mt-10">
        <!--是否双清-->
        <el-form-item
          v-if="[2, 3, 4].indexOf(+form.transportId) > -1"
          :label="$t('delivery.doubleClear')"
        >
          <dict-selector
            v-model="form.doubleClear"
            form-type="radio"
            :type="DICT_TYPE.ECW_DOUBLE_CLEAR"
            defaultable
          />
        </el-form-item>
        <!--el-form-item
          v-if="[3, 4].indexOf(+form.transportId) > -1"
          :label="$t('delivery.airlineCompany')"
        >
          <supplier-selector v-model="form.airlineCompany" company-type="10" />
        </el-form-item-->
        <!--船公司-->
        <el-form-item
          v-if="[2].indexOf(+form.transportId) > -1"
          :label="$t('delivery.shippingCompany')"
        >
          <supplier-selector v-model="form.shippingCompany" company-type="9" />
        </el-form-item>
      </el-card>

      <el-form-item label="" class="mt-20">
        <el-button
          v-if="form.status == 0 || editFlag"
          type="primary"
          @click="submitForm(0, false)"
        >{{ $t("存草稿") }}</el-button>
        <el-button
          v-if="editFlag || form.status == 0"
          type="primary"
          @click="submitForm(2)"
          :disabled="isOverSeaWareHouse"
        >{{ $t("提交") }}</el-button>
        <el-button
          v-if="form.status == 2 && !editFlag"
          type="primary"
          @click="submitForm(2, false)"
          :disabled="isOverSeaWareHouse"
        >{{ $t("提交") }}</el-button>
        <el-button @click="handleCancel">{{ $t("common.cancel") }}</el-button>
      </el-form-item>
      <div style="padding-bottom: 20px; font-size: 12px; color: red" v-if="isOverSeaWareHouse">
        {{$t('如需海外仓服务，请联系客服，服务热线：{tel}', {tel: '400-900-9962'})}}
      </div>
    </el-form>
    <!-- 收货人列表弹窗 -->
    <el-dialog
      :title="$t('delivery.openConsignee')"
      :visible.sync="consigneeVisdle"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="mb-10">
        <el-input
          class="w-200"
          v-model="customeParams.searchKey"
          placeholder="请输入姓名/公司/电话"
          clearable
          @clear="getCustomerList(true)"
          @change="getCustomerList(true)"
        />
        <el-button
          type="primary"
          @click="getCustomerList(true)"
          style="margin-left: 10px"
        >{{ $t("搜索") }}</el-button>
      </div>
      <div v-if="!addCustomerShow">
        <el-table
          ref="consigneeTable"
          :data="customerList"
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" width="50" />
          <el-table-column
            prop="name"
            :label="$t('customer.name')"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="nameEn"
            :label="$t('customer.nameEn')"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="company"
            :label="$t('customer.company')"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="companyEn"
            :label="$t('customer.companyEn')"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="maitou"
            :label="$t('customer.maitou')"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="phone"
            :label="$t('customer.phone')"
            align="center"
            header-align="center"
          >
            <template slot-scope="scope">
              +{{ scope.row.dialCode }} {{ scope.row.phone }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('common.action')"
            align="center"
            header-align="center"
            width="120"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="selectConsignee(scope.row)"
              >{{ $t("delivery.select") }}</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="updateCustomer(scope.row)"
              >{{ $t("common.update") }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="customeParams.page"
          :limit.sync="customeParams.rows"
          @pagination="getCustomerList"
        />
      </div>
      <el-form
        v-else
        ref="addCustomerForm"
        :model="addCustomerForm"
        :rules="addCustomerRules"
        label-width="126px"
      >
        <el-form-item :label="$t('customer.name')" prop="name">
          <el-input
            v-model="addCustomerForm.name"
            :placeholder="$t('customer.nameNotice')"
          />
        </el-form-item>
        <el-form-item :label="$t('customer.nameEn')" prop="nameEn">
          <el-input
            v-model="addCustomerForm.nameEn"
            :placeholder="$t('customer.nameNotice')"
          />
        </el-form-item>
        <el-form-item :label="$t('customer.company')" prop="company">
          <el-input
            v-model="addCustomerForm.company"
            :placeholder="$t('customer.companyNotice')"
          />
        </el-form-item>
        <el-form-item :label="$t('customer.companyEn')" prop="companyEn">
          <el-input
            v-model="addCustomerForm.companyEn"
            :placeholder="$t('customer.companyNotice')"
          />
        </el-form-item>
        <el-form-item :label="$t('customer.maitou')" prop="maitou">
          <el-input
            v-model="addCustomerForm.maitou"
            :placeholder="$t('customer.maitouNotice')"
          />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item :label="$t('customer.phone')" prop="dialCode">
              <el-select v-model="addCustomerForm.dialCode">
                <el-option
                  v-for="item in countryList"
                  :key="item.id"
                  :label="item.tel + ' ' + item.nameZh"
                  :value="item.tel"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item prop="phone">
              <span slot="label" />
              <el-input
                v-model="addCustomerForm.phone"
                :placeholder="$t('customer.phoneNotice')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('customer.email')" prop="email">
          <el-input
            v-model="addCustomerForm.email"
            :placeholder="$t('customer.emailNotice')"
          />
        </el-form-item>
        <el-form-item :label="$t('customer.address')" prop="address">
          <el-input
            v-model="addCustomerForm.address"
            :placeholder="$t('customer.addressNotice')"
          />
        </el-form-item>
        <el-form-item :label="$t('customer.groupBy')" prop="pid">
          <el-select v-model="addCustomerForm.pid">
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('customer.default')">
          <el-radio v-model="addCustomerForm.defaultContact" :label="true">{{
            $t("customer.yes")
          }}</el-radio>
          <el-radio v-model="addCustomerForm.defaultContact" :label="false">{{
            $t("customer.no")
          }}</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="!addCustomerShow"
          type="primary"
          @click="addCustomerShow = true"
        >{{ $t("delivery.addCustomer") }}</el-button>
        <el-button v-if="!addCustomerShow" @click="consigneeVisdle = false">{{
          $t("common.cancel")
        }}</el-button>
        <el-button v-if="addCustomerShow" type="primary" @click="addCustomer">{{
          $t("common.confirm")
        }}</el-button>
        <el-button
          v-if="addCustomerShow"
          @click="
            addCustomerShow = false;
            getCustomerList();
            addCustomerForm = { defaultContact: false };
          "
        >{{ $t("common.back") }}</el-button>
      </div>
    </el-dialog>
    <!-- 批量添加商品 -->
    <el-dialog
      :title="$t('delivery.batchImport')"
      :visible.sync="showBatchImportDialog"
      width="1000px"
      :close-on-click-modal="false"
    >
      <el-steps
        :active="importList.length > 0 ? 1 : 0"
        finish-status="success"
        class="w-500"
        style="margin: 20px auto"
      >
        <el-step :title="$t('delivery.uoloadBox')" />
        <el-step :title="$t('delivery.startImport')" />
        <el-step :title="$t('delivery.complete')" />
      </el-steps>
      <div class="mt-20">
        <el-upload
          :http-request="upload"
          :show-file-list="false"
          action=""
          :before-upload="beforeUpload"
          class="mr-10"
          style="display: inline-block"
        >
          <el-button size="small" type="primary">{{
            $t("delivery.upload")
          }}</el-button>
        </el-upload>
        <el-button
          type="info"
          size="small"
          :loading="exportLoading"
          @click="downloadTpl"
        >{{ $t("delivery.boxTpl") }}</el-button>
      </div>
      <el-table :data="importList" class="mt-10" height="300">
        <el-table-column :label="$t('delivery.index')">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column :label="$t('delivery.proZh')" prop="prodTitleZh" />
        <el-table-column :label="$t('delivery.proEn')" prop="prodTitleEn" />
        <el-table-column :label="$t('delivery.brand')" prop="brandType" />
        <el-table-column :label="$t('delivery.num')" prop="num" />
        <el-table-column
          :label="$t('delivery.weight') + '(kg)'"
          prop="weight"
        />
        <el-table-column
          :label="$t('delivery.volume') + '(m³)'"
          prop="volume"
        />
        <!-- <el-table-column label="有无单证" prop="">// TODO</el-table-column> -->
        <!-- <el-table-column label="缺货箱数" prop="lessNum"></el-table-column> -->
        <el-table-column :label="$t('delivery.quantity')" prop="quantity" />
        <el-table-column :label="$t('delivery.material')" prop="material" />
      </el-table>

      <div class="mt-10 center">
        <el-button type="primary" @click="addToProductList">{{
          $t("delivery.next")
        }}</el-button>
        <el-button type="default" @click="showBatchImportDialog = false">{{
          $t("common.cancel")
        }}</el-button>
      </div>
    </el-dialog>
    <!-- 实名登记提示弹窗 -->
    <el-dialog
      :title="$t('sidebar.notice')"
      :visible.sync="noticeVisble"
      width="30%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-card>
        {{ $t("sidebar.realNameNotice1") }}
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="noticeVisble = false">{{
          $t("sidebar.cancel")
        }}</el-button>
        <el-button
          @click="
            noticeVisble = false;
            $router.push('/jiedao/jd-idcard');
          "
        >{{ $t("sidebar.determine") }}</el-button>
      </div>
    </el-dialog>
    <!-- 营业执照提示弹窗 -->
    <el-dialog
      :title="$t('sidebar.notice')"
      :visible.sync="noticeVisble1"
      width="30%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-card>
        {{
          $t(
            "根据国家公安部、安监总局等部门所有入仓货物需要“实名制”登记，请联系客服上传营业执照认证"
          )
        }}
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeVisble1 = false">{{
          $t("sidebar.cancel")
        }}</el-button>
        <el-button type="primary">{{ $t("联系客服400-900-9962") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTradeCityList,
  getProductAttrList,
  getChannelList,
  getCurrencyList,
  calculationPrice,
  getData,
  getOpenedRouterList,
  validatorPhone,
  checkKycStatus, getListTree, getWarehouseTreeList, getGuojiaAndShiAndWarehouseList
} from '@/api/data'
import {
  getCustomerList,
  getGroupList,
  createCustomer,
  updateCustomer
} from '@/api/customer'
import { getCountryList, getIdCard } from '@/api/user'
import { getCustomerAvailableCouponList } from '@/api/coupon'
import {
  createOrder,
  updateOrder,
  getOrderDetail,
  getOrderCourierNumber,
  orderImport,
  exportPackingList
} from '@/api/order'
import DictSelector from '@/components/DictSelector'
import { getDictData, getDictDatas } from '@/utils/dict'
import ProductSelector from '@/components/ProductSelector'
import Selector from '@/components/Selector'
import AreaSelector from '@/components/AreaSelector'
import DictTag from '@/components/DictTag'
import SupplierSelector from '@/components/SupplierSelector'
import Pagination from '@/components/Pagination'
import SectionTitle from '@/views/jiedao/profile/components/SectionTitle.vue'
import { checkCountryCode } from '@/api/country'
export default {
  name: 'OrderEdit',
  components: {
    SectionTitle,
    ProductSelector,
    DictSelector,
    Selector,
    AreaSelector,
    DictTag,
    SupplierSelector,
    Pagination
  },
  data() {
    const validatorPositiveNumber = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') return callback()
      if (!value) return callback(new Error(this.$t('请输入数字')))
      if (!Number(value)) return callback(new Error(this.$t('请输入有效数字')))
      const reg = /((^[1-9]\d*)|^0)(\.\d*){0,1}$/
      if (!reg.test(value)) {
        return callback(new Error(this.$t('请输入有效数字')))
      }
      if (value <= 0) {
        return callback(new Error(this.$t('请输入大于0的数字')))
      }
      callback()
    }
    return {
      validatorPositiveNumber,
      // customDraweeList: [],
      // 国家区号列表，用于电话的区号选择
      countryList: [],
      // 目的国家，用于线路筛选
      destCountryList: [],
      // 目的城市
      destCityList: [],
      customerList: [], // 客户信息
      productAttrList: [], // 商品属性
      channelList: [], // 出货取到
      routerList: [],
      transportTypeList: [], // 运输方式
      couponTypeList: [], // 优惠卷类型
      consignee: null,
      consignor: null,
      // transportList: [],
      currencyList: [],
      tradeCityList: [],
      unitList: [],
      couponList: [],
      fee: {}, // 费用
      form: {
        destCountryId: null,
        countryCode: '86',
        objectiveId: '',
        departureId: '',
        status: 0,
        consigneeName: '',
        consigneePhone: '',
        consigneeCompany: '',
        consigneeEmail: '',
        consigneeAddress: '',
        marks: '',
        isCargoControl: false,
        isCollection: false,
        customsClearCert: false,
        isSingleTicketTransport: false,
        isUnpack: false,
        drawee: 2,
        type: [],
        orderItemVOList: [],
        externalWarehouseDtoList:[],
        displayBillLadingPrice: true,
        lineId: ''
      },
      // 总条数
      total: 0,
      // 查询参数
      customeParams: {
        page: 1,
        rows: 10,
        searchKey: ''
      },
      editFlag: true,
      consigneeVisdle: false,
      addCustomerShow: false,
      addCustomerForm: {
        defaultContact: false
      },
      groupList: [],
      addCustomerRules: {
        name: [
          {
            required: true,
            message: this.$t('customer.nameRules'),
            trigger: 'blur'
          }
        ],
        company: [
          {
            required: true,
            message: this.$t('customer.companyRules'),
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: this.$t('customer.phoneRules1'),
            trigger: 'blur'
          },
          { pattern: /^[0-9]\d*$/, message: this.$t('customer.phoneRules2') }
        ],
        dialCode: [
          {
            required: true,
            message: this.$t('customer.dialCode'),
            trigger: 'blur'
          }
        ]
      },
      showCollectionProxy: false,
      showBatchImportDialog: false, // 显示批量导入弹窗
      exportLoading: false, // 装下单模板下载状态
      importList: [],
      noticeVisble: false,
      noticeVisble1: false,
      // 有无收货人
      hasConsignee: true,
      // 显示完整收货人信息
      showFullConsignee: false,
      // 仓库区域树形列表
      warehouseTreeList: [],
      // 选择的路线对象
      selectedRouter: null,
      // 客户搜索关键词
      customerSearchKey: ''
    }
  },
  computed: {
    exportCityList() {
      return this.tradeCityList.filter((item) => {
        return item.type == 2 || item.type == 3
      })
    },
    importCityList() {
      return this.tradeCityList.filter((item) => {
        return item.type == 1 || item.type == 3
      })
    },
    exportCityIds() {
      const ids = []
      this.exportCityList.forEach((item) => {
        ids.push(item.id)
      })
      return ids
    },
    importCityIds() {
      const ids = []
      this.importCityList.forEach((item) => {
        ids.push(item.id)
      })
      return ids
    },
    getDictData() {
      return (type, value) => getDictData(type, value) || {}
    },
    getDictDatas() {
      return getDictDatas
    },
    transportList() {
      return this.getDictDatas(this.DICT_TYPE.ECW_TRANSPORT_TYPE)
    },
    customDraweeList() {
      const data = []
      this.getDictDatas(this.DICT_TYPE.ECW_CUSTOM_DRAWEE).forEach((item) => {
        data.push({
          label: item.label, // 显示文字
          name: item.value, // key值
          value: 2 // 1 发货人，2收货人，默认收货人，可修改
        })
      })
      return data
    },
    /* selectedRouter() {
      // otherService 1 送货上门，2非控货订单代收货款
      if (!this.form.lineId) return null
      return this.routerList.find((item) => item.id == this.form.lineId)
    }, */
    // 送货上门
    homeDeliveryService() {
      return (
        this.selectedRouter &&
        this.selectedRouter.otherService &&
        this.selectedRouter.otherService.indexOf('2') > -1
      )
    },
    // 代收货款
    collectionProxy() {
      return (
        !this.form.isCargoControl &&
        this.selectedRouter &&
        this.selectedRouter.otherService &&
        this.selectedRouter.otherService.indexOf('3') > -1
      )
    },
    // 根据渠道id显示渠道名
    getChannelNameById() {
      return (channelId) => {
        return this.channelList.find((item) => item.channelId == channelId)
          .nameZh
      }
    },
    // 当前运输方式
    transport() {
      return this.transportList.find(
        (item) => item.value == this.form.transportId
      )
    },
    currentcyMap() {
      const map = {}
      this.currencyList.forEach((item) => {
        map[item.id] = item.titleZh
      })
      return map
    },
    unitMap() {
      const map = {}
      this.unitList.forEach((item) => {
        map[item.id] = item.titleZh
      })
      return map
    },
    sum() {
      const sum = {
        totalNum: 0,
        totalVolume: 0,
        totalWeight: 0,
        totalWorth: 0,
        totalQuantity: 0
      }
      this.form.orderItemVOList.forEach((item) => {
        sum.totalNum += parseInt(item.num) || 0
        sum.totalVolume += parseFloat(item.volume) || 0
        sum.totalWeight += parseFloat(item.weight) || 0
        sum.totalWorth += parseFloat(item.worth) || 0
        sum.totalQuantity += parseFloat(item.quantity) || 0
      })
      return sum
    },
    // 路线开通的服务
    routeOtherServices() {
      if (!this.selectedRouter || !this.selectedRouter.otherService) return []
      return this.selectedRouter.otherService.split(',')
    },
    // 是否可以添加商品
    canAddProduct() {
      if (!this.form.lineId) {
        return false
      }
      // 如果是海空联运或者空运专线则必须选择渠道
      // if (
      //   this.transport &&
      //   this.transport.cssClass == 'channel' &&
      //   !this.form.channelId
      // ) {
      //   return false
      // }
      return true
    },
    // 当前用户信息
    userInfo() {
      return this.$store.getters.loginUser || {}
    },
    noConsignee() {
      return this.userInfo.noConsignee || false
    },
    isAir() {
      return [3, 4].indexOf(+this.form.transportId) > -1
    },
    // 显示的目的国
    showDestCountryLis(){
      return this.destCountryList
    },
    showDestCityList(){
      if(!this.form.destCountryId) return this.destCityList
      return this.destCityList.filter(item => item.guojia === this.form.destCountryId) || []
    },
    isOverSeaWareHouse(){
      return this.form.type?.indexOf('2') > -1
    },
    rules(){
      const rules = {
        transportId: [
          {
            required: true,
            message: this.$t('delivery.transportNotice'),
            trigger: 'blur'
          }
        ],
        marks: [
          { required: true, message: this.$t('delivery.marksRules') },
          // { pattern: /[A-z]/, message: this.$t('delivery.marksRules1') }
        ],
        destCountryId: [
          { required: true, message: this.$t('delivery.destCountryRules') }
        ],
        departureId: [
          { required: true, message: this.$t('delivery.departureRules') }
        ],
        objectiveId: [
          { required: true, message: this.$t('delivery.objectiveRules') }
        ],
        lineId: [{ required: true, message: this.$t('delivery.router') }],
        deliveryDate: [
          { required: true, message: this.$t('delivery.deliveryDateRules') }
        ],
        consigneeAddress: [
          { required: true, message: this.$t('delivery.addressdetailRules') }
        ],
        city: [
          { required: true, message: this.$t('delivery.deliveryaddressRules') }
        ]
      }
      if(this.hasConsignee){
        rules.consigneeName = [
          {
            required: true,
            message: this.$t('delivery.consigneeNameNotice'),
            trigger: 'blur'
          }
        ]
        rules.consigneeCompany = [
          {
            required: true,
            message: this.$t('delivery.consigneeCompanyNotice'),
            trigger: 'blur'
          }
        ]
        rules.consigneePhone = [
          {
            required: true,
            message: this.$t('delivery.consigneePhoneNotice'),
            trigger: 'blur'
          },
          { pattern: /^[0-9]\d*$/, message: this.$t('customer.phoneRules2') }
        ]
      }
      return rules
    }
  },
  watch: {
    $route() {
      location.reload()
    },
    // 始发地
    'form.departureId'() {
      this.getOpenedRouterList()
    },
    // 目的地
    /* 'form.objectiveId'() {
      this.getOpenedRouterList()
    }, */
    'form.transportId'() {
      this.getOpenedRouterList()
    },
    'form.isCargoControl'() {
      // this.isCargoControlDrawee()
      this.setDefaultDrawee()
      this.getIdCardData()
    },
    'form.channelId'() {
      this.calculationPrice()
      // 选择渠道后需要筛选目的城市和线路
      // 有点卡，改异步
      this.$nextTick(async() => {
        // 更新目的城市备选
        await this.getTradeCity()
        // 更新线路备选
        this.getOpenedRouterList()
      })
    },
    async 'form.lineId'(lineId) {
      const router = this.routerList.find((item) => item.id == lineId)
      if (!router) return
     /*  this.$set(this.form, 'departureId', router.startCityId)
      this.$set(this.form, 'objectiveId', router.destCityId)
      this.form.destCountryId = router.destCountryId */
      this.calculationPrice()
      this.getIdCardData()
      await this.getChannelList()
    },
    // 选择送货上门需要查询并填充默认地址
    'form.harvestMethod'(harvestMethod) {
      console.log(harvestMethod)
    },
    // 服务
    'form.type'(type, oldType){
      if(type.indexOf('2') > -1 && oldType?.indexOf('2') == -1){
        this.$alert(this.$t('如需海外仓服务，请联系客服，服务热线：{tel}', {tel: '400-900-9962'}))
      }
    },
    'form.isExternalWarehouse'(isExternalWarehouse){
      // 勾选外部仓则添加一个默认的，取消则删除默认的空的
      if(!isExternalWarehouse){
        this.$set(this.form, 'externalWarehouseDtoList', [])
      }else if(!this.form.externalWarehouseDtoList || !this.form.externalWarehouseDtoList.length){
        this.$set(this.form, 'externalWarehouseDtoList', [{}])
      }
    },
    // 选择的路线变化后，需要判断是否开通了对应的服务，如果没开通需要取消对应的服务选择
    async selectedRouter(val) {
      if (!val) return;
      ['1', '4'].forEach((service) => {
        if (
          this.routeOtherServices.indexOf(service) < 0 &&
          this.form.type.indexOf(service) > -1
        ) {
          this.form.type.splice(
            this.form.type.findIndex((item) => item == service),
            1
          )
        }
      })
    },
    // 送货上门变化后需要判断当前选择的收货方式，如果选择了送货上门但是当前不支持送货上门则需要重置
    homeDeliveryService(enable) {
      if (typeof enable === 'undefined') return
      if (!enable && this.form.harvestMethod != 1) {
        this.form.harvestMethod = 1
      }
    },
    hasConsignee(){
      // 无收货人，默认发货人付款,而且必须控货
      if(!this.hasConsignee){
        // this.form.drawee = 1
        this.form.isCargoControl = true
        this.$refs.form.clearValidate("consigneeName")
        this.$refs.form.clearValidate("consigneePhone")
        this.$refs.form.clearValidate("consigneeCompany")
        this.setDefaultDrawee()
      }
    }
  },
  async created() {
    await this.getCustomerList()
    await getCountryList().then((r) => {
      this.countryList = r.data
    })
    await getListTree({treeType: 1}).then(res => {
      this.dstCountryList = res.data
    })
    await getData({ page: 1, rows: 100, dictType: 'transport_type' }).then((r) => {
      this.transportTypeList = r.data.list
    })
    await getData({ page: 1, rows: 100, dictType: 'coupon_type' }).then((r) => {
      this.couponTypeList = r.data.list
    })
    await getGroupList({ page: 1, rows: 100 }).then((r) => {
      this.groupList = r.data.list
      this.groupList.push({ id: 0, title: this.$t('delivery.none') })
    })
    await getProductAttrList().then((res) => (this.productAttrList = res.data))
    // getChannelList().then((res) => (this.channelList = res.data))
    await await this.getTradeCity()
    await await this.getChannelList()
    await getCurrencyList().then((res) => (this.currencyList = res.data))

    await getGuojiaAndShiAndWarehouseList({tradeType: 1}).then(res => {
      this.destCountryList = res.data.guojiaList
      this.destCityList = res.data.shiList
      // this.destWarehoustList = res.data.warehouseList
    })

    // this.getIdCard()

    if (this.$route.query.id) {
      await getOrderDetail(this.$route.query.id).then(async (res) => {
        this.form = Object.assign({}, res.data, {
          orderItemVOList: [],
          destCountryId: null,
          consigneeName: '',
          consigneePhone: ''
        })
        this.form.deliveryDate = res.data.deliveryDate
        if (this.$route.query.copy && this.$route.query.copy == 1) {
          // 复制订单，需要将数据初始化
          this.form.orderId = null
          this.form.orderNo = null
          this.form.containerNumber = null
          this.form.tidanNo = null
          this.form.parentOrderId = null
          this.form.parentNumber = null
          this.form.number = null
          this.form.initialParentOrderId = null
          this.form.initialParentOrderNo = null
          this.form.noChargeRecord = null
          this.form.oldNumbers = null
          this.form.userId = 0
          this.form.sumNum = null
          this.form.sumQuantity = null
          this.form.sumVolume = null
          this.form.sumWeight = null
          this.form.pickleType = null
          this.form.pickRatio = null
          this.form.pickNum = null
          this.form.releaseRatio = null
          this.form.releaseNum = null
          this.form.cost = null
          this.form.packingListUrl = null
          this.form.commissionPayable = null
          this.form.specialVWeight = null
          this.form.handlerChannelAttrException = null
          this.form.weightBeforePack = null
          this.form.weightAfterPack = null
          this.form.stockOverWeightLimit = null
          this.form.firstStockedTime = null
          this.form.isLimitUpdateConsignee = null
          this.form.lockConsigneeDay = null
          this.form.lockConsigneeTime = null
          this.form.firstStockedTime = null
          this.form.adjustToStartWarehouseId = null
          this.form.adjustToDestWarehouseId = null
          this.form.destAdjustToStartWarehouseId = null
          this.form.destAdjustToDestWarehouseId = null
          // 状态重置
          this.form.status = 0
          this.form.cargoControlStatus = 0
          this.form.abnormalState = 0
          this.form.inWarehouseState = 0
          this.form.shipmentState = 0
          this.form.auditType = 0
          this.form.auditResult = null
          this.form.airShipment = null
          this.form.splitSeparateOrder = null
          this.form.pickState = null
          this.form.guanLianOrderStatus = null
          this.form.oldInWarehouseState = null
          this.form.oldStatus = null
          this.form.oldShipmentState = null
          this.form.orderType = null
          // 时间重置
          this.form.takeTime = null
          this.form.unloadTime = null
          this.form.rucangTime = null
          this.form.loadTime = null
          this.form.preLoadTime = null
          this.form.deliveryDate = null
          this.form.daogangTime = null
          this.form.qingguanTime = null
          this.form.splitTime = null
          this.form.isException = null
          this.form.exceptionReason = null
          this.form.externalWarehouseJson = null
          this.form.hasExitAndEntry = null
          this.form.hasSendRucangSms = null
          this.form.hasSendWarehouseInNotice = null
        }
        this.form.hasConsignee  = res.data.hasConsignee
        if (!this.noConsignee){
          // 不允许无收货人
          this.form.hasConsignee = true
        }
        if (res.data.consigneeVO && this.$route.query.copy && this.$route.query.copy == 1) {
          res.data.consignorVO.id = null
          res.data.consignorVO.orderId = null
        }
        if(res.data.consigneeVO){
          if (this.$route.query.copy && this.$route.query.copy == 1) {
            res.data.consigneeVO.id = null
            res.data.consigneeVO.orderId = null
          }
          this.$set(this.form, 'consigneePhone', res.data.consigneeVO.phone)
          this.$set(this.form, 'countryCode', res.data.consigneeVO.countryCode)
          this.$set(this.form, 'consigneeCompany', res.data.consigneeVO.company)
          this.$set(this.form, 'consigneeCompanyEn', res.data.consigneeVO.companyEn)
          this.$set(this.form, 'consigneeEmail', res.data.consigneeVO.email)
          this.$set(this.form, 'consigneeName', res.data.consigneeVO.name)
          this.$set(this.form, 'consigneeNameEn', res.data.consigneeVO.nameEn)
        }

        if(this.form.type){
          this.form.type = this.form.type.split(",").filter(item => !!item)
        }else this.form.type = []

        await this.getOpenedRouterList()
        this.handleChangeLineId()

        if (res.data.status != 0) {
          this.editFlag = false
        }
        if (res.data.channelId == 0) {
          this.$set(this.form, 'channelId', null)
        }
        this.$nextTick(() => {
          res.data.orderItemVOList.forEach((item) => {
            let newItem = {}
            if (this.$route.query.copy && this.$route.query.copy == 1) {
              newItem.link = item.link
              newItem.prodId = item.prodId
              newItem.prodTitleEn = item.prodTitleEn
              newItem.prodTitleZh = item.prodTitleZh
              newItem.prodAttrIds = item.prodAttrIds
              newItem.prodType = item.prodType
              newItem.volume = item.volume
              newItem.weight = item.weight
              newItem.quantity = item.quantity
              newItem.num = item.num
              newItem.worth = item.worth
              newItem.boxGauge = item.boxGauge
              newItem.brandType = item.brandType
            }else {
              newItem = item
            }
            newItem.prodAttrArr = newItem.prodAttrIds
              .split(',')
              .filter((item) => item != '')
              .map((attrId) => +attrId)
            this.form.orderItemVOList.push({ ...newItem })
          })
        })
      })
    } else{
      this.setDefaultDrawee()
      this.addProduct()
      if (this.$route.query.tranfId) {
        setTimeout(() => {
          this.$set(this.form, 'transportId', this.$route.query.tranfId)
        }, 500)
      }
    }
    await this.$nextTick()
    this.$refs.form.clearValidate()
  },
  methods: {
    async getTradeCity() {
      const query = {}
      if (this.form.channelId) {
        query.channelId = this.form.channelId
      }
      if(this.destCountryId){
        query.destCountryId = this.destCountryId
      }
      this.tradeCityList = (await getTradeCityList(query)).data
      await this.$nextTick()

      // 如果已选中的城市不在列表中则清空
      /* if(this.form.departureId && this.importCityList.findIndex(item => item.id == this.form.departureId) < 0){
        this.form.objectiveId = null
      } */
      // 如果只有一个城市则选中
      /* if(this.importCityList.length === 1){
        this.form.objectiveId = this.importCityList[0].id
      } */
    },
    setDefaultDrawee(){
      // 优先级为：发货人默认付款，发货人付款>收货人默认付款，收货人付款>订单控货，收货人付款
      if(this.userInfo.defaultPay){
        this.form.drawee = 1
        return
      }
      if(this.form.isCargoControl){
        this.form.drawee = 2
      }
    },
    async getChannelList() {
      const query = {
        cityId: this.form.objectiveId,
        lineId: this.form.lineId
      }
      this.channelList = (await getChannelList(query)).data
    },
    async getIdCardData() {
      if (!this.form.isCargoControl || !this.form.lineId) return
      var checkKyc = await checkKycStatus({
        controlCargoStatus: this.form.isCargoControl,
        lineId: this.form.lineId
      })
      switch (checkKyc.data.wareHouseStatus) {
        case 2:
          if (checkKyc.data.memberKycStatus != 2) {
            this.noticeVisble = true
          }
          break
        case 3:
          if (checkKyc.data.companyKycStatus != 2) {
            this.noticeVisble1 = true
          }
          break
        case 4:
          if (checkKyc.data.memberKycStatus != 2) {
            this.noticeVisble = true
          }
          if (checkKyc.data.companyKycStatus != 2) {
            this.noticeVisble1 = true
          }
          break
        case 5:
          if (
            checkKyc.data.memberKycStatus != 2 &&
            checkKyc.data.companyKycStatus != 2
          ) {
            this.noticeVisble = true
          }
          break
      }
    },
    isCargoControlDrawee() {
      if (!this.form.isCargoControl) {
        this.form.drawee = 1
      } else {
        this.form.drawee = 2
      }
    },
    getIdCard() {
      getIdCard().then((r) => {
        if (r.data && r.data.status == 2) {
          console.log('idcard is used')
        } else {
          this.$message.error(this.$t('delivery.realName'))
          this.$router.push('/jiedao/jd-profile')
        }
      })
    },
    getCustomerList(reload = false) {
      if(reload){
        this.customeParams.page = 1
        this.customerList = []
      }
      getCustomerList(this.customeParams).then((r) => {
        this.customerList = r.data.list
        this.total = r.data.total
      })
    },
    changeArea(code, mobile) {
      validatorPhone({ code: code, mobile: mobile })
    },
    addCustomer() {
      this.$refs['addCustomerForm'].validate((valid) => {
        if (!valid) {
          return
        }
        validatorPhone({
          code: this.addCustomerForm.dialCode,
          mobile: this.addCustomerForm.phone
        }).then((res) => {
          if (res.data) {
            // 修改的提交
            if (this.addCustomerForm.id != null) {
              updateCustomer(this.addCustomerForm).then((response) => {
                this.$message({
                  message: this.$t('common.success'),
                  type: 'success'
                })
                this.getCustomerList()
                this.addCustomerShow = false
              })
            } else {
              createCustomer(this.addCustomerForm).then((response) => {
                this.$message({
                  message: this.$t('common.success'),
                  type: 'success'
                })
                this.getCustomerList()
                this.addCustomerShow = false
              })
            }
            this.addCustomerForm = { defaultContact: false }
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    openConsignee() {
      this.consigneeVisdle = true
    },
    async selectConsignee(val) {
      if (val) {
        console.log(val)
        this.form.consigneeName = val.name
        this.form.consigneeNameEn = val.nameEn || ''
        this.form.consigneePhone = val.phone
        this.form.consigneeCompany = val.company
        this.form.consigneeCompanyEn = val.companyEn || ''
        this.form.consigneeEmail = val.email
        this.form.countryCode = String(val.dialCode)
        if (val.maitou) {
          this.form.marks = val.maitou
        }
        this.consigneeVisdle = false
        this.$refs.consigneeTable.setCurrentRow()
        await this.$nextTick()
        this.$refs.form.clearValidate('consigneeName')
        this.$refs.form.clearValidate('consigneePhone')
      }
    },
    updateCustomer(row) {
      this.addCustomerShow = true
      this.addCustomerForm = row
    },
    upload(e) {
      console.log({ upload: e })
      const form = new FormData()
      form.append('file', e.file)
      orderImport(form).then((res) => {
        this.importList = res.data.list
        this.$set(this.form, 'packingListUrl', res.data.packingListUrl)
      })
    },
    beforeUpload(file) {
      if (file.type.indexOf('excel') === -1) {
        this.$message.error(this.$t('文件类型不是excel'))
        return false
      }
    },
    addToProductList() {
      console.log('addToProductList')
      this.importList.forEach((item) => {
        this.form.orderItemVOList.push({
          prodId: item.prodId,
          brandType: item.brandType,
          num: item.num,
          quantity: item.quantity,
          volume: item.volume,
          weight: item.weight,
          prodAttrArr: []
        })
      })
      // 重置
      this.importList = []
      this.showBatchImportDialog = false
    },
    downloadTpl() {
      this.exportLoading = true
      exportPackingList()
        .then((response) => {
          this.$download.excel(response, this.$t('delivery.boxTpl') + '.xls')
          this.exportLoading = false
        })
        .catch(() => {
          this.exportLoading = false
        })
    },
    // onProductChange(row, product) {
    //   // row.goodsType = product ? product.typeId : null
    //   row.prodAttrArr = !product
    //     ? []
    //     : product.attrId
    //       .split(',')
    //       .filter((item) => item !== '')
    //       .map((item) => +item)
    //   row.prodTitleEn = product.titleEn
    //   row.prodTitleZh = product.titleZh
    //   this.calculationPrice()
    // },
    onProductChange(row, product) {
      console.log(product)
      // 如果是清除商品
      if (!product) {
        row.fee = null
        row.prodAttrArr = []
        return false
      }
      // 没有orderItemId则表示新增的，否则就是编辑回显的
      // row.updated 表示用户操作了,用来区分是自动回显还是用户选择商品
      if (!row.orderItemId || row.updated) {
        row.prodAttrArr = !product
          ? []
          : product.attrId
            .split(',')
            .filter((item) => item !== '')
            .map((item) => +item)
      }
      row.prodTitleEn = product.titleEn
      row.prodTitleZh = product.titleZh
      this.calculationPrice()
    },
    onProductAttrChange(row, attr) {
      // this.calculationPrice(row)
      /* // 需要强制刷新，否则勾选框不更新
        this.$forceUpdate() */
    },
    selectCollectionProxy(val) {
      this.showCollectionProxy = val
    },
    onAreaChange(type, val) {
      this.$set(this.form, type, val)
    },
    // 生成快递单号
    getOrderCourierNumber() {
      getOrderCourierNumber().then((res) => {
        this.$set(this.form, 'number', res.data)
      })
    },
    setLink(row) {
      this.$prompt(this.$t('delivery.linkRules'), {
        inputValue: row.link
      }).then(({ value }) => {
        console.log('value', value)
        this.$set(row, 'link', value)
      })
    },
    addProduct(data) {
      this.form.orderItemVOList.push(data || {
        prodAttrArr: [],
        prodId: null,
        worth: '',
        volume: '',
        weight: '',
        num: 1
      })
    },
    // 计算商品运费(根据货值计算保费)
    calculationPrice() {
      let calcable = true
      if (!this.form.orderItemVOList.length) return false
      this.form.orderItemVOList.forEach((item) => {
        if (!item.prodId) {
          calcable = false
        }
      })
      console.log(calcable, 'calcable')
      if (this.calculating || !calcable) return false
      this.calculating = true
      calculationPrice({
        lineId: this.form.lineId,
        transportId: this.form.transportId,
        channelId: this.form.channelId,
        prodConditionParamList: this.getProductListWithDefaultValue(),
        orderType: this.form.orderType
      })
        .then((res) => {
          this.$set(this, 'fee', res.data.costDto)
          // alert(res.data.costDto.insuranceCurrencyId);
          this.form.orderItemVOList.map((item, index) => {
            this.$set(item, 'fee', res.data.prodCostDtoList[index] || null)
          })
        })
        .finally(() => {
          this.calculating = false
        })
    },
    // 体积。件数，数量，重量为选填，但是接口确实必填，所以生成一个副本并赋予默认值
    getProductListWithDefaultValue() {
      const arr = []
      this.form.orderItemVOList.forEach((item) => {
        const tmp = { ...item }
        if (!tmp.volume) tmp.volume = 1
        if (!tmp.weight) tmp.weight = 1
        if (!tmp.quantity) tmp.quantity = 1
        if (!tmp.num) tmp.num = 1
        arr.push(tmp)
      })
      return arr
    },
    // 获取路线
    async getOpenedRouterList() {
      const 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(this.form.destCountryId){
        params.destCountryId = this.form.destCountryId
      }
      await this.$nextTick()
      await getOpenedRouterList(params).then((res) => {
        this.routerList = res.data.filter((item) => {
          return (
            this.exportCityIds.indexOf(item.startCityId) > -1 &&
            this.importCityIds.indexOf(item.destCityId) > -1
          )
        })
        return this.$nextTick()
      }).then(() =>{
        // 如果已选中的路线不在列表中则清空
        if(this.form.lineId && this.routerList.findIndex(item => item.id == this.form.lineId) < 0){
          this.form.lineId = null
        }
      })
    },
    // 计算体积
    calcVolume(row) {
      if (!row.boxGauge || !row.num) return false
      try {
        row.volume = (this.evil(row.boxGauge) * row.num).toFixed(2)
      } catch (e) {
        row.volume = ''
      }
    },
    evil(fn) {
      const Fn = Function
      return new Fn('return ' + fn)()
    },
    // 删除一条产品
    delProduct(index) {
      this.$confirm(this.$t('delivery.delPro')).then((res) => {
        this.form.orderItemVOList.splice(index, 1)
      })
    },
    getCoupons() {
      if (!this.form.consigneeContactsId || !this.form.consignorContactsId) {
        return false
      }
      const data = Object.assign({}, this.form, {
        prodConditionParamList: this.form.orderItemVOList,
        consigneeCustomerContactsId: this.form.consigneeContactsId,
        consignorCustomerContactsId: this.form.consignorContactsId
      })
      getCustomerAvailableCouponList(data).then((res) => {
        this.couponList = res.data
      })
    },
    // 切换目的国
    handleChangeDestCountry(val) {
      console.log("handleChangeDestCountry", val)
      this.form.destCountryId = val
      if(this.form.destCountryId){
        this.form.objectiveId = null
        this.form.lineId = null
        this.selectedRouter = null
        this.getOpenedRouterList()
      }
    },
    // 切换目的城市
    handleChangeDestCity(val){
      this.form.objectiveId = val
      if(this.form.objectiveId){
        this.form.lineId = null
        this.selectedRouter = null
        this.form.destCountryId = this.destCityList.find(item => item.shi === val)?.guojia
        this.getOpenedRouterList()
      }
    },
    // 切换路线
    setLineId(lineId){
      this.form.lineId = lineId
      this.handleChangeLineId()
    },
    // 切换线路回调
    async handleChangeLineId(){
      await this.$nextTick()
      this.selectedRouter = this.routerList.find(item => item.id === this.form.lineId)
      console.log("handleChangeLineId",
          "路线", this.form.lineId,
          "目的市", this.selectedRouter?.destCityId,
          "目的国", this.selectedRouter?.destCountryId,
          "始发市", this.selectedRouter?.startCityId)
      if(this.form.lineId){
        this.form.objectiveId = this.selectedRouter?.destCityId
        this.form.destCountryId = this.selectedRouter?.destCountryId
        this.form.departureId = this.selectedRouter?.startCityId
      }
    },
    /** 提交按钮 */
    submitForm(status, flag = true) {
      this.$refs['form'].validate(async(valid, errors) => {
        if (!valid) {
          return this.$showFormValidateErrors(errors)
        }
        if(this.hasConsignee){
          var validatorArea = await validatorPhone({
            code: this.form.countryCode,
            mobile: this.form.consigneePhone
          })
          if (!validatorArea.data) return
        }
        if (this.form.isCargoControl) {
          var checkKyc = await checkKycStatus({
            controlCargoStatus: this.form.isCargoControl,
            lineId: this.form.lineId
          })
          switch (checkKyc.data.wareHouseStatus) {
            case 2:
              if (checkKyc.data.memberKycStatus != 2) {
                this.noticeVisble = true
                return
              }
              break
            case 3:
              if (checkKyc.data.companyKycStatus != 2) {
                this.noticeVisble1 = true
                return
              }
              break
            case 4:
              if (checkKyc.data.memberKycStatus != 2) {
                this.noticeVisble = true
                return
              }
              if (checkKyc.data.companyKycStatus != 2) {
                this.noticeVisble1 = true
                return
              }
              break
            case 5:
              if (
                checkKyc.data.memberKycStatus != 2 &&
                checkKyc.data.companyKycStatus != 2
              ) {
                this.noticeVisble = true
                return
              }
              break
          }
        }
        let isInclude = false
        this.form.orderItemVOList.map((item) => {
          // 如果商品特性包含不接受货物，不能创建订单或修改订单
          if (item.prodAttrArr.indexOf(4) != -1) {
            isInclude = true
          }
          item.prodAttrIds = item.prodAttrArr.join(',')
        })
        if (isInclude) {
          return this.$message({
            message: this.$t('delivery.isContainNotice'),
            type: 'warning'
          })
        }
        // this.form.orderItemVOList.map((item) => {
        //   item.prodAttrIds = item.prodAttrArr.join(',')
        // })
        this.transportList.map((item) => {
          if (item._enabled) {
            item.lineIds = Array.from(item.lineIdSet).join(',')
            item.channelIds = Array.from(item.channelIdSet).join(',')
          }
        })
        this.form.status = status

        // 校验目的国与收货人手机号地区是否匹配
        if (this.hasConsignee && this.form.countryCode) {
          const res = await checkCountryCode({
            areaCode: this.form.countryCode,
            currencyId: this.form.destCountryId
          })
          // 并不一致则提示
          if (!res.data) {
            await this.$confirm(this.$t('电话所在国与目的国不一致，请检查'))
          }
        }

        // 修改的提交
        if (this.form.orderId) {
          const data = Object.assign({}, this.form, {
            customDraweeVOList: this.customDraweeList,
            // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
            orderItemVOList: this.getProductListWithDefaultValue(),
            type: this.form.type?.join(","),
            hasConsignee: this.hasConsignee
          })
          updateOrder(data).then((response) => {
            this.$message({
              message: this.$t('common.success'),
              type: 'success'
            })
            if (flag) {
              this.$router.push(
                '/jiedao/jd-deliverysuccess?orderId=' + this.form.orderId
              )
            } else {
              this.$router.push('/jiedao/jd-postorder')
            }
            this.$bus.$emit('reload')
          })
          return
        }
        const data = Object.assign({}, this.form, {
          customDraweeVOList: this.customDraweeList,
          // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
          orderItemVOList: this.getProductListWithDefaultValue(),
          type: this.form.type?.join(","),
          hasConsignee: this.hasConsignee
        })

        // 添加的提交
        createOrder(data).then((response) => {
          if (status != 0) {
            this.$message({
              message: this.$t('common.success'),
              type: 'success'
            })
            this.$router.push(
              '/jiedao/jd-deliverysuccess?orderId=' + response.data
            )
          } else {
            this.$message({
              message: this.$t('保存草稿成功'),
              type: 'success'
            })
            this.$router.push('/jiedao/jd-postorder')
          }

          this.$bus.$emit('reload')
        })
      })
    },
    async handleCancel(){
      await this.$confirm(this.$t("是否需要返回?"))
      this.$router.back()
    },
    // 去除唛头首尾空格
    trimMarks(){
      this.form.marks = this.form.marks.trim()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__header .el-table__cell {
  background-color: #27417c;
  font-size: 13px;
  height: 48px;
  text-align: center;
  font-size: 13px;
  font-weight: 500;
  color: #ffffff;
}
::v-deep .el-descriptions-item__content .el-form-item{
  /*margin-bottom: 0;*/
}
.card-title {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
::v-deep .product-list .el-form-item__error {
  position: static;
}
::v-deep th.el-table__cell .cell {
  white-space: nowrap;
  .red {
    color: red;
  }
}
::v-deep .product-list .el-input-number--medium {
  width: 90px;
}
</style>
