<template>
  <div class="app-container">
    <!--初始化过程中不渲染页面，利用此特性在新建订单后重新初始化表单(字典选择组件默认值)-->
    <el-form v-if="!initing"
             ref="form"
             :model="form"
             :rules="rules"
             label-position="left"
             inline
             :key="$route.fullPath"
             :disabled="updateChannel || updateWorth"
             :validate-on-rule-change="false"
    >
      <el-card v-if="form.applyStatus == 1" class="mb-10">
        <div slot="header" class="card-title">{{ $t('以下信息修改审核中') }}</div>
        <el-table :data="form.applyInfoList">
          <el-table-column label="字段" prop="name"></el-table-column>
          <el-table-column label="旧内容" prop="orgValue"></el-table-column>
          <el-table-column label="新内容" prop="newValue"></el-table-column>
        </el-table>
      </el-card>
      <div class="page-title">{{ editMode ? $t('编辑订单') + '-' + (form.orderNo || $t('草稿')) : $t('新建订单') }}
      </div>

      <el-card class="form-section mt-10">
        <template #header>
          <div slot="header" class="card-title">发货人</div>
        </template>
        <el-form-item :label="$t('名称')" prop="consignorContactsId">
          <!-- <customer-contact-selector v-model="form.consignorContactsId" @change="consignorContact = $event" type="1" /> -->
          <div class="contact">
            <el-input v-model="form.consignorName" placeholder="" :disabled2="inWarehouse"/>
            <img v-if="!(updateChannel || updateWorth)" disabled src="@/assets/svg/contacts.svg" class="phonebook"
                 @click="contactChooseType='consignor'"/>
            <img v-if="!(updateChannel || updateWorth )" src="@/assets/svg/contact_create.svg" class="phonebook"
                 @click="quickCreateType='0'"/>
          </div>
        </el-form-item>
        <el-form-item :label="$t('电话')" prop="consignorPhone">
          <div class="flex">
            <area-code-selector v-model="form.consignorCountryCode" class="w-200 mr-10" disabled/>
            <el-input v-model="form.consignorPhone" class="w-200" disabled/>
          </div>
        </el-form-item>

        <el-button circle icon="el-icon-circle-plus" v-if="!showFullConsignor"
                   @click="showFullConsignor=true"></el-button>
        <el-button circle icon="el-icon-remove" v-else @click="showFullConsignor=false"></el-button>

        <div v-if="showFullConsignor">
          <el-form-item :label="$t('英文名称')" prop="consignorNameEn">
            <!-- <customer-contact-selector v-model="form.consignorContactsId" @change="consignorContact = $event" type="1" /> -->
            <div class="contact">
              <el-input v-model="form.consignorNameEn" placeholder="" :disabled2="inWarehouse"/>
            </div>
          </el-form-item>
          <el-form-item :label="$t('公司中文名称')" prop="consignorPhone">
            <el-input v-model="form.consignorCompany" :disabled2="inWarehouse"/>
          </el-form-item>
          <!-- v1.7新增 -->
          <el-form-item :label="$t('公司英文名称')" prop="consignorPhone">
            <el-input v-model="form.consignorCompanyEn" :disabled2="inWarehouse"/>
          </el-form-item>
          <el-form-item label="Email" prop="consignorPhone">
            <el-input v-model="form.consignorEmail" :disabled2="inWarehouse"/>
          </el-form-item>
        </div>
      </el-card>
      <!--el-card如果只有header没有主题会显示异常，所以没有收货人的时候单独用一个-->
      <el-card class="form-section mt-10" v-if="!hasConsignee">
        <div class="flex items-center">
          <div class="card-title mr-20">收货人</div>
          <el-radio-group v-if="noConsignee" v-model="hasConsignee">
            <el-radio :label="true">{{ $t('有') }}</el-radio>
            <el-radio :label="false">{{ $t('无') }}</el-radio>
          </el-radio-group>
        </div>
      </el-card>
      <el-card class="form-section mt-10" v-else>
        <template #header>
          <div class="flex items-center">
            <div class="card-title mr-20">收货人</div>
            <el-radio-group v-if="noConsignee" v-model="hasConsignee">
              <el-radio :label="true">{{ $t('有') }}</el-radio>
              <el-radio :label="false">{{ $t('无') }}</el-radio>
            </el-radio-group>
          </div>
        </template>
        <el-form-item v-if="hasConsignee" :label="$t('名称')" prop="consigneeContactsId">
          <!-- <customer-contact-selector v-model="form.consignorContactsId" @change="consignorContact = $event" type="1" /> -->
          <div class="contact">
            <el-input v-model="form.consigneeName" placeholder="" :disabled="!hasConsignee"/>
            <img v-if="!(updateChannel || updateWorth) && hasConsignee" src="@/assets/svg/contacts.svg" class="phonebook"
                 @click="contactChooseType='consignee'"/>
            <img v-if="!(updateChannel || updateWorth) && hasConsignee" src="@/assets/svg/contact_create.svg" class="phonebook"
                 @click="quickCreateType='1'"/>
          </div>
        </el-form-item>
        <!-- v1.7新增 -->

        <el-form-item v-if="hasConsignee" :label="$t('电话')" prop="consigneePhone">
          <div class="flex">
            <area-code-selector v-model="form.consigneeCountryCode" class="w-200 mr-10" disabled/>
            <el-input v-model="form.consigneePhone" class="w-200" disabled/>
          </div>
        </el-form-item>

        <el-button circle icon="el-icon-circle-plus" v-if="hasConsignee && !showFullConsignee"
                   @click="showFullConsignee=true"></el-button>
        <el-button circle icon="el-icon-remove" v-if="hasConsignee && showFullConsignee"
                   @click="showFullConsignee=false"></el-button>

        <div v-if="showFullConsignee">
          <el-form-item v-if="hasConsignee" :label="$t('英文名称')" prop="consigneeNameEn">
            <!-- <customer-contact-selector v-model="form.consignorContactsId" @change="consignorContact = $event" type="1" /> -->
            <div class="contact">
              <el-input v-model="form.consigneeNameEn" placeholder="" :disabled="!hasConsignee"/>
            </div>
          </el-form-item>
          <el-form-item v-if="hasConsignee" :label="$t('公司中文名称')" prop="consigneePhone">
            <el-input v-model="form.consigneeCompany" :disabled="!hasConsignee"/>
          </el-form-item>
          <!-- v1.7新增 -->
          <el-form-item v-if="hasConsignee" :label="$t('公司英文名称')" prop="consigneePhone">
            <el-input v-model="form.consigneeCompanyEn" :disabled="!hasConsignee"/>
          </el-form-item>
          <el-form-item v-if="hasConsignee" label="Email" prop="consigneePhone">
            <el-input v-model="form.consigneeEmail" :disabled="!hasConsignee"/>
          </el-form-item>
        </div>
      </el-card>
      <el-card class="mt-10">
        <div slot="header" class="card-title">{{ $t('运输') }}</div>
        <div class="form-section">
          <el-form-item :label="$t('运输方式')" prop="transportId">
            <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="form.transportId" formatter="number"
                           clearable @input="updateRoutes('transportId')" :disabled="form.shipmentState > 0"/>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('始发城市')" prop="departureId" :disabled="false">
            <el-select v-model="form.departureId" :placeholder="$t('请选择始发地')" :disabled="form.shipmentState > 0"
                       clearable @input="updateRoutes('departureId')">
              <el-option v-for="item in exportCityList" :label="$l(item, 'title')" :value="item.id"
                         :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的国家')" prop="destCountryId">
            <el-select v-model="form.destCountryId" :placeholder="$t('请选择目的国家')"
                       @change="handleChangeDestCountry" clearable :disabled="form.shipmentState > 0">
              <el-option v-for="item in showDestCountryList" :label="$l(item, 'guojiaName')" :value="item.guojia"
                         :key="item.guojia"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的城市')" prop="objectiveId">
            <el-select v-model="form.objectiveId" :placeholder="$t('请选择目的地')" @change="handleChangeDestCity"
                       clearable>
              <el-option v-for="item in showDestCityList" :label="$l(item, 'shiName')" :value="item.shi"
                         :key="item.shi"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('选择线路')" prop="lineId">
            <el-input
              :value="selectedRouter ? $l(selectedRouter, 'startTitle') + ' > ' + $l(selectedRouter, 'destTitle') : ''"
              disabled :placeholder="$t('请在右侧选择线路')"></el-input>
          </el-form-item>
          <!--select是原生组件，不受el-form的disabled控制-->
          <select size="5" v-model="form.lineId" style="min-width: 300px; border:1px solid #DCDFE6; border-radius:4px"
                  @change="handleChangeLineId" :disabled="updateWorth" >
            <option v-for="item in routerList" :value="item.id" :key="item.id">
              {{ $l(item, 'startTitle') }} >> {{ $l(item, 'destTitle') }}
              (
              <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="item.transportType"></dict-tag>
              )
            </option>
          </select>
        </div>
        <div class="form-section mt-10">
          <el-form-item :label="$t('出货渠道')" prop="channelId"
                        v-if="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass == 'channel'">
            <!--嵌套一个form来脱离disabled控制-->
            <el-form>
              <selector
                v-model="form.channelId"
                :options="channelList"
                value-field="channelId"
                :label-field="$l(null, 'name')"
                :disabled="updateWorth"
                clearable
              ></selector>
            </el-form>
          </el-form-item>
        </div>
        <div>
          <!--默认显示类型(selectedRouter==null)，如果选择路线后没开通则隐藏-->
          <el-form-item :label="$t('增值服务')"
                        v-if="routeOtherServices.indexOf('1') > -1 || routeOtherServices.indexOf('4') > -1">
            <el-checkbox-group v-model="form.type">
              <el-checkbox label="1" v-if="routeOtherServices.indexOf('1') > -1">{{ $t('集运') }}</el-checkbox>
              <el-checkbox label="2" v-if="routeOtherServices.indexOf('4') > -1" :disabled="form.shipmentState > 0">
                {{ $t('海外仓') }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </el-card>
      <el-card class="mt-10">
        <div slot="header" class="card-title">
          <!--lanbm 根据需求文档改 商品信息 为 商品 -->
          <div class="card-name">{{ $t('商品') }}</div>
        </div>
        <el-table :data="form.orderItemVOList" border class="product-list" v-if="!initing">
          <el-table-column :label="$t('序号')" width="60px" fixed>
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('中文品名')" width="160px">
            <template slot="header" slot-scope="scope">
              {{ $t('中文品名') }} <span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item label=""
                            :prop2="`orderItemVOList.${scope.$index}.prodId`"
                            :rules2="{
                            // required: true, message: $t('请选择产品'), trigger: 'blur'
                        }"
                            class="mb-0 mr-0"
              >
                <product-selector
                  @hook:mounted="onTableMounted"
                  v-model="scope.row.prodId"
                  @change="onProductChange(scope.row, $event)"
                  :disabled="!canAddProduct || !productEditable"
                  @focus="scope.row.updated = true"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('英文品名')" width="160px">
            <template slot="header" slot-scope="scope">
              {{ $t('英文品名') }} <span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <product-selector
                lang="En"
                v-model="scope.row.prodId"
                @change="onProductChange(scope.row, $event)"
                @focus="scope.row.updated = true"
                :disabled="!canAddProduct || !productEditable"/>
            </template>
          </el-table-column>

          <el-table-column :label="$t('品牌')" width="100px">
            <template slot="header">
              {{ $t('品牌') }} <span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item label=""
                            :prop="`orderItemVOList.${scope.$index}.brandType`"
                            :rules="{
                            required: true, message: $t('请选择品牌'), trigger: 'blur'
                        }"
                            class="mb-0 mr-0"
              >
                <dict-selector v-model="scope.row.brandType" :type="DICT_TYPE.ECW_IS_BRAND" defaultable
                               :disabled="!canAddProduct || !productEditable"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('件数')" width="90px">
            <template slot="header">
              {{ $t('件数') }} <span class="red">*</span>
            </template>
            <template slot-scope="{row}">
              <el-input-number :min="1" :step="1" :controls="false" style="width: 65px" v-model="row.num"
                               :disabled="!canAddProduct || !productEditable"/>
            </template>
          </el-table-column>
          <el-table-column :label="$t('包装单位')" width="100px">
            <template slot="header" slot-scope="scope">
              {{ $t('包装单位') }} <span class="red">*</span>
            </template>
            <template slot-scope="{row}">
              <dict-selector v-model="row.unit" :type="DICT_TYPE.ECW_PACKAGING_TYPE" defaultable
                             :disabled="!canAddProduct || !productEditable"/>
            </template>
          </el-table-column>
          <el-table-column :label="`${$t('数量')}(${$t('个')})`" width="120px">
            <template slot-scope="{row}">
              <el-input-number :min="1" :step="1" style="width: 80px;" :controls="false" v-model="row.quantity"
                               :disabled="!canAddProduct || !productEditable"/>
            </template>
          </el-table-column>
          <el-table-column :label="$t('总体积') + '(m³)'" width="120px">
            <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-number :min="0" v-model="scope.row.volume" :disabled="!canAddProduct || !productEditable"
                                 :controls="false" style="width: 80px"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('总重量') + '(kg)'" width="120px">
            <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-number :min="0" :controls="false" style="width: 80px" v-model="scope.row.weight"
                                 :disabled="!canAddProduct || !productEditable"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('总货值') + '(RMB)'" width="100px">
            <template slot="header" slot-scope="scope">
              {{ $t('货值') }}(RMB) <span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <!-- 重写el-form标签，根据自定义规则控制disabled -->
              <el-form :model="form">
                <el-form-item label=""
                              :prop="`orderItemVOList.${scope.$index}.worth`"
                              :rules="[
                              { required: true, message: $t('货值不能为空'), trigger: 'blur'},
                              { type: 'number', min: 0, message: $t('货值错误'), trigger: 'blur'}
                          ]"
                              class="mb-0 mr-0"
                >

                  <!--input事件在快速输入的时候，可能最后拿到的结果不是最后输入的参数，所以改成在blur的时候计算-->
                  <el-input-number :min="0" :controls="false" style="width: 80px" v-model.number="scope.row.worth"
                                   :disabled="updateChannel || !canAddProduct" @blur="calculationPrice"/>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column :label="$t('商品特性')" width="250px">
            <template slot-scope="{row}">
              <el-checkbox-group v-model="row.prodAttrArr" @change="onProductAttrChange(row, $event)"
                                 :disabled="row.prodAttrArr.indexOf(4)!=-1||!canAddProduct || !productEditable">
                <el-checkbox v-for="item in productAttrList" :label="item.id" :key="item.id">
                  {{ $l(item, 'attrName') }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </el-table-column>

          <el-table-column :label="$t('是否预付')">
            <template slot-scope="{row}">
              <dict-tag v-if="row.fee" :type="DICT_TYPE.ECW_PAY_ADVANCE" :value="row.fee.isPayAdvance"/>
            </template>
          </el-table-column>
          <el-table-column :label="$t('商品链接')" width="200px" align="center">
            <template slot-scope="{row}">
              <el-link type="primary" :href="row.link" target="_blank" style="display:block">{{ row.link }}</el-link>
              <el-button type="primary" size="mini" @click="setLink(row)" v-if="productEditable">
                {{ row.link ? $t('编辑商品链接') : $t('添加商品链接') }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column :label="$t('快递单号')" width="100px">
            <template slot-scope="{row}">
              <el-input v-model="row.expressNo" placeholder="" :disabled="!productEditable"/>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" width="80px" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="delProduct(scope.$index)"
                         :disabled="!productEditable || updateChannel || updateWorth">{{ $t('删除') }}
              </el-button>
            </template>
          </el-table-column>

        </el-table>
        <div class="flex justify-end mt-10">
          <el-button type="primary" size="mini" @click="addProduct(null)"
                     :disabled="!canAddProduct || !productEditable || updateChannel || updateWorth">{{ $t('添加') }}
          </el-button>
          <el-button type="primary" size="mini" @click="showBatchImportDialog=true"
                     :disabled="!canAddProduct || !productEditable || updateChannel || updateWorth">{{ $t('批量添加') }}
          </el-button>
        </div>
        <!--
    </el-card>
    <el-card  class="mt-10"> -->
        <div class="card-title" style="padding:20px 0;">{{ $t('合计') }}</div>
        <el-descriptions :column="6" border>
          <el-descriptions-item :label="$t('总件数')">
            {{ sum.totalNum.toFixed() }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('总体积')">
            {{ sum.totalVolume.toFixed() }}m³
          </el-descriptions-item>
          <el-descriptions-item :label="$t('总重量')">
            {{ sum.totalWeight.toFixed() }}kg
          </el-descriptions-item>
          <el-descriptions-item :label="$t('总数量')">
            {{ sum.totalQuatity.toFixed() || 0 }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('总货值') + '(RMB)'">
            {{ sum.totalWorth.toFixed() || 0 }}元
          </el-descriptions-item>
          <el-descriptions-item :label="$t('保价费')">
            {{ fee.insuranceFee || 0 }}
            {{ selectedRouter ? currentcyMap[selectedRouter.currencyUnit || 1] : '' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="mt-10 right-label">
        <div class="card-title" slot="header">{{ $t('通用') }}</div>
        <div class="form-section">
          <el-form-item :label="$t('唛头')" prop="marks" class="w-500">
            <el-input v-model="form.marks" @blur="trimMarks"></el-input>
          </el-form-item>
          <el-form-item :label="$t('单证报关')" :span="2" prop="customsType">
            <template #label>
              {{ $t('单证报关') }}
              <el-tooltip effect="dark"
                          :content="$t('我司全代 : 该货物的出口手续由我司代为办理 ; 自单代报: 该货物由发货人提供相关出口单证并委托我司代为办理 ;混单代报该货物有以上两种情况出现')"
                          placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
            <!--241023 已起运不让修改报关方式-->
            <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="form.customsType" form-type="radio" defaultable
                           :disabled="isShipment"/>
            <!--自单代报显示提示-->
            <div v-if="+form.customsType === 2" style="color:red;font-size:14px">{{ $t('报关退税，请备齐资料。') }}</div>
          </el-form-item>
        </div>
        <div class="form-section" v-if="form.transportId == 3">
          <!--目的港清关：选择专线空运才显示，默认选中我司
          我司选中后，按钮下方显示“多票”和“单票”的操作，默认选中多票。
          客户选中后，按钮下方显示“单票”的操作，默认选中，无需点击-->
          <el-form-item :label="$t('目的港清关')" class="w-500">
            <el-radio-group v-model="form.portDestCustomsClear">
              <el-radio :label="1">
                {{ $t('我司') }}
                <el-tooltip effect="dark" :content="$t('我司承接')" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </el-radio>
              <el-radio :label="2">
                {{ $t('客户') }}
                <el-tooltip effect="dark" :content="$t('客户自清')" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('发货方式')">
            <el-radio-group v-model="form.deliveryWay">
              <el-radio :label="1" v-if="form.portDestCustomsClear == 1">{{ $t('多票') }}</el-radio>
              <el-radio :label="2">{{ $t('单票') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('是否控货')" prop="isCargoControl" class="w-500">
            <template #label>
              {{ $t('是否控货') }}
              <el-tooltip effect="dark"
                          :content="$t('是指由发货人与收货人约定在货物的国际运输过程中，我司作为第三方对该货物货权的控制;需由发货人授权我司放货的情况下收货人才能提取该票货物的一种交易方式')"
                          placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
            <!--无收货人的情况下必须控货且不能更改-->
            <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                           v-model="form.isCargoControl"
                           formatter="bool"
                           form-type="radio"
                           :disabled="!hasConsignee"
                           :filter="(item) => {
                          return selectedRouter && selectedRouter.controlStatus === 1 && item.value === 'true' ? false : true
                       }"
            />
          </el-form-item>
          <el-form-item :label="$t('付款人')" prop="drawee" class="w-500">
            <dict-selector :formatter="Number" :type="DICT_TYPE.DRAWEE" v-model="form.drawee" defaultable
                           form-type="radio" :disabled="false"/>
            <el-table :data="customDraweeList" v-if="form.drawee==3">
              <el-table-column :label="$t('费用类型')" prop="label" width="200px"></el-table-column>
              <el-table-column :label="$t('付款人')" width="300px">
                <template slot-scope="{row}">
                  <dict-selector :formatter="Number" :type="DICT_TYPE.DRAWEE"
                                 :filter="(e) => e.value == 1 || e.value == 2" v-model="row.value" form-type="radio"
                                 :disabled="false"/>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item :label="$t('提单是否显示价格')" prop="displayBillLadingPrice">
            <el-radio-group v-model="form.displayBillLadingPrice">
              <el-radio :label="true">{{ $t('显示') }}</el-radio>
              <el-radio :label="false">{{ $t('不显示') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="form-section flex">
          <el-form-item :label="$t('入仓类型')" prop="warehouseType" class="w-500">
            <dict-selector :type="DICT_TYPE.ECW_WAREHOUSING_TYPE" v-model="form.warehouseType" defaultable
                           :disabled="false"/>
          </el-form-item>
          <div>
            <el-form-item :label="$t('外部仓库')" prop="isExternalWarehouse">
              <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" class="flex" :key="index">
                <div class="w-380">
                  <el-form-item :label="$t('装货时间')"
                                :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-200"></el-date-picker>
                  </el-form-item>
                </div>
                <div class="w-500">
                  <el-form-item :label="$t('装货地址')"
                                :prop="'externalWarehouseDtoList.' + index + '.loadingAddress'"
                                :rules="{
                              required: true, message: '装货地址不能为空', trigger: 'blur'
                              }"
                  >
                    <el-input v-model="item.loadingAddress" placeholder="" class="w-200"></el-input>
                  </el-form-item>
                  <el-button type="primary" icon="el-icon-plus" v-if="index==0"
                             @click="form.externalWarehouseDtoList.push({})"></el-button>
                  <el-button type="danger" icon="el-icon-delete"
                             v-else-if="index == form.externalWarehouseDtoList.length-1"
                             @click="form.externalWarehouseDtoList.splice(index, 1)"></el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('预计送货日期')" prop="deliveryDate" v-if="!form.isExternalWarehouse" class="w-500">
            <el-date-picker v-model="form.deliveryDate" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('是否代收货款')" prop="isCollection" v-if="collectionProxy" class="w-500">
            <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" v-model="form.isCollection"
                           form-type="radio" :disabled="false"/>
          </el-form-item>
          <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
          <el-form-item :label="$t('代收货款金额')" v-if="collectionProxy && form.isCollection" prop="collectionProxy">
            <el-input type="number" v-model="form.collectionProxy" class="w-200 mr-10" :disabled="false"></el-input>
            <selector v-model="form.collectionProxyCurrency" :options="currencyList" label-field="titleZh"
                      value-field="id" defaultable class="w-100" :disabled="false"/>
          </el-form-item>
        </div>
        <div class="form-section flex">
          <el-form-item :label="$t('收货方式')" prop="harvestMethod" class="w-500">
            <el-select v-model="form.harvestMethod" @change="handleChange">
              <el-option :label="$t('自提')" :value="1"></el-option>
              <el-option v-if="homeDeliveryService" :label="$t('送货上门')" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('关联报价单')" prop="offerId">
            <span v-if="offerIdNochange&&offerNumber">{{ offerNumber }}</span>
            <el-select
              v-else
              v-model="form.offerId"
              filterable
              clearable
              reserve-keyword
              :disabled="offerIdNochange"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="(item, index) in offerData"
                :key="index"
                :label="item.number"
                :value="item.offerId"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-section" v-if="form.harvestMethod == 2">
          <el-form-item :label="$t('收货地区')" prop="country">
            <area-selector
              :country="form.country"
              :province="form.province"
              :city="form.city"
              @countryChange="onAreaChange('country', $event)"
              @provinceChange="onAreaChange('province', $event)"
              @cityChange="onAreaChange('city', $event)"
              :disabled="false"
            ></area-selector>
          </el-form-item>
          <br/>
          <el-form-item :label="$t('收货详细地址')" prop="consigneeAddress">
            <el-input v-model="form.consigneeAddress" :disabled="false" class="w-300"></el-input>
          </el-form-item>
        </div>
      </el-card>
      <el-card class="mt-10">
        <template #header>
          <div class="card-title">其他</div>
        </template>
        <div class="form-section">
          <el-form-item :label="$t('特殊要求')">
            <template #label>
              {{ $t('特殊要求') }}
              <el-tooltip effect="dark" :content="$t('如需我司打包，请勾选相应选项，费用付款人及打包要求可备注补充')"
                          placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
            <dict-selector v-model="form.packageTypeArr" form-type="checkbox" :type="DICT_TYPE.ORDER_SPECIAL_NEEDS"
                           multiple :disabled="false"/>
          </el-form-item>
          <el-form-item :label="$t('特殊要求备注')">
            <el-input v-model="form.packageRemarks" :disabled="false"></el-input>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('快递单号')">
            <el-input v-model="form.number" :placeholder="$t('请输入购买商品的快递单号')" :disabled="false">
              <el-button type="primary" slot="append" @click="getOrderCourierNumber" :disabled="updateWorth">
                {{ $t('生成单号') }}
              </el-button>
            </el-input>
          </el-form-item>
        </div>
        <div class="form-section" v-if="[2,3,4].indexOf(+form.transportId) > -1">
          <el-form-item :label="$t('清关证书')">
            <dict-selector v-model="form.customsClearCert" form-type="radio" :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                           formatter="bool" :defaultable="!editMode" :disabled="false"/>
          </el-form-item>
          <el-form-item :label="$t('清关证书备注')">
            <el-input v-model="form.customsClearCertRemarks" :disabled="false"></el-input>
          </el-form-item>
        </div>
        <div class="form-section" v-if="[3,4].indexOf(+form.transportId) > -1">
          <el-form-item :label="$t('是否拆包')">
            <dict-selector v-model="form.isUnpack" form-type="radio" :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                           formatter="bool" :defaultable="!editMode" :disabled="false"/>
          </el-form-item>
          <el-form-item :label="$t('单票立刻转运')" v-if="[3,4].indexOf(+form.transportId) > -1">
            <dict-selector v-model="form.isSingleTicketTransport" form-type="radio"
                           :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" :defaultable="!editMode"
                           :disabled="false"/>
            <span
              style="margin-left:10px">{{ $t('注：若只有一件，货到仓库立即发，选“是”，多件需仓库集运待发，选“否”') }}</span>
          </el-form-item>
        </div>
        <!-- 20240823 新需求改动：屏蔽出单方式 和 是否双清字段
        https://471hsh.axshare.com/?id=uc7auj&p=%E5%90%8E%E5%8F%B0%E5%88%9B%E5%BB%BA%E8%AE%A2%E5%8D%95%E9%A1%B5%E9%9D%A2&g=1
          <el-form-item :label="$t('出单方式')" prop="issuingMethod">
              <dict-selector :type="DICT_TYPE.ECW_SUING_METHOD" v-model="form.issuingMethod" form-type="radio" defaultable  :disabled="false"/>
          </el-form-item>
          <div v-if="[2,3,4].indexOf(+form.transportId) > -1">
            <el-form-item :label="$t('是否双清')">
              <dict-selector v-model="form.doubleClear" form-type="radio" :type="DICT_TYPE.ECW_DOUBLE_CLEAR" defaultable :disabled="false" />
            </el-form-item>
          </div>
        </div>-->
        <!--20240823 新需求原型没有船公司字段，暂时屏蔽
        <div  v-if="[2].indexOf(+form.transportId) > -1">
          <el-form-item :label="$t('船公司')">
            <supplier-selector v-model="form.shippingCompany" company-type="9" :disabled="false" />
          </el-form-item>
        </div>-->
      </el-card>

      <el-card class="mt-10" v-if="showWorkFlow">
        <div class="card-title" slot="header">{{ $t('审批流程') }}</div>
        <work-flow :xmlkey="updateChannel ? 'shipment_channel_change' : 'order_modify'" v-model="ccIdArr"/>
      </el-card>

      <div style="margin: 30px 0; display: flex">
        <!--返回按钮应该在表单被禁用的情况下也可以点击，所以需要用一个form来包裹以脱离原form的disabled控制-->
        <el-form inline class="mr-10">
          <el-button @click="$store.dispatch('tagsView/delCurrentView')">{{ $t('返回') }}</el-button>
        </el-form>

        <template v-if="form.applyStatus == 1">
          <el-button type="primary" @click="$router.push('/bpm/process-instance/detail?id=' + form.formId)">
            {{ $t('审核中') }}
          </el-button>
        </template>
        <!--更新渠道的时候用一个form包裹按钮，脱离原form的disabled控制-->
        <el-form v-else-if="updateChannel || updateWorth" inline>
          <el-button type="primary" @click="submitForm(2)">{{ $t('编辑订单') }}</el-button> <!--修改-->
        </el-form>
        <template v-else>
          <el-button type="primary" @click="submitForm(0)" v-if="!form.status">{{ $t('保存草稿') }}</el-button><!--草稿-->
          <el-button type="primary" @click="submitForm(2)" v-if="!form.orderId || !form.status">{{ $t('新建订单') }}
          </el-button> <!--待入仓-->
          <el-button type="primary" @click="submitForm(2)" v-else>{{ $t('编辑订单') }}</el-button> <!--修改-->
        </template>
      </div>
    </el-form>

    <el-dialog :title="$t('批量导入')" :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('上传装箱单')"></el-step>
        <el-step :title="$t('开始导入')"></el-step>
        <el-step :title="$t('完成')"></el-step>
      </el-steps>
      <div class="mt-20">
        <el-upload :http-request="upload" :show-file-list="false" action="" class="mr-10"
                   style="display:inline-block; ">
          <el-button size="small" type="primary">{{ $t('点击上传') }}</el-button>
        </el-upload>
        <el-button type="info" @click="downloadTpl" size="small" :loading="exportLoading">{{ $t('装箱单模板') }}
        </el-button>
      </div>
      <el-table :data="importList" class="mt-10" height="300">
        <el-table-column :label="$t('序号')">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column :label="$t('中文品名')" prop="prodTitleZh"></el-table-column>
        <el-table-column :label="$t('英文品名')" prop="prodTitleEn"></el-table-column>
        <el-table-column :label="$t('品牌')" prop="brand">
          <template slot-scope="{row}">
            <dict-tag :type="DICT_TYPE.ECW_IS_BRAND" :value="row.brandType"/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('件数')" prop="num"></el-table-column>
        <el-table-column :label="$t('重量') + '(kg)'" prop="weight"></el-table-column>
        <el-table-column :label="$t('体积') + '(m³)'" prop="volume"></el-table-column>
        <!-- <el-table-column :label="$t('有无单证')" prop="">// TODO</el-table-column> -->
        <!-- <el-table-column :label="$t('缺货箱数')" prop="lessNum"></el-table-column> -->
        <el-table-column :label="$t('数量')" prop="quantity"></el-table-column>
        <el-table-column :label="$t('材质')" prop="material"></el-table-column>
      </el-table>

      <div class="mt-10 center">
        <el-button type="primary" @click="addToProductList">{{ $t('下一步') }}</el-button>
        <el-button type="default" @click="showBatchImportDialog=false">{{ $t('取消') }}</el-button>
      </div>
    </el-dialog>

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

<script>
import {
  createOrder,
  updateApply,
  getOrderDetail,
  getOrderCourierNumber,
  orderImport,
  exportPackingList,
  getUpdateInfo,
  updateShipmentApply
} from '@/api/ecw/order'
import ProductSelector from '@/components/ProductSelector'
import {getProductAttrList} from '@/api/ecw/productAttr'
import {getChannelList} from '@/api/ecw/channel'
import Selector from '@/components/Selector'
import CustomerContactSelector from '@/components/CustomerContactSelector'
import {getGuojiaAndShiAndWarehouseList, openedRouterList as getOpenedRouterList} from '@/api/ecw/warehouse'
import {checkCountryCode, getTradeCityList} from '@/api/ecw/region'
import {DICT_TYPE, getDictData, getDictDatas} from '@/utils/dict'
import {getCurrencyList} from '@/api/ecw/currency'
import {getUnitList} from '@/api/ecw/unit'
import AreaSelector from '@/components/AreaSelector'
import FileUpload from '@/components/FileUpload'
import AreaCodeSelector from '@/components/AreaCodeSelector'
import ChooseContactDialog from '@/components/ChooseContactDialog'
import QuickCreateCustomer from '@/components/QuickCreateCustomer'
import {calculationPrice} from '@/api/ecw/product'
import SupplierSelector from '@/components/SupplierSelector'
import Decimal from 'decimal.js'
import WorkFlow from '@/components/WorkFlow'
import {getCustomer} from "@/api/ecw/customer";
import {debounce} from "@/utils";
import {getOfferSelect, getOfferCheck} from "@/api/ecw/offer"
import Template from '@/views/cms/template/index.vue'
import {checkBillOfLadingService} from "@/api/ecw/box";

// 缓存默认的表单数据
let makeDefaultFormData = () => {
  return {
    destCountryId: null,
    lineId: null,
    objectiveId: null,
    departureId: null,
    status: 0,
    sendstatus: 0,
    isCargoControl: false,
    isCollection: false,
    type: [],
    isExternalWarehouse: false,
    externalWarehouseDtoList: [],
    orderItemVOList: [],
    drawee: 2,
    harvestMethod: 1,
    displayBillLadingPrice: true
  }
}
window.Decimal = Decimal

export default {
  name: "EcwOrderEdit",
  components: {
    Template,
    ProductSelector,
    Selector,
    CustomerContactSelector,
    AreaSelector,
    FileUpload,
    AreaCodeSelector,
    ChooseContactDialog,
    QuickCreateCustomer,
    SupplierSelector,
    WorkFlow
  },
  data() {
    let validatorPositiveNumber = (rule, value, callback) => {
      if (!value || value == '') return callback();
      if (!value) return callback(new Error('请输入数字'))
      if (!Number(value)) return callback(new Error('请输入有效数字'))
      let reg = /((^[1-9]\d*)|^0)(\.\d*){0,1}$/;
      if (!reg.test(value)) return callback(new Error('请输入有效数字'));
      callback();
    }
    return {
      DICT_TYPE,
      validatorPositiveNumber,
      customDraweeList: [],
      // draweeList: [],
      // 遮罩层
      loading: true,
      //productList:[], // 商品信息
      productAttrList: [],  // 商品属性
      channelList: [], // 出货取到
      routerList: [],
      tradeCityList: [],
      treeList: [],
      consignorContact: {}, // 发货联系人
      consigneeContact: {}, // 收货联系人
      /* consignee: null,
      consignor: null,  */
      transportList: [],
      currencyList: [],
      unitList: [],
      couponList: [],
      couponTypeList: [],
      fee: {}, // 费用
      // 表单参数
      form: makeDefaultFormData(),
      ccIdArr: [],
      // 表单校验
      labelStyle: 'width:120px',
      showBatchImportDialog: false, // 显示批量导入弹窗
      importList: [],
      exportLoading: false, // 装下单模板下载状态
      contactChooseType: null, // 联系人选择对象consignor(发货人) 或者 consignee（收货人）
      quickCreateType: null, // 快速新建客户类型，1发货人，2收货人
      showWorkFlow: false, // 是否显示工作流表单
      calculating: false, // 是否正在计算费用，防止频繁重新请求
      initing: true, // 初始化中,
      updateChannel: false, // 是否更新渠道
      updateWorth: false, // 是否更新货值
      offerData: [],// 关联报价单
      offerIdNochange: false,
      offerNumber: null,
      showAdress: false,
      // harvestMethod2: null,
      /* lunchList: [
        { label: "自提", value: 1 },
        { label: "送货上门", value: 2 },
      ], */
      // 发货人客户最新信息
      consignorCustomer: null,
      // 发货人是否允许控货无收货人
      noConsignee: false,
      // 是否有收货人
      hasConsignee: true,
      // 是否展示全部发货人信息
      showFullConsignor: false,
      // 是否展示全部收货人信息
      showFullConsignee: false,
      destCountryList: [],
      destCityList: [],
      selectedRouter: null,
      // 发货人默认付款
      defaultPay: false,
      showDestCityList: []
    };
  },
  computed: {
    rules() {
      const rules = {
        marks: [
          {required: true, message: this.$t('请填写唛头')},
          {
            validator: (rule, value, callback) => {
              // 必须是字母和数字
              let reg = /^[a-zA-Z0-9 ]*$/;

              if (!reg.test(value)) {
                return callback(new Error(this.$t('唛头只能是字母和数字')));
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        consignorContactsId: [{required: true, message: this.$t('发货人不能为空')}],
        transportId: [{required: true, message: this.$t('请选择运输方式')}],
        departureId: [{required: true, message: this.$t('请选择始发城市')}],
        destCountryId: [{required: true, message: this.$t('请选择目的国家')}],
        lineId: [{required: true, message: this.$t('请选择路线')}],
        channelId: [{required: true, message: this.$t('请选择出货渠道')}],
        deliveryDate: [{required: true, message: this.$t('请选择预计送货日期')}],
        consigneeAddress: [{required: true, message: this.$t('请填写详细地址')}],
        country: [{required: true, message: this.$t('收货地区填写不完整')}],
        isCargoControl: [{required: true, message: this.$t('请选择是否控货')}],
        isCollection: [{required: true, message: this.$t('请选择代收货款')}],
        collectionProxy: [{required: true, message: this.$t('代收货款不能为空')}],
        customsType: [{required: true, message: this.$t('请选择单证报关')}],
        warehouseType: [{required: true, message: this.$t('请选择入仓类型')}],
        harvestMethod: [{required: true, message: this.$t('请选择收货方式')}]
      }
      // 有收货人则添加收货人校验
      if (this.hasConsignee) {
        rules.consigneeContactsId = [{required: true, message: this.$t('收货人不能为空')}]
      }
      return rules
    },
    // 是否已完成入仓
    inWarehouse() {
      return (!!this.form.inWarehouseState && this.form.inWarehouseState > 201) || this.form.shipmentState > 0
    },
    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() {
      let ids = []
      this.exportCityList.forEach(item => {
        ids.push(item.id)
      })
      return ids
    },
    importCountryIds() {
      let ids = []
      this.destCountryList.forEach(item => {
        ids.push(item.guojia)
      })
      return ids
    },
    importCityIds() {
      let ids = []
      this.destCityList.forEach(item => {
        ids.push(item.shi)
      })
      return ids
    },
    getDictData() {
      return (type, value) => getDictData(type, value) || {}
    },
    getDictDatas() {
      return getDictDatas
    },
    /* selectedRouter(){
        // otherService 1 集运服务  2 送货上门  3 非控货订单代收货款  4 海外仓  5 提货异常
        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)
    },
    // 根据id获取优惠券
    getCoupon() {
      return couponId => {
        if (!couponId) return null
        return this.couponList.find(item => item.couponId == couponId)
      }
    },
    currentcyMap() {
      let map = {}
      this.currencyList.forEach(item => {
        map[item.id] = item.titleZh
      })
      return map
    },
    unitMap() {
      let map = {}
      this.unitList.forEach(item => {
        map[item.id] = item.titleZh
      })
      return map
    },
    sum() {
      let sum = {
        totalNum: new Decimal(0),
        totalVolume: new Decimal(0),
        totalWeight: new Decimal(0),
        totalWorth: new Decimal(0),
        totalQuatity: new Decimal(0)
      }
      if (!this.form || !this.form.orderItemVOList) return sum
      this.form.orderItemVOList.forEach(item => {
        sum.totalNum = sum.totalNum.plus(item.num || 0)
        sum.totalVolume = sum.totalVolume.plus(item.volume || 0)
        sum.totalWeight = sum.totalWeight.plus(item.weight || 0)
        sum.totalWorth = sum.totalWorth.plus(item.worth || 0)
        sum.totalQuatity = sum.totalQuatity.plus(item.quantity || 0)
      })
      return sum
    },
    // 总优惠金额
    discount() {
      return 0
    },
    // 是否编辑
    editMode() {
      return this.$route.path.indexOf('create') == -1
    },
    // 是否可以编辑商品基本信息（货值除外）
    productEditable() {
      // 非编辑模式 或者 未完成入仓
      return !this.editMode || !this.inWarehouse
    },
    // 路线开通的服务
    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
    },
    // 显示的目的国
    showDestCountryList() {
      return this.destCountryList
    },
    // 是否已起运（已起运不让修改报关方式）
    isShipment() {
      return [326, 328, 329, 330, 332, 391, 392, 426, 428, 432].indexOf(this.form.shipmentState) > -1
    }
  },
  watch: {
    // 如果无收货人则必须控货
    hasConsignee(val) {
      if (!val) {
        this.$set(this.form, 'isCargoControl', true)
        // 无收货人且控货则默认发货人付款
        // this.$set(this.form, 'drawee', 1)
        // 清除收货人必填校验
        this.$refs.form?.clearValidate("consigneeContactsId")
        if (!this.initing){
          this.setDefaultDrawee()
        }
      }
    },
    ccIdArr(arr) {
      this.$set(this.form, 'ccIds', arr.join(","))
    },
    // 始发地
    'form.departureId'(departureId, oldDepartureId) {
      console.log('departureId', departureId)
      // this.getOpenedRouterList()
    },
    // 目的地
    async 'form.objectiveId'(objectiveId, oldObjectiveId) {
      // 重新获取路线
      // await this.getOpenedRouterList()
      // 重新获取渠道
      await this.getChannelList()
    },
    'form.transportId'(transportId, oldTransportId) {
      // 空运
      if (!this.initing && (this.form.transportId == 4 || this.form.transportId == 3)) {
        this.$nextTick(() => {
          console.log('切换空运，修改默认值')
          this.$set(this, 'form', Object.assign(this.form, {
            doubleClear: 2,
            customsClearCert: false,
            isUnpack: false,
            isSingleTicketTransport: false
          }))
        })
      }
      // 更换运输方式之后，之前选择的路线会失效，需要重新选择
      /* if(oldTransportId && oldTransportId != transportId && transportId != this.selectedRouter?.transportType && !this.initing){
          console.log('重置路线',oldTransportId, transportId, this.selectedRouter?.transportType)
          this.$set(this.form, 'lineId', undefined)
      } */

      // 选择海运拼柜和海运整柜清空渠道值
      if (transportId == 1 || transportId == 2) {
        this.$set(this.form, 'channelId', null)
      }

      console.log('form.transportId', this.form.transportId, this.initing)
      if (!this.initing && transportId == 3) {
        // 如果是专线空运默认目的港清关选择我司
        this.$set(this.form, 'portDestCustomsClear', 1)
      }

      // this.getOpenedRouterList()
    },
    'form.channelId'() {
      this.calculationPrice()
      if (this.form.lineId) this.getOfferData()
      // 选择渠道后需要筛选目的城市和线路
      // 有点卡，改异步
      this.$nextTick(async () => {
        // 更新目的城市备选
        await this.getTradeCity()
        // 如果已选择城市，在切换后不可用则重置
        if (this.form.objectiveId && !this.importCityList.find(item => item.id == this.form.objectiveId)) {
          this.$set(this.form, 'objectiveId', null)
        }
        // 更新线路备选
        //await this.getOpenedRouterList()
        /* // 如果已选择路线且切换后原路线不可用则重置
        if(this.form.lineId && !this.routerList.find(item => item.id == this.form.lineId)){
            this.$set(this.form, 'lineId', null)
        } */
      })
    },
    'form.consigneeCountryCode'() {
      if (this.form.lineId) this.getOfferData()
    },
    'form.consignorCountryCode'() {
      if (this.form.lineId) this.getOfferData()
    },
    'form.consigneePhone'() {
      if (this.form.lineId) this.getOfferData()
    },
    'form.consignorPhone'() {
      if (this.form.lineId) this.getOfferData()
    },
    async 'form.lineId'(lineId) {
      console.log("路线修改", lineId)
      let 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.$set(this.form, 'transportId', router.transportType) */
      await this.getChannelList()
      this.calculationPrice()
      this.$nextTick(() => {
        // 如果开启了默认送货上门，则默认选择送货上门，2是送货上门，10是默认送货上门
        this.$set(this.form, 'harvestMethod', this.routeOtherServices.indexOf('2') > -1 && this.routeOtherServices.indexOf('10') > -1 ? 2 : 1)

        // controlStatus 0 支持控货，1不支持控货
        // 如果不支持控货，则控货不能选择是
        if (router.controlStatus === 1) {
          this.$set(this.form, 'isCargoControl', false)
        }
      })
      this.getOfferData()
    },
    /* 'form.packageTypeArr'(val){
        console.log('packageType', val, val.length)
        this.$set(this.form, 'packageType', val ? val.join(',') : '')
    }, */
    'form.isExternalWarehouse'(isExternalWarehouse) {
      // 勾选外部仓则添加一个默认的，取消则删除默认的空的
      if (!isExternalWarehouse) {
        this.$set(this.form, 'externalWarehouseDtoList', [])
      } else if (!this.form.externalWarehouseDtoList || !this.form.externalWarehouseDtoList.length) {
        this.$set(this.form, 'externalWarehouseDtoList', [{}])
      }
    },
    // 选择送货上门需要查询并填充默认地址
    'form.harvestMethod'(harvestMethod) {
      if (harvestMethod == 2 && !this.form.address && this.form.consigneeId) {
        getCustomer(this.form.consigneeId).then(res => {
          if (res.data.address) {
            this.$set(this.form, 'consigneeAddress', res.data.address)
          }
        })
      }
    },
    'form.isCargoControl'(isCargoControl) {
      console.log('form.isCargoControl', this.form.isCargoControl, this.initing)
      if (!this.initing) {
        // this.$set(this.form, 'drawee', isCargoControl && !this.hasConsignee ? 2 : 2)
        this.setDefaultDrawee()
      }

      this.setBllLandingPrice('form.isCargoControl')
    },
    'form.type'(newVal, oldVal) {
      // 在选择预计送货日期后这里会触发，暂不清楚原因，所以加一个判断
      /* if(newVal?.join(",") == oldVal?.join(",")){
        return
      } */
      this.setBllLandingPrice('form.type')
    },
    'form.drawee'(old, newVal) {
      this.setBllLandingPrice('form.drawee')
    },
    'form.consigneeId'() {
      this.setBllLandingPrice('form.consigneeId')
    },
    'form.consignorId'() {
      this.setBllLandingPrice('form.consignorId')
    },
    // 目的港清关,1我司，2客户
    'form.portDestCustomsClear'(portDestCustomsClear) {
      // 我司默认多票
      if (portDestCustomsClear == 1) {
        this.$set(this.form, 'deliveryWay', 1)
      }
      // 客户默认单票
      if (portDestCustomsClear == 2) {
        this.$set(this.form, 'deliveryWay', 2)
      }
    },
    /* 'form.orderItemVOList'(){
        console.log('form.orderItemVOList', this.form.orderItemVOList.length, this.form.orderItemVOList)
    }, */
    // 选择的路线变化后，需要判断是否开通了对应的服务，如果没开通需要取消对应的服务选择
    selectedRouter(val) {
      if (!val) {
        return
      }
      ['1', '4'].forEach(service => {
        if (this.routeOtherServices.indexOf(service) < 0 && this.form.type.indexOf(service == 4 ? 2 : service) > -1) {
          console.log("当前集运服务选择", this.form.type)
          this.form.type.splice(this.form.type.findIndex(item => item == (service == 4 ? 2 : service)), 1)
        }
      })

    },
    // 送货上门变化后需要判断当前选择的收货方式，如果选择了送货上门但是当前不支持送货上门则需要重置
    homeDeliveryService(enable) {
      if (!enable && this.form.harvestMethod != 1) {
        this.form.harvestMethod = 1
      }
    },
    // 变更渠道需要显示工作流组件
    updateChannel(updateChannel) {
      if(updateChannel) {
        this.$set(this, 'showWorkFlow', true)
      }
    },
    /*'$route.query.transportType'(transportType){
      this.$set(this.form, 'transportId', transportType ? +transportType : undefined)
    }*/
  },
  activated() {
    console.log("%c activated", "color: red")
    if (this.$route.query.id != this.form.id) {
      console.log("activated 加载订单数据")
      this.getOrder()
    }
    let transportType = undefined
    if (this.$route.query.transportType) {
      transportType = +this.$route.query.transportType
    }
    if (transportType != this.transportId) {
      this.$set(this.form, 'transportId', transportType)
    }

    // 变更出货渠道
    this.updateChannel = this.$route.query.updateChannel == 1
    // 修改货值功能
    this.updateWorth = this.$route.query.updateWorth == 1
  },
  async created() {
    console.log("%c created", "color: red")
    // 初始化自定义付款人需要在前面，否则先执行activated里的getOrder，会被覆盖
    this.getDictDatas(this.DICT_TYPE.ECW_CUSTOM_DRAWEE).forEach(item => {
      this.customDraweeList.push({
        label: item.label, // 显示文字
        name: item.value, // key值
        value: 2 // 1 发货人，2收货人，默认收货人，可修改
      })
    })
    await getGuojiaAndShiAndWarehouseList({tradeType: 1}).then(({data}) => {
      this.destCountryList = data.guojiaList
      this.destCityList = data.shiList
      this.showDestCityList = data.shiList
    })
    this.productAttrList = (await getProductAttrList()).data
    await this.getChannelList()

    this.currencyList = (await getCurrencyList()).data
    this.unitList = (await getUnitList()).data
    this.transportList = this.getDictDatas(this.DICT_TYPE.ECW_TRANSPORT_TYPE)

    if (this.$route.query.transportType) {
      this.$set(this.form, 'transportId', +this.$route.query.transportType)
    }
    // 变更出货渠道
    if (this.$route.query.updateChannel) {
      this.updateChannel = true
    }
    // 修改货值
    if (this.$route.query.updateWorth) {
      this.updateWorth = true
    }
    if (this.$route.query.id) {
      console.log('created 加载订单数据')
      this.getOrder()
    } else {
      await this.getTradeCity()
      this.addProduct()
      this.$nextTick(() => {
        this.initing = false
      })
    }
  },
  methods: {
    async getTradeCity(a) {
      let query = {}
      if (this.form.channelId) {
        query.channelId = this.form.channelId
      }
      this.tradeCityList = (await getTradeCityList(query)).data
    },
    async getChannelList() {
      let query = {
        cityId: this.form.objectiveId,
        lineId: this.form.lineId
      }
      this.channelList = (await getChannelList(query)).data
    },
    onTableMounted(e) {
      // console.warn('onTableMounted', e)
    },
    getCustomer(id) {
      getCustomer(id).then((response) => {
        console.log(response.data, "response")
        this.consignorCustomer = {
          ...this.consignorCustomer,
          ...response.data
        }
        if (this.consignorCustomer) {
          // 最新的客户设置信息，是否允许控货无收货人
          this.noConsignee = this.consignorCustomer.noConsignee
        } else {
          // 默认不允许控货无收货人
          this.noConsignee = false
        }
        // 最新的发货人档案不允许无收货人则重置状态
        if (!this.noConsignee) {
          // 最新的发货人不允许无收货人，则重置为有收货人
          this.hasConsignee = true
        }
      })
    },
    async getOrder() {
      console.log('是否加载编辑订单数据')
      // if (this.form.orderId == this.$route.query.id) {
      //   console.log('加载中或者已加载此订单数据，不重复加载', this.initing, this.form.orderId, this.$route.query.id)
      //   return
      // }
      await this.$nextTick()
      this.initing = true
      getUpdateInfo(this.$route.query.id).then(async (res) => {
        this.form = Object.assign({}, {...res.data}, {orderItemVOList: []})
        this.getOfferData()
        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

        }
        // 可能是来自于activated切换其他订单获取数据，需要重新获取城市确保路线的时候能有效过滤
        await this.getTradeCity()
        await this.getOpenedRouterList()
        this.selectedRouter = this.routerList.find(item => item.id === this.form.lineId)
        if (this.selectedRouter) {
          this.form.destCountryId = this.selectedRouter.destCountryId
        } else console.log("未找到选择的路线", this.routerList, this.selectedRouter)
        console.log("国家ID", this.form.destCountryId)


        /* console.log({...this.form}, {
          customsClearCert: this.form.customsClearCert,
          isUnpack: this.form.isUnpack,
          isSingleTicketTransport: this.form.isSingleTicketTransport,
        }) */
        console.log("集运服务类型", this.form.type)
        this.form.type = this.form.type ? this.form.type.split(',').filter(item => item != '') : []
        this.form.packageTypeArr = this.form.packageType ? this.form.packageType.split(',').filter(item => item != '') : []
        // 是否有收货人
        this.hasConsignee = !!res.data.consigneeVO
        // 每次编辑订单详情需要实时获取发货人当前信息
        if (res.data.consignorVO) {
          if (this.$route.query.copy && this.$route.query.copy == 1) {
            res.data.consignorVO.id = null
            res.data.consignorVO.orderId = null
          }
          this.$set(this.form, 'consignorCompany', res.data.consignorVO.company)
          this.$set(this.form, 'consignorCompanyEn', res.data.consignorVO.companyEn)
          this.$set(this.form, 'consignorContactsId', res.data.consignorVO.customerContactsId)
          this.$set(this.form, 'consignorCountryCode', res.data.consignorVO.countryCode.replace('+', ''))
          this.$set(this.form, 'consignorEmail', res.data.consignorVO.email)
          this.$set(this.form, 'consignorId', res.data.consignorVO.customerId)
          this.$set(this.form, 'consignorName', res.data.consignorVO.name)
          this.$set(this.form, 'consignorNameEn', res.data.consignorVO.nameEn)
          this.$set(this.form, 'consignorPhone', res.data.consignorVO.phone)
          this.getCustomer(res.data.consignorVO.customerId)
        }

        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, 'consigneeCompany', res.data.consigneeVO.company)
          this.$set(this.form, 'consigneeCompanyEn', res.data.consigneeVO.companyEn)
          this.$set(this.form, 'consigneeContactsId', res.data.consigneeVO.customerContactsId)
          this.$set(this.form, 'consigneeCountryCode', res.data.consigneeVO.countryCode.replace('+', ''))
          this.$set(this.form, 'consigneeEmail', res.data.consigneeVO.email)
          this.$set(this.form, 'consigneeId', res.data.consigneeVO.customerId)
          this.$set(this.form, 'consigneeName', res.data.consigneeVO.name)
          this.$set(this.form, 'consigneeNameEn', res.data.consigneeVO.nameEn)
          this.$set(this.form, 'consigneePhone', res.data.consigneeVO.phone)
        }
        // res.data.hasConsignee 订单冗余的发货人是否允许无收货人
        // res.data.noConsignee 当前订单发货人是否允许无收货

        if (this.form.channelId == 0) {
          delete this.form.channelId
        }

        if (res.data.ccIds) {
          this.ccIdArr = res.data.ccIds.split(",").filter(item => item && item != '')
        }

        // 审核中需要显示流程表单
        if (this.form.applyStaus == 1) {
          this.showWorkFlow = true
        }
        if (this.$route.query.copy && this.$route.query.copy == 1) {
          // 复制订单逻辑不管审批业务
          this.showWorkFlow = false
        }

        // 如果是自定义付款人，则需要同步具体发货人信息
        if (this.form.drawee == 3) {
          console.log('同步自定义付款人信息', JSON.stringify(this.customDraweeList))
          this.customDraweeList.forEach(item => {
            console.log(item.name, this.form.customDraweeVOList.find(it => it.name == item.name)?.value, item.value)
            item.value = this.form.customDraweeVOList.find(it => it.name == item.name)?.value || item.value
          })
          console.log('同步自定义付款人信息', this.customDraweeList, this.form.customDraweeVOList)
        }

        // 如果已完成入仓，则需要监听必填内容，发生更改后需要填写审批表单
        this.$nextTick(() => {
          console.log('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})
          })

          // 已入仓后，必填字段修改则需要显示审批流
          if (this.updateWorth == 1){
            this.showWorkFlow = false
          } else if (this.inWarehouse) {
            Object.keys(this.rules).forEach(field => {
              console.log("watch", field)
              this.$watch(`form.${field}`, () => {
                this.showWorkFlow = true
              })
            })
          }



          // 在初始化结束后transportId还会发生一次变化导致目的港清关被重置，所以需要延迟一下。暂不清楚原因
          setTimeout(() => {
            console.log('transportId', this.form.transportId)
            console.log('portDestCustomsClear', this.form.portDestCustomsClear, res.data.portDestCustomsClear)
            if (res.data.portDestCustomsClear) {
              this.$set(this.form, 'portDestCustomsClear', res.data.portDestCustomsClear)
            }
            if (res.data.deliveryWay) {
              this.$set(this.form, 'deliveryWay', res.data.deliveryWay)
            }
            this.$nextTick(() => {
              this.initing = false
              console.log("初始化完成 initing", this.initing)
            })

          }, 100)

        })

        //alert(this.form.harvestMethod);
        if (this.form.harvestMethod == 2) {
          this.showAdress = true;
          this.harvestMethod2 = this.form.harvestMethod;
        } else {
          this.showAdress = false;
          this.harvestMethod2 = this.form.harvestMethod;
        }

        console.log('order数据加载成功')
      }).catch(() => {
        this.initing = false
      })
    },
    onContactChoose(contact) {
      console.log('选择联系人', contact)
      if (!this.contactChooseType && !this.quickCreateType) return
      if (!this.contactChooseType && this.quickCreateType) {
        this.contactChooseType = this.quickCreateType == 0 ? 'consignor' : 'consignee'
      }
      this.$set(this.form, this.contactChooseType + 'Company', contact.company)
      this.$set(this.form, this.contactChooseType + 'CompanyEn', contact.companyEn || '')
      this.$set(this.form, this.contactChooseType + 'ContactsId', contact.customerContactsId)
      this.$set(this.form, this.contactChooseType + 'CountryCode', contact.areaCode.replace('+', ''))
      this.$set(this.form, this.contactChooseType + 'Email', contact.email)
      this.$set(this.form, this.contactChooseType + 'Id', contact.customerId)
      this.$set(this.form, this.contactChooseType + 'Name', contact.contactsName)
      this.$set(this.form, this.contactChooseType + 'NameEn', contact.contactsNameEn || '')
      this.$set(this.form, this.contactChooseType + 'Phone', contact.phoneNew)
      this.$set(this.form, this.contactChooseType + 'DefaultPay', contact.defaultPay)

      if (this.contactChooseType == 'consignor') {
        this.noConsignee = contact.noConsignee
      }
      if (!this.initing) {
        this.setDefaultDrawee()
      }
      this.contactChooseType = null
      this.quickCreateType = null
      if (this.form.lineId) this.getOfferData()
    },
    upload(e) {
      console.log({upload: e})
      let form = new FormData()
      form.append('file', e.file)
      orderImport(form).then(res => {
        if (!res.data.list.length) {
          return this.$message.error('无有效数据')
        }

        this.importList = res.data.list
        this.$set(this.form, 'packingListUrl', res.data.packingListUrl)

      })
    },
    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('装箱单模板') + '.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    setLink(row) {
      this.$prompt(this.$t('请输入商品链接'), {inputValue: row.link}).then(({value}) => {
        this.$set(row, 'link', value)
      })
    },
    // 检查正整数
    checkPositiveInterge(row, field) {
      console.log('checkPositiveInterge', field, row[field])
      row[field] = row[field].toString().replace(/[^\d]/g, '')
    },
    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()
    },
    onAreaChange(type, val) {
      this.$set(this.form, type, val)
    },
    // 生成快递单号
    getOrderCourierNumber() {
      getOrderCourierNumber().then(res => {
        this.$set(this.form, 'number', res.data)
      })
    },
    onProductAttrChange(row, attr) {
      console.log(attr)
    },

    addProduct(data) {
      this.form.orderItemVOList.push(data || {
        prodAttrArr: [],
        prodId: null,
        worth: undefined,
        volume: '',
        weight: '',
        num: undefined
      })
    },
    // 更新路线并打印来源
    updateRoutes(fr) {
      console.log("%cupdateRotutes", "color: blue", fr)
      return this.getOpenedRouterList()
    },
    // 获取路线
    async getOpenedRouterList() {
      let params = {}
      if (this.form.departureId) {
        params.startCityId = this.form.departureId
      }
      if (this.form.destCountryId) {
        params.destCountryId = this.form.destCountryId
      }
      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
      }
      console.log("获取路线,参数", params)
      // 始发，目的和运输方式都没有的时候不获取
      if (!params.startCityId && !params.destCountryId && !params.destCityId && !params.transportType) return false
      return getOpenedRouterList(params).then(res => {
        this.routerList = res.data.filter(item => {
          return this.exportCityIds.indexOf(item.startCityId) > -1 && this.importCountryIds.indexOf(item.destCountryId) > -1 && (this.importCityIds && this.importCityIds.indexOf(item.destCityId) > -1)
        })
        console.log(`已获取到路线${res.data?.length}条，有效路线${this.routerList.length}条,参数:${JSON.stringify(params)}`)
        console.table([
          {
            all: res.data.map(item => item.id).join(","),
            avail: this.routerList.map(item => item.id).join(",")
          }
        ])
        // 如果已选择的线路ID不在上述路线列表里则重置
        if (this.form.lineId) {
          this.selectedRouter = this.routerList.find(item => item.id == this.form.lineId)
          if (!this.selectedRouter) {
            console.log(`获取到的路线未找到原路线lineId: ${this.form.lineId}，重置为null`)
            this.$set(this.form, 'lineId', null)
          }
        }
      })
    },
    // 计算体积
    calcVolume(row) {
      if (!row.boxGauge || !row.num) return false
      try {
        row.volume = (eval(row.boxGauge) * row.num).toFixed(2)
      } catch (e) {
        row.volume = ''
      }
    },
    // 删除一条产品
    delProduct(index) {
      this.$confirm(this.$t('确定删除此条内容么？'))
        .then(res => {
          this.form.orderItemVOList.splice(index, 1)
        })
    },
    handleChange(harvestMethod) {
      if (harvestMethod == 1) {
        this.showAdress = false;
      } else {
        if (this.homeDeliveryService == false) {
          this.form.harvestMethod = 1;
          this.$message.error("此路线未开通上门服务。");
          return;
        }
        this.showAdress = true;
      }
      if (harvestMethod == 2 && !this.form.address && this.form.consigneeId) {
        getCustomer(this.form.consigneeId).then((res) => {
          if (res.data.address) {
            this.$set(this.form, "consigneeAddress", res.data.address);
          }
        });
      }
    },
    checkBillOfLading() {
      return checkBillOfLadingService(this.form.orderId).then((res) => {
        console.log("检查提单制作状态", res.data)
        return res.data
      })
    },
    /** 提交按钮 */
    // type 在新建的时候表示状态，0草稿，2带入仓
    submitForm(submitType) {
      if (this.form.harvestMethod == 2 && this.homeDeliveryService == false) {
        return this.$message.error("此路线未开通上门服务。");
      }

      this.$refs["form"].validate(async (valid, errors) => {
        if (!valid) {
          return this.$showFormValidateErrors(errors)
        }

        if (this.form.harvestMethod == 2) {
          if (!this.form.country || !this.form.province || !this.form.city) {
            return this.$notify({
              title: this.$t('提示'),
              message: this.$t("收货地区填写不完整"),
              type: 'warning'
            });
          }
        }
        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.$notify({
            title: this.$t('提示'),
            message: this.$t("订单包含不接受货物，请检查"),
            type: 'warning'
          });
        }
        this.transportList.map(item => {
          if (item._enabled) {
            item.lineIds = Array.from(item.lineIdSet).join(',')
            item.channelIds = Array.from(item.channelIdSet).join(',')
          }
        })
        this.form.packageType = this.form.packageTypeArr.join(',')

        for (const i in this.form.orderItemVOList) {
          const item = this.form.orderItemVOList[i]
          if (!item.prodId) {
            return this.$message.error(this.$t(`第${Number(i) + 1}行未选择商品`, i + 1))
          }
        }

        // 付款人=发货人提示
        if (+this.form.drawee === 1 && !(this.updateChannel || this.updateWorth)) {
          await this.$confirm(this.$t('请再次确认运费由您支付还是收货人支付?'))
        }
        // 24-02-08 新需求 当付款人=发货人且提单显示价格，需要弹出提示，付款人=发货人，请再次确认提单是否显示价格明细，是则允许提交订单，否则留在当前页面
        // https://zentao.test.jdshangmen.com/task-view-3442.html
        if (+this.form.drawee === 1 && this.form.displayBillLadingPrice && !(this.updateChannel || this.updateWorth)) {
          await this.$confirm(this.$t('付款人=发货人，请再次确认提单是否显示价格明细'))
        }

        // 校验手机号跟目的国是否匹配
        if (this.updateWorth){
          // 如果是修改货值跳过检验
        }else if (this.hasConsignee && this.form.consigneeCountryCode && this.form.consigneePhone) {
          // if (this.form.consigneeCountryCode == "86" || this.form.consigneeCountryCode == "+86") {
          //   this.$message.error(this.$t("控货订单的收货人手机号不能是国内号码"))
          //   return
          // }
          const res = await checkCountryCode({
            areaCode: this.form.consigneeCountryCode,
            currencyId: this.form.destCountryId
          })
          // 并不一致则提示
          if (!res.data) {
            await this.$confirm(this.$t('电话所在国与目的国不一致，请检查'))
          }
        }

        // 修改的提交
        if (this.form.orderId) {
          if (await this.checkBillOfLading()) {
            await this.$confirm(this.$t('提单已制作，如需修改请联系客服'))
          }
          let data = Object.assign({}, this.form, {
            status: submitType,
            customDraweeVOList: this.customDraweeList,
            // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
            orderItemVOList: this.getProductListWithDefaultValue(),
            hasConsignee: this.hasConsignee
          })
          data.type = data.type.join(',')
          const func = this.form.shipmentState > 0 ? updateShipmentApply : updateApply
          func(data).then(response => {
            this.$modal.msgSuccess(this.$t("修改成功"));
            // 如果url中copy=1则表示复制后编辑订单，需要跳转到成功页面
            if (this.$route.query.copy == 1) {
              this.$redirect('success?orderId=' + this.form.orderId)
              return
            }
            this.$router.back()
          });
          return;
        }
        let data = Object.assign({
          consigneeId: this.consigneeContact.customerId,
          consignorId: this.consignorContact.customerId,
          customerId: this.consignorContact.customerId,
          // couponIds: coupons.join(","),
        }, this.form, {
          customDraweeVOList: this.customDraweeList,
          // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
          orderItemVOList: this.getProductListWithDefaultValue(),
          status: submitType,
          hasConsignee: this.hasConsignee
        })
        data.type = data.type.join(',')

        // 添加的提交
        createOrder(data).then(response => {
          this.$modal.msgSuccess(this.$t("新增成功"));
          this.initing = true
          // 重置数据
          this.form = {...makeDefaultFormData()}
          this.routerList = []
          this.addProduct()
          this.$nextTick(() => {
            this.initing = false
            this.$nextTick(() => {
              this.$redirect('success?orderId=' + response.data)
            })
          })
        });
      });
    },
    // 计算商品运费(根据货值计算保费)
    calculationPrice() {
      let calcable = true
      if (!this.form.orderItemVOList.length) return false
      this.form.orderItemVOList.forEach(item => {
        if (!item.prodId) {
          calcable = false
        }
      })
      console.log('calculationPrice', calcable)
      if (this.calculating || !calcable) return false
      this.calculating = true
      console.log('calculating ---> ')
      const data = {
        lineId: this.form.lineId,
        transportId: this.form.transportId,
        channelId: [3, 4].indexOf(this.form.transportId) > -1 ? this.form.channelId : undefined,
        prodConditionParamList: this.getProductListWithDefaultValue(),
        orderType: this.form.orderType
      }
      if (this.form.channelId) {
        data.channelId = this.form.channelId
      }
      calculationPrice(data).then(res => {
        this.$set(this, 'fee', res.data.costDto)
        this.form.orderItemVOList.map((item, index) => {
          this.$set(item, 'fee', res.data.prodCostDtoList[index] || null)
        })
      }).finally(() => {
        this.calculating = false
      })
    },
    // 体积。件数，数量，重量为选填，但是接口确实必填，所以生成一个副本并赋予默认值
    getProductListWithDefaultValue() {
      let arr = []
      this.form.orderItemVOList.forEach(item => {
        //  商品信息只要商品id、品牌收费模式、件数、数量、体积、重量、货值、包装类型即可
        let tmp = {...item}
        /* const tmp = {
          prodId: item.prodId,
          brandType: item.brandType,
          num: item.num,
          quantity: item.quantity,
          volume: item.volume,
          weight: item.weight,
          prodAttrIds: item.prodAttrArr.join(','),
          worth: item.worth,
          packageType: item.packageType,
          unit: item.unit
        } */
        if (!tmp.volume) tmp.volume = 0
        if (!tmp.weight) tmp.weight = 0
        if (!tmp.quantity) tmp.quantity = 0
        if (!tmp.num) tmp.num = 0
        tmp.orderType = item.orderItemType
        delete tmp.fee
        delete tmp.couponInfo
        delete tmp.couponInfoVOList
        arr.push(tmp)
      })
      return arr
    },
    // 关联报价单
    getOfferData() {
      //查询订单关联报价单下拉列表 lanbm 2024-05-29 添加注释
      const that = this
      const offParams = {}
      if (that.form.lineId) {
        offParams.lineId = that.form.lineId
      }
      if (that.form.channelId) {
        offParams.channelId = that.form.channelId
      }
      if (that.form.consigneeContactsId) {
        offParams.consigneeId = that.form.consigneeContactsId
      } else {
        offParams.consigneeCode = that.form.consigneeCountryCode
        offParams.consigneePhone = that.form.consigneePhone
      }
      if (that.form.consignorContactsId) {
        offParams.consignorId = that.form.consignorContactsId
      } else {
        offParams.consignorCode = that.form.consignorCountryCode
        offParams.consignorPhone = that.form.consignorPhone
      }
      getOfferSelect(offParams).then((res) => {
        that.offerData = res.data || []
        if (!that.form.offerId && that.form.orderId) {
          that.getOfferNumber(that.form.orderId)
        }
      })
    },
    getOfferNumber(id) {
      const that = this
      that.offerIdNochange = false
      getOfferCheck({orderId: id}).then(response => {
        if (!response.data) return
        if (that.offerData.length == 0) {
          that.offerData.push(response.data)
        }
        that.offerIdNochange = true
        that.offerNumber = response.data.number
        that.$set(that.form, 'offerId', response.data.offerId)
      })
    },
    // 设置默认的提货单是否显示价格
    setBllLandingPrice(src) {
      console.log("更新默认的提单是否显示价格:src" + src, this.initing, {...this.form});
      if (this.form.orderId && this.initing) return

      // 240224 微信反馈
      // 不好意思，这写错了，付款人=发货人----提单价格默认否；付款人=收货人，提交价格默认是
      if (this.form.drawee == 1) {
        this.form.displayBillLadingPrice = false
        return
      }
      if (this.form.drawee == 2) {
        this.form.displayBillLadingPrice = true
        return
      }

      // 海外仓归属发货人
      // 控货订单归属发货人
      // 非控货订单 + 付款人为发货人 归属发货人， 其他归属收货人
      let customerId = null
      if (this.form.type == 2 || this.form.isCargoControl == 1 || this.form.drawee == 2) {
        customerId = this.form.consignorId
      } else {
        customerId = this.form.consigneeId
      }
      if (!customerId) return

      console.log('原归属人', this.displayBillLadingPriceFrom, '新归属人', customerId)

      // 如果当前的提单价格设置来自同一个客户则不在查询
      if (this.displayBillLadingPriceFrom == customerId) return;
      this.displayBillLadingPriceFrom = customerId

      // 获取客户信息
      getCustomer(customerId).then(res => {
        console.log('isShowTidanPrice', res)
        this.form.displayBillLadingPrice = res.data.isShowTidanPrice
      })
    },
    // 切换目的国
    handleChangeDestCountry(val) {
      console.log("handleChangeDestCountry", val)
      // 目的城市赋值
      this.form.destCountryId = val
      if (!val) {
        this.showDestCityList = JSON.parse(JSON.stringify(this.destCityList))
      } else {
        this.showDestCityList = JSON.parse(JSON.stringify(this.destCityList.filter(item => item.guojia === val)))
      }
      if (this.form.destCountryId) {
        this.form.objectiveId = null
        this.form.lineId = null
        this.selectedRouter = null
        this.updateRoutes('handleChangeDestCountry')
      }
    },
    // 切换目的城市
    async 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

      }
      await this.updateRoutes('handleChangeDestCity')
    },
    // 切换路线
    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
      }
    },
    // 去掉唛头首尾空格
    trimMarks() {
      this.form.marks = this.form.marks.trim()
    },
    // 更新默认付款人
    // 1发货人，2收货人，3自定义
    setDefaultDrawee() {
      // 优先级为：发货人默认付款，发货人付款>收货人默认付款，收货人付款>订单控货，收货人付款
      if (this.form.consignorDefaultPay) {
        this.form.drawee = 1
        return
      }
      if (this.form.consigneeDefaultPay) {
        this.form.drawee = 2
        return
      }
      if (this.form.isCargoControl) {
        this.form.drawee = 2
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.w-380 {
  width: 380px;
}

.justify-end {
  justify-content: flex-end;
}

.card-title {
  font-size: 18px;
  display: flex;

  .card-name {
    flex: 1;
  }
}

.form-section {
  .contact {
    display: flex;
    align-items: center;

    img.phonebook {
      width: 30px;
      height: 30px;
      margin-left: 10px;
      cursor: pointer;
    }
  }

}

::v-deep .product-list .el-form-item__error {
  position: static;
}

::v-deep th.el-table__cell .cell {
  white-space: nowrap;

  .red {
    color: red;
  }
}

::v-deep .right-label {
  .el-form-item__label {
    width: 150px;
    display: inline-flex;
    justify-content: flex-end;
    align-items: center;
  }
}
</style>
