<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">
      <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">
      <el-form-item
        v-if="
          selectedRouter &&
            (routeOtherServices.indexOf('1') > -1 ||
              routeOtherServices.indexOf('4') > -1)
        "
        :label="$t('delivery.header')"
        style="margin-top: 30px"
      >
        <el-checkbox-group v-model="form.type">
          <el-checkbox
            v-if="
              (!selectedRouter || routeOtherServices.indexOf('1') > -1) && false
            "
            label="1"
          >{{ $t("delivery.orderType1") }}</el-checkbox>
          <el-checkbox
            v-if="!selectedRouter || routeOtherServices.indexOf('2') > -1"
            label="2"
          >{{ $t("delivery.orderType2") }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-row :gutter="20" style="margin-top: 30px">
        <el-col :span="12">
          <el-form-item
            :label="$t('delivery.consigneeName')"
            prop="consigneeName"
          >
            <el-input
              v-model="form.consigneeName"
              :placeholder="$t('delivery.consigneeNameNotice')"
              style="width: 200px"
            />
            <el-button
              style="margin-left: 5px"
              type="text"
              @click="openConsignee"
            >{{ $t("delivery.openConsignee") }}</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('orderdetail.consigneeNameEn')"
            prop="consigneeNameEn"
          >
            <el-input
              v-model="form.consigneeNameEn"
              :placeholder="$t('delivery.consigneeNameNoticeEn')"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 30px">
        <el-col :span="12">
          <el-form-item
            :label="$t('delivery.consigneePhone')"
            prop="consigneePhone"
          >
            <el-select
              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
              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="12">
          <el-form-item :label="$t('delivery.consigneeCompany')">
            <el-input
              v-model="form.consigneeCompany"
              :placeholder="$t('delivery.consigneeCompanyNotice')"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('orderdetail.consigneeCompanyEn')">
            <el-input
              v-model="form.consigneeCompanyEn"
              :placeholder="$t('delivery.consigneeCompanyNoticeEn')"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Email">
            <el-input
              v-model="form.consigneeEmail"
              :placeholder="$t('delivery.emailNotice')"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-card>
        <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="2" 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.objective") }}</span>
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="objectiveId"
              required
              :error="$t('delivery.objectiveRules')"
            >
              <el-select
                v-model="form.objectiveId"
                :placeholder="$t('delivery.objectiveNotice')"
                clearable
              >
                <el-option
                  v-for="item in importCityList"
                  :key="item.id"
                  :label="$l(item, 'title')"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('delivery.router')"
            :span="2"
            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">
                  <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>
      </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>
          <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="0"
                  :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") }}
            </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 }}<div v-if="fee.insuranceCurrencyId == 1">
              {{ $t("delivery.dollar") }}
            </div>
            <div v-else>(RMB)</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card v-if="false" 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;
              "
            >预计费用</span>
          </div>
        </div>

        <el-descriptions :column="5" border>
          <el-descriptions-item label="保价费">
            {{ fee.insuranceFee || 0 }} 人民币
          </el-descriptions-item>
          <el-descriptions-item label="总运费">
            <div>{{ fee.seaNGN || 0 }}奈拉</div>
            <div>{{ fee.seaRMB || 0 }}人民币</div>
            <div>{{ fee.seaUSD || 0 }}美元</div>
          </el-descriptions-item>
          <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
          <el-descriptions-item label="总清关费">
            <div>{{ fee.clearanceNGN || 0 }}奈拉</div>
            <div>{{ fee.clearanceRMB || 0 }}人民币</div>
            <div>{{ fee.clearanceUSD || 0 }}美元</div>
          </el-descriptions-item>
          <el-descriptions-item label="其他费用">
            <!--TODO 缺少其他费用字段-->
            <el-input
              v-model="form.otherFee"
              placeholder=""
              style="width: 100px"
            />
            <selector
              v-model="form.otherFeeCurrencyId"
              :options="currencyList"
              label-field="titleZh"
              value-field="id"
              defaultable
              style="width: 100px"
            />
          </el-descriptions-item>

          <el-descriptions-item label="原价" :span="2">
            <!--TODO 缺少字段-->
            <div>{{ fee.clearanceNGN || 0 }}奈拉</div>
            <div>{{ fee.clearanceRMB || 0 }}人民币</div>
            <div>{{ fee.clearanceUSD || 0 }}美元</div>
          </el-descriptions-item>
        </el-descriptions>

        <div class="card-title" style="padding: 20px 0">
          <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;
              "
            >优惠信息</span>
          </div>
        </div>
        <el-row
          v-for="(item, index) in getDictDatas(DICT_TYPE.ECW_COUPON_TYPE)"
          :key="item.value"
          :gutter="10"
        >
          <el-col :span="4">{{ index + 1 }}.{{ item.label }}</el-col>
          <el-col :span="6">
            <!-- <el-select placeholder="">
                </el-select> -->
          </el-col>
          <el-col :span="4">-10美元</el-col>
          <el-col :span="6">有效期：永久有效</el-col>
        </el-row>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="优惠合计">
            1233.1美元
          </el-descriptions-item>
          <el-descriptions-item label="预计费用" />
        </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.common") }}</span>
          </div>
        </div>

        <el-descriptions :column="2" 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="" />
            </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"
              />
            </el-form-item>
          </el-descriptions-item>
          <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
          <el-descriptions-item
            v-if="collectionProxy"
            :label="$t('delivery.isCollection')"
          >
            <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-descriptions-item>
          <el-descriptions-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-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.issuingMethod')">
            <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-item :label="$t('delivery.deliveryDate')">
            <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
                v-model="form.deliveryDate"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </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
                v-model="form.warehouseType"
                :type="DICT_TYPE.ECW_WAREHOUSING_TYPE"
                defaultable
              />
            </el-form-item>
          </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
                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
            v-if="homeDeliveryService && form.harvestMethod == 2"
            :label="$t('delivery.deliveryaddress')"
            :span="2"
          >
            <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
                :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-item :label="$t('delivery.drawee')" :span="2">
            <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"
                :filter="(e) => e.value == '1' || e.value == '2'"
                defaultable
                form-type="radio"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="form.drawee == 3"
            :label="$t('delivery.customDraweeList')"
            :span="2"
          >
            <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>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card v-if="transport" 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;
              "
            >{{ $l(transport, "label") }}</span>
          </div>
        </div>
        <el-form-item :label="$t('delivery.number')">
          <el-input
            v-model="form.number"
            :placeholder="$t('delivery.numberNotice')"
          >
            <el-button
              slot="append"
              type="primary"
              @click="getOrderCourierNumber"
            >{{ $t("delivery.getNumber") }}</el-button>
          </el-input>
        </el-form-item>
        <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-form-item
          v-if="[2, 3, 4].indexOf(+form.transportId) > -1"
          :label="$t('delivery.customsClearCert')"
        >
          <dict-selector
            v-model="form.customsClearCert"
            form-type="radio"
            :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
            fomatter="bool"
            defaultable
          />
        </el-form-item>
        <el-form-item
          v-if="[2, 3, 4].indexOf(+form.transportId) > -1"
          :label="$t('delivery.clearCertRemark')"
        >
          <el-input v-model="form.remarks" />
        </el-form-item>
        <el-form-item
          v-if="[3, 4].indexOf(+form.transportId) > -1"
          :label="$t('delivery.isUnpack')"
        >
          <dict-selector
            v-model="form.isUnpack"
            form-type="radio"
            :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
            fomatter="bool"
          />
        </el-form-item>
        <el-form-item
          v-if="[3, 4].indexOf(+form.transportId) > -1"
          :label="$t('delivery.isSingleTicketTransport')"
        >
          <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-form-item :label="$t('delivery.packageType')">
          <template #label>
            {{ $t("delivery.packageType") }}
          </template>
          <el-tooltip
            :content="$t('delivery.packageTypeNotice')"
            placement="top"
            style="margin-right: 15px"
          >
            <i class="el-icon-question" />
          </el-tooltip>
          <dict-selector
            v-model="form.packageType"
            form-type="checkbox"
            :type="DICT_TYPE.ORDER_SPECIAL_NEEDS"
            multiple
          />
        </el-form-item>
        <el-form-item :label="$t('delivery.packageRemarks')">
          <el-input v-model="form.packageRemarks" />
        </el-form-item>
      </el-card>

      <el-form-item label="">
        <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)"
        >{{ $t("提交") }}</el-button>
        <el-button
          v-if="form.status == 2 && !editFlag"
          type="primary"
          @click="submitForm(2, false)"
        >{{ $t("提交") }}</el-button>
        <el-button @click="$router.back()">{{ $t("common.cancel") }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 收货人列表弹窗 -->
    <el-dialog
      :title="$t('delivery.openConsignee')"
      :visible.sync="consigneeVisdle"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <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
} 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'
export default {
  name: 'OrderEdit',
  components: {
    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: [],
      customerList: [], // 客户信息
      productAttrList: [], // 商品属性
      channelList: [], // 出货取到
      routerList: [],
      transportTypeList: [], // 运输方式
      couponTypeList: [], // 优惠卷类型
      consignee: null,
      consignor: null,
      // transportList: [],
      currencyList: [],
      tradeCityList: [],
      unitList: [],
      couponList: [],
      fee: {}, // 费用
      form: {
        countryCode: '86',
        status: 0,
        consigneeName: '',
        consigneePhone: '',
        consigneeCompany: '',
        consigneeEmail: '',
        consigneeAddress: '',
        marks: '',
        isCargoControl: false,
        isCollection: false,
        customsClearCert: false,
        isSingleTicketTransport: false,
        isUnpack: false,
        drawee: 2,
        type: [],
        orderItemVOList: []
      },
      // 总条数
      total: 0,
      // 查询参数
      customeParams: {
        page: 1,
        rows: 10
      },
      editFlag: true,
      consigneeVisdle: false,
      addCustomerShow: false,
      addCustomerForm: {
        defaultContact: false
      },
      groupList: [],
      rules: {
        consigneeName: [
          {
            required: true,
            message: this.$t('delivery.consigneeNameNotice'),
            trigger: 'blur'
          }
        ],
        consigneeCompany: [
          {
            required: true,
            message: this.$t('delivery.consigneeCompanyNotice'),
            trigger: 'blur'
          }
        ],
        consigneePhone: [
          {
            required: true,
            message: this.$t('delivery.consigneePhoneNotice'),
            trigger: 'blur'
          },
          { pattern: /^[0-9]\d*$/, message: this.$t('customer.phoneRules2') }
        ],
        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') }
        ],
        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') }
        ]
      },
      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
    }
  },
  computed: {
    exportCityList() {
      return this.tradeCityList.filter(
        (item) => item.type == 2 || item.type == 3
      )
    },
    importCityList() {
      return this.tradeCityList.filter(
        (item) => 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
    }
  },
  watch: {
    $route() {
      location.reload()
    },
    // 始发地
    'form.departureId'() {
      this.getOpenedRouterList()
    },
    // 目的地
    'form.objectiveId'() {
      this.getOpenedRouterList()
    },
    'form.transportId'() {
      this.getOpenedRouterList()
    },
    'form.isCargoControl'() {
      // this.isCargoControlDrawee()
      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.calculationPrice()
      this.getIdCardData()
      await this.getChannelList()
    },
    // 选择送货上门需要查询并填充默认地址
    'form.harvestMethod'(harvestMethod) {
      console.log(harvestMethod)
    },
    // 选择的路线变化后，需要判断是否开通了对应的服务，如果没开通需要取消对应的服务选择
    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
      }
    }
  },
  async created() {
    // this.getIdCard()
    if (this.$route.query.tranfId) {
      setTimeout(() => {
        this.$set(this.form, 'transportId', this.$route.query.tranfId)
      }, 500)
    }
    if (this.$route.query.id) {
      getOrderDetail(this.$route.query.id).then((res) => {
        this.form = Object.assign({}, res.data, { orderItemVOList: [] })
        this.form.deliveryDate = res.data.deliveryDate
        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 (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) => {
            item.prodAttrArr = item.prodAttrIds
              .split(',')
              .filter((item) => item != '')
              .map((attrId) => +attrId)
            this.form.orderItemVOList.push({ ...item })
          })
        })
      })
    } else this.addProduct()
    this.getCustomerList()
    getCountryList().then((r) => {
      this.countryList = r.data
    })
    getData({ page: 1, rows: 100, dictType: 'transport_type' }).then((r) => {
      this.transportTypeList = r.data.list
    })
    getData({ page: 1, rows: 100, dictType: 'coupon_type' }).then((r) => {
      this.couponTypeList = r.data.list
    })
    getGroupList({ page: 1, rows: 100 }).then((r) => {
      this.groupList = r.data.list
      this.groupList.push({ id: 0, title: this.$t('delivery.none') })
    })
    getProductAttrList().then((res) => (this.productAttrList = res.data))
    // getChannelList().then((res) => (this.channelList = res.data))
    await this.getTradeCity()
    await this.getChannelList()
    getCurrencyList().then((res) => (this.currencyList = res.data))
  },
  methods: {
    async getTradeCity() {
      const query = {}
      if (this.form.channelId) {
        query.channelId = this.form.channelId
      }
      this.tradeCityList = (await getTradeCityList(query)).data
    },
    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() {
      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
    },
    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()
      }
    },
    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: [] })
    },
    // 计算商品运费(根据货值计算保费)
    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
      }
      await this.$nextTick()
      getOpenedRouterList(params).then((res) => {
        this.routerList = res.data.filter((item) => {
          return (
            this.exportCityIds.indexOf(item.startCityId) > -1 &&
            this.importCityIds.indexOf(item.destCityId) > -1
          )
        })
      })
    },
    // 计算体积
    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
      })
    },
    /** 提交按钮 */
    submitForm(status, flag = true) {
      this.$refs['form'].validate(async(valid, errors) => {
        if (!valid) {
          return this.$showFormValidateErrors(errors)
        }
        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.type =
          this.form.type.length > 0 ? this.form.type.toString : ''
        this.form.status = status
        // 修改的提交
        if (this.form.orderId) {
          const data = Object.assign({}, this.form, {
            customDraweeVOList: this.customDraweeList,
            // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
            orderItemVOList: this.getProductListWithDefaultValue()
          })
          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()
        })
        // 添加的提交
        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')
        })
      })
    }
  }
}
</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;
}

.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>
