<template>
  <div class="app-container">

    <el-form ref="form" :model="form" :rules="rules" label-width="120px" inline>
        <el-card>
            <div slot="header" class="card-title">{{$t('新建报价单')}}</div>
            <el-form-item :label="$t('所属人')">
                <el-radio-group v-model="form.relation">
                  <el-radio label="1">{{$t('发件人')}}</el-radio>
                  <el-radio label="2">{{$t('收件人')}}</el-radio>
                </el-radio-group>
            </el-form-item>
            <br/>
            <el-form-item :label="$t('订单类型')">
                <el-checkbox-group v-model="form.type">
                    <el-checkbox label="1">{{$t('集运服务')}}</el-checkbox>
                    <el-checkbox label="2">{{$t('海外仓')}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <div class="form-section">
                <el-form-item :label="$t('发货人')" prop="consignorId" >
                    <div class="contact">
                        <el-input v-model="form.consignorName" placeholder="选择或新建" disabled/>
                        <img src="@/assets/images/phonebook.png" class="phonebook" @click="contactChooseType='consignor'" />
                        <img src="@/assets/images/new_customer.png" class="phonebook" @click="quickCreateType='1'" />
                    </div>
                </el-form-item>
                <el-form-item :label="$t('发货人电话')" prop="consignorPhone">
                    <!-- <area-code-selector v-model="form.consignorCountryCode" class="w-200 mr-10" disabled /> -->
                    <el-input :value="`${form.consignorCountryCode || ''} ${form.consignorPhone || ''}`" class="w-200" disabled />
                </el-form-item>
                <el-form-item :label="$t('发货人公司')" prop="consignorCompany">
                    <el-input v-model="form.consignorCompany" disabled />
                </el-form-item>
                <el-form-item label="Email" prop="consignorEmail">
                    <el-input v-model="form.consignorEmail" disabled />
                </el-form-item>
            </div>
            <div class="form-section">
                <el-form-item :label="$t('收货人')" prop="consigneeId">
                    <div class="contact">
                        <el-input v-model="form.consigneeName" placeholder="请选择或新建" :disabled="true"/>
                        <img src="@/assets/images/phonebook.png" class="phonebook" @click="contactChooseType='consignee'" />
                        <img src="@/assets/images/new_customer.png" class="phonebook" @click="quickCreateType='2'" />
                    </div>
                </el-form-item>
                <el-form-item :label="$t('收货人电话')" prop="consigneePhone">
                    <!-- <area-code-selector v-model="form.consigneeCountryCode" class="w-200 mr-10" disabled/> -->
                    <el-input :value="`${form.consigneeCountryCode || ''} ${form.consigneePhone || ''}`" class="w-200" disabled/>
                </el-form-item>
                <el-form-item :label="$t('收货人公司')" prop="consigneeCompany">
                    <el-input v-model="form.consigneeCompany" :disabled="true" />
                </el-form-item>
                <el-form-item label="Email" prop="consigneeEmail">
                    <el-input v-model="form.consigneeEmail" :disabled="true"/>
                </el-form-item>
            </div>

            <!-- <el-descriptions :column="3" border>
                <el-descriptions-item :label="$t('*发货人')" :labelStyle="labelStyle" >
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consignorId" required :error="$t('发货人不能为空')">
                        <customer-contact-selector v-model="form.consignorId" @change="consignor = $event" type="1" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('手机号')" :labelStyle="labelStyle">
                    {{consignor.areaCode}} {{consignor.phoneNew || this.$t('无')}}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('发货人公司名称')" :labelStyle="labelStyle">
                    {{consignor.company || this.$t('无')}}
                </el-descriptions-item>
                <el-descriptions-item label="Email" :labelStyle="labelStyle">
                    {{consignor.email || this.$t('无')}}
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions :column="3" border>
                <el-descriptions-item :label="$t('收货人')" :labelStyle="labelStyle">
                    
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consigneeId" required :error="$t('收货人不能为空')">
                        <customer-contact-selector v-model="form.consigneeId" @change="consignee = $event" type="2" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('手机号')" :labelStyle="labelStyle">
                    {{consignee.areaCode}} {{consignee.phoneNew}}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('发货人公司名称')" :labelStyle="labelStyle">
                    {{consignee.company || this.$t('无')}}
                </el-descriptions-item>
                <el-descriptions-item label="Email" :labelStyle="labelStyle">
                    {{consignee.email || this.$t('无')}}
                </el-descriptions-item>
            </el-descriptions> -->
            
            <div class="form-section">
                <el-form-item :label="$t('运输方式')" prop="transportId">
                    <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="form.transportId" @input="calculationPrice" />
                </el-form-item>
                <el-form-item :label="$t('出货渠道')"  v-if="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass == 'channel'" prop="channelId">
                    <selector
                    :disabled="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass != 'channel'"
                    v-model="form.channelId"
                    :options="channelList"
                    value-field="channelId"
                    label-field="nameZh"
                    @input="calculationPrice"
                    ></selector>
                </el-form-item>
            </div>

            <div class="form-section">
                <el-form-item :label="$t('始发城市')" prop="departureId">
                    <el-select v-model="form.departureId" :placeholder="$t('请选择始发地')">
                        <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="objectiveId">
                    <el-select v-model="form.objectiveId" :placeholder="$t('请选择目的地')">
                        <el-option v-for="item in importCityList" :label="$l(item, 'title')" :value="item.id" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </div>
            <div class="form-section">
                <el-form-item :label="$t('选择线路')" prop="lineId">
                    <!-- <el-input :value="getRouterNameById(form.lineId)" readonly :placeholder="$t('请在右侧选择线路')"></el-input> -->
                    <el-input :value="selectedRouter ? $l(selectedRouter, 'startTitle') + ' > ' + $l(selectedRouter, 'destTitle') : ''" disabled :placeholder="$t('请在右侧选择线路')"></el-input>
                </el-form-item>
                <select size="5" v-model="form.lineId" style="min-width: 300px; border:1px solid #DCDFE6; border-radius:4px">
                    <template v-for="item in routerList">
                        <option :value="item.id" :key="item.id">{{$l(item, 'startTitle')}} >> {{$l(item, 'destTitle')}}</option>
                    </template>
                </select>
            </div>
        </el-card>
        <el-card  class="mt-10">
            <div slot="header" class="card-title">
                <div class="card-name">{{$t('商品信息')}}</div>
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="addProduct()" :disabled="!form.lineId"></el-button>
            </div>
            <el-table :data="productList" border>
              <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-scope="{row}">
                    <product-selector v-model="row.prodId" @change="onProductChange(row, $event)" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('英文品名')" width="160px">
                <template slot-scope="{row}">
                    <product-selector lang="En" v-model="row.prodId" @change="onProductChange(row, $event)" />
                </template>
              </el-table-column>
               <el-table-column :label="$t('品牌')" width="100px">
                <template slot-scope="{row}">
                    <dict-selector v-model="row.brand" :type="DICT_TYPE.ECW_IS_BRAND" defaultable @input="calculationPrice" />
                </template>
              </el-table-column>
             
              <el-table-column :label="$t('件数')" width="90px">
                <template slot-scope="{row}">
                    <el-input v-model.number="row.num" @input="calculationPrice" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('包装单位')">
                <template slot-scope="{row}">
                    <dict-selector v-model="row.unit" :type="DICT_TYPE.ECW_PACKAGE_TYPE" defaultable @input="calculationPrice" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('数量') + '(个)'">
                <template slot-scope="{row}">
                    <el-input v-model.number="row.quantity" @input="calculationPrice" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('总体积') + '(m³)'" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.volume" @input="calculationPrice"/>
                </template>
              </el-table-column>
              <el-table-column :label="$t('总重量') + '(kg)'" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.weight" @input="calculationPrice" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('总货值') + '(RMB)'" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.worth" />
                </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)">
                      <el-checkbox v-for="item in productAttrList" :label="item.id" :key="item.id">{{item.attrName}}</el-checkbox>
                    </el-checkbox-group>
                </template>
              </el-table-column>
              <el-table-column :label="$t('运费')" width="200px">
                <template slot-scope="{row}">
                    <template v-if="row.fee && row.fee.charging == 1">
                        <template v-if="!row.fee.freight">{{$t('未报价')}}</template>
                        <template v-else>
                            {{$t('全包价')}}：{{row.fee.freight}} {{currentcyMap[row.fee.freightCurrency]}} / {{unitMap[row.fee.freightVolume]}}
                        </template>
                    </template>
                    <template v-else-if="!row.fee || !row.fee.freight && !row.fee.clearanceFee">{{$t('未报价')}}</template>
                    <template v-else-if="row.fee">
                        <div>
                            {{$t('运费')}}：{{row.fee.freight}} {{currentcyMap[row.fee.freightCurrency]}} / {{unitMap[row.fee.freightVolume]}}
                        </div>
                        <div>
                            {{$t('清关费')}}：{{row.fee.clearanceFee}} {{currentcyMap[row.fee.clearanceFeeCurrency]}} / {{unitMap[row.fee.clearanceFeeVolume]}}
                        </div>
                    </template>
                </template>
              </el-table-column>
              <el-table-column :label="$t('是否预付')">
                <template slot-scope="{row}">
                    <dict-tag v-if="row.fee" :type="DICT_TYPE.ECW_PAY_ADVANCE" :value="row.fee.isPayAdvance"  />
                </template>
              </el-table-column>
              <el-table-column :label="$t('商品链接')" width="200px" align="center">
                <template slot-scope="{row}">
                    <el-link type="primary" :href="row.link" target="_blank" style="display:block">{{row.link}}</el-link>
                    <el-button type="primary" size="mini" @click="setLink(row)">
                        {{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="" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('操作')" width="180px" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="danger" @click="delProduct(scope.$index)">{{$t('删除')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 
        </el-card>
        <el-card  class="mt-10"> -->
            <div class="card-title" style="padding:20px 0;">{{$t('合计')}}</div>
            <el-descriptions :column="4" border>
                <el-descriptions-item :label="$t('总件数')">
                    {{sum.totalNum || 0}}
                </el-descriptions-item>
                <el-descriptions-item label="总体积">
                    {{sum.totalVolume || 0}}m³
                </el-descriptions-item>
                <el-descriptions-item label="总重量">
                    {{sum.totalWeight || 0}}kg
                </el-descriptions-item>
                <el-descriptions-item label="总数量">
                    {{sum.totalQuatity || 0}}
                </el-descriptions-item>
                
                <el-descriptions-item :label="$t('总货值') + '(RMB)'">
                    {{sum.totalWorth || 0}}{{$t('元')}}
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <el-card class="mt-10">
            <div class="card-title" slot="header">{{$t('预计费用')}}</div>
            
            <el-descriptions :column="5" border>
                <el-descriptions-item :label="$t('保价费')">
                    {{fee.insuranceFee || 0}} {{$t('美元')}}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('总运费')">
                    <template v-for="item in clearanceFeeList">
                        <div :key="item.currencyId">{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</div>
                    </template>
                </el-descriptions-item>
                <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
                <el-descriptions-item :label="$t('总清关费')">
                    <template v-for="item in freightFeeList">
                        <div :key="item.currencyId">{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</div>
                    </template>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('其他费用')">
                    <el-input v-model="form.otherFee" placeholder="" class="w-100 mr-10"></el-input>
                    <selector v-model="form.otherFeeCurrencyId" :options="currencyList" label-field="titleZh" value-field="id" defaultable class="w-100" />
                </el-descriptions-item>
                <el-descriptions-item :label="$t('原价')" :span="2">
                    <template v-for="item in originalFeeList">
                        <div :key="item.currencyId">{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</div>
                    </template>
                </el-descriptions-item>
            </el-descriptions>

            
            <div class="card-title" style="padding:20px 0;">{{$t('优惠信息')}}</div>
            <el-table :data="couponList" :show-header="false">
                <el-table-column label="">
                    <template slot-scope="scope">
                        {{scope.$index+1}}.
                        {{$l(productNames[scope.row.prodId], 'title') || $t('未知')}}
                    </template>
                </el-table-column>
                <el-table-column label="">
                    <template slot-scope="{row}">
                        <dict-tag :type="DICT_TYPE.ECW_COUPON_TYPE" :value="row.type" />
                    </template>
                </el-table-column>
                <el-table-column label="">
                    <template slot-scope="{row}">
                        {{$l(row, 'title')}}
                    </template>
                </el-table-column>
                <el-table-column label="">
                    <template slot-scope="{row}">
                        -{{row.reduceAmount}} 
                        {{currentcyMap[row.reduceCurrencyId]}}
                    </template>
                </el-table-column>
                <el-table-column label="">
                    <template slot-scope="{row}">
                        {{$t('有效期至')}}：{{row.endTime ? row.endTime : $t('永久有效')}}
                    </template>
                </el-table-column>
            </el-table>

            <el-descriptions :column="1" class="mt-20">
                <el-descriptions-item :label="$t('优惠费用')"  v-if="couponTotalAmountList && couponTotalAmountList.length">
                    <div v-for="(item, discountIndex) in couponTotalAmountList" :key="discountIndex">
                        {{item.totalAmount}} {{currentcyMap[item.currencyId]}}
                    </div>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('预计费用')">
                    <template v-for="item in estimatedCosts">
                        <div :key="item.currencyId">{{item.amount || 0}}{{currentcyMap[item.currencyId]}}</div>
                    </template>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>
        
        <el-card class="mt-10">
            <div class="card-title" slot="header">{{$t('通用')}}</div>
            <div class="form-section">
                <el-form-item :label="$t('唛头')" prop="marks">
                    <el-input v-model="form.marks" placeholder=""></el-input>
                </el-form-item>
            </div>
            <div class="form-section"> 
                <el-form-item :label="$t('报关方式')" prop="customsType">
                    <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="form.customsType" form-type="radio" defaultable />
                </el-form-item>
            </div>
            <div class="form-section">
                <el-form-item :label="$t('预计结束时间')" prop="stopTime">
                    <el-date-picker v-model="form.stopTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('是否控货')" prop="control">
                    <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" v-model="form.control" form-type="radio" defaultable />
                </el-form-item>
            </div>
            <div class="form-section">
                <el-form-item :label="$t('竞争对手')" prop="competitor">
                    <el-input v-model="form.competitor" placeholder=""></el-input>
                </el-form-item>
                <el-form-item :label="$t('重要程度')" prop="importance">
                    <el-rate v-model="form.importance"></el-rate>
                </el-form-item>
            </div>
            <div class="form-section">
                <el-form-item :label="$t('价格有效时间')" prop="startTime">
                    <el-date-picker v-model="form.startTime" placeholder="" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-form-item>
                <el-form-item label="" prop="endTime">
                    <el-date-picker v-model="form.endTime" placeholder="" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-form-item>
            </div>
                
            <div class="form-section">
                <el-form-item :label="$t('交货方式')">
                    <!--
                        接口要求数据为整数，所以增加trade_type类型的字典，用1234代码以下不同类型
                        FOB(离岸价)，CIF(到岸价)，CNF(成本加运费)，EXW(出厂价)
                    -->
                    <dict-selector :type="DICT_TYPE.ECW_TRADE_TYPE" fomtter="number" v-model="form.tradeType" />
                    
                </el-form-item>
                <el-form-item :label="$t('交货地址')">
                    <el-input v-model="form.tradeAdress" placeholder="港口或地点"></el-input>
                </el-form-item>
            </div>
            <div class="form-section">
                <el-form-item :label="$t('备注')" :span="2">
                    <el-input v-model="form.remarks" type="textarea" placeholder="" style="width:500px; height: 100px"></el-input>
                </el-form-item>
            </div>
        </el-card>

        <el-card  class="mt-10" v-if="transport">
            <div class="card-title" slot="header">{{transport.label}}</div>
            <!-- <el-form-item :label="$t('快递单号')">
                <el-input v-model="form.number" :placeholder="$t('请输入购买商品的快递单号')"></el-input>
            </el-form-item> -->
            <el-form-item :label="$t('是否双清')" v-if="[2,3,4].indexOf(+form.transportId) > -1">
                <dict-selector v-model="form.doubleClear" form-type="radio" :type="DICT_TYPE.ECW_DOUBLE_CLEAR" />
            </el-form-item>
            <el-form-item :label="$t('航空公司')" v-if="[3,4].indexOf(+form.transportId) > -1">
                <!--待查询备选数据-->
                <!-- <el-select placeholder="" v-model="form.airlineCompany">
                </el-select> -->
                <supplier-selector v-model="form.airlineCompany" companyType="10" />
            </el-form-item>
            
            <el-form-item :label="$t('船公司')" v-if="[2].indexOf(+form.transportId) > -1">
                <!-- <el-select placeholder="" v-model="form.shippingCompany">
                </el-select> -->
                <supplier-selector v-model="form.shippingCompany" companyType="9" />
            </el-form-item>

            <el-form-item :label="$t('清关证书')" v-if="[2,3,4].indexOf(+form.transportId) > -1">
                <dict-selector v-model="form.customsClearCert"  form-type="radio" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" fomatter="bool" />
            </el-form-item>
            <el-form-item :label="$t('清关证书备注')" v-if="[2,3,4].indexOf(+form.transportId) > -1">
                <el-input v-model="form.remarks" ></el-input>
            </el-form-item>
            <el-form-item :label="$t('是否拆包')" v-if="[3,4].indexOf(+form.transportId) > -1">
                <dict-selector v-model="form.isUnpack"  form-type="radio" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" fomatter="bool" />
            </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" fomatter="bool" />
                <span style="margin-left:10px">{{$t('注：若只有一件，货到仓库立即发，选“是”，多件需仓库集运待发，选“否”')}}</span>
            </el-form-item>
            <br/>
            <el-form-item :label="$t('特殊要求')" >
                <dict-selector v-model="form.packageType" form-type="checkbox" :type="DICT_TYPE.ORDER_SPECIAL_NEEDS" multiple />
            </el-form-item>
            <br/>
            <el-form-item :label="$t('特殊要求备注')">
                <el-input v-model="form.packageRemarks"  ></el-input>
            </el-form-item>
        </el-card>
        

        <el-form-item label="" class="mt-20">
            <el-button type="primary" @click="submitForm">{{$t('确定')}}</el-button>
            <el-button @click="$store.dispatch('tagsView/delCurrentView')">{{$t('取消')}}</el-button>
        </el-form-item>
      </el-form>


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

<script>
import { createOffer, updateOffer, getOffer} from "@/api/ecw/offer";
import ProductSelector from '@/components/ProductSelector'
import {getProductAttrList} from '@/api/ecw/productAttr'
import {getChannelList} from '@/api/ecw/channel'
import Selector from '@/components/Selector'
import {openedRouterList as getOpenedRouterList} from '@/api/ecw/warehouse'
import {getTradeCityList} from '@/api/ecw/region'
import {getDictData} from  '@/utils/dict'
import {getCurrencyList} from '@/api/ecw/currency'
import {getUnitList} from '@/api/ecw/unit'
import {calculationPrice} from '@/api/ecw/product'
import SupplierSelector from '@/components/SupplierSelector'
import ChooseContactDialog from '@/components/ChooseContactDialog'
import QuickCreateCustomer from '@/components/QuickCreateCustomer'
import {getCustomerContactsSelect} from '@/api/ecw/customerContacts'

export default {
  name: "OfferEdit",
  components: {
    ProductSelector, Selector, SupplierSelector,ChooseContactDialog, QuickCreateCustomer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      productList:[], // 商品信息
      productAttrList:[],  // 商品属性
      channelList: [], // 出货取到
      routerList: [],
      tradeCityList: [],
      consignor: {}, // 发货人
      consignee:{}, // 收货人
      transportList: [],
      currencyList:[],
      unitList:[],
      // couponList: [],
      fee: {}, // 费用
      // 表单参数
      form: {
        sendstatus:0,
        type: [],
        isCargoControl: false,
      },
      // 表单校验
      rules: {
        lineId:         [{ required: true, message: "请选择线路"}],
        consignorId:    [{ required: true, message: "发货人不能为空",}],
        consigneeId:    [{ required: true, message: "收货人不能为空"}],
        startTime:      [{ required: true, message: "有效期开始时间不能为空"}],
        endTime:        [{ required: true, message: "有效期结束时间不能为空"}],
        transportId:    [{ required: true, message: "选择运输方式"}],
        channelId:      [{ required: true, message: "选择出货渠道"}],
        /*sendstatus: [{ required: true, message: "站内信状态，0未发送，1已发送不能为空", trigger: "blur" }], */
      },
      labelStyle: 'width:120px',
      productNames: {}, // 品名id和名称对应关系
      couponAvailableGroupDtoList: [], // 可用优惠
      couponTotalAmountList: [], // 优惠总额
      contactChooseType: null, // 联系人选择对象consignor(发货人) 或者 consignee（收货人）
      quickCreateType: null, // 快速新建客户类型，1发货人，2收货人
      getOpenedRouterListHandler: undefined
    };
  },
  computed:{
    exportCityList(){
        return this.tradeCityList.filter(item => item.type == 2)
    },
    importCityList(){
        return this.tradeCityList.filter(item => item.type == 1)
    },
    getDictData(){
        return (type, value) => getDictData(type, value) || {}
    },
    // 根据线路id显示线路名称
    getRouterNameById(){
        return routerId => {
            let router = this.routerList.find(item => item.id == routerId)
            console.log({router})
            if(router){
                return router.startTitleZh + ' > ' + router.destTitleZh
            }
            return '-'
        }
    },
    // 根据渠道id显示渠道名
    getChannelNameById(){
        return channelId => {
            return this.channelList.find(item => item.channelId == channelId) ?. nameZh
        }
    },
    // 当前运输方式
    transport(){
        return this.transportList.find(item => item.value == this.form.transportId)
    },
    selectedRouter(){
        // otherService 1 送货上门，2非控货订单代收货款
        if(!this.form.lineId)return null
        return this.routerList.find(item => item.id == this.form.lineId)
    },
    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: 0,
            totalVolume: 0,
            totalWeight: 0,
            totalWorth: 0,
        }
        this.productList.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

        })
        return sum
    },
    // 总有优惠金额
    couponList(){
        let arr = []
        this.couponAvailableGroupDtoList.forEach(item => {
            if(item.couponAvailableDtoList && item.couponAvailableDtoList.length){
                // 只取第一个
                let it = item.couponAvailableDtoList[0]
                arr.push({
                        prodId: item.prodId,
                        type: it.type,
                        titleZh: it.titleZh,
                        titleEn: it.titleEn,
                        endTime: it.endTime,
                        reduceAmount: it.reduceAmount,
                        reduceCurrencyId: it.reduceCurrencyId
                    })
            }
        })
        return arr
    },
    // 计算返回的费用清单
    feeDtoList(){
        return this.fee.feeDtoList || []
    },
    // 清关费
    clearanceFeeList(){
        return this.feeDtoList.filter(item => item.feeType == 2)
    },
    // 运费
    freightFeeList(){
        return this.feeDtoList.filter(item => item.feeType == 1)
    },
    // 原价（清关费 + 运费）
    originalFeeList(){
        let arr = []
        this.clearanceFeeList.forEach(item => {
            let it = {...item}
            let freight = this.freightFeeList.find(fee => fee.currencyId == item.currencyId)
            if(freight){
                it.amount += freight.amount
            }
            arr.push(it)
        })
        return arr
    },
    // 预计费用(原价 - 优惠金额)
    estimatedCosts(){
        let arr = []
        this.originalFeeList.forEach(item => {
            let it = {...item}
            let coupon = this.couponList.find(coupon => coupon.reduceCurrencyId == item.currencyId)
            if(coupon){
                it.amount -= coupon.reduceAmount
            }
            arr.push(it)
        })
        return arr
    },
    // 路线开通的服务
    routeOtherServices(){
        if(!this.selectedRouter || !this.selectedRouter.otherService) return []
        return this.selectedRouter.otherService.split(',')
    }
    /* productKeyd(){
        return arrryToKeyedObjectBy(this.productList, 'prodId')
    } */
  },
  watch:{
    // 始发地
    'form.departureId'(){
        this.getOpenedRouterList()
    },
    // 目的地
    'form.objectiveId'(){
        this.getOpenedRouterList()
    },
    'form.transportId'(){
        this.getOpenedRouterList()
    },
    'form.channelId'(){
        this.getOpenedRouterList()
    },
    'form.lineId'(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)
    },
    // 选择的路线变化后，需要判断是否开通了对应的服务，如果没开通需要取消对应的服务选择
    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)
            }
        })
    }
  },
  created() {
    getProductAttrList().then(res => this.productAttrList = res.data)
    getChannelList().then(res => this.channelList = res.data)
    getTradeCityList().then(res => this.tradeCityList = res.data)
    getCurrencyList().then(res => this.currencyList = res.data)
    getUnitList().then(res => this.unitList = res.data)
    this.transportList = this.getDictDatas(this.DICT_TYPE.ECW_TRANSPORT_TYPE)

    if(this.$route.query.id){
        getOffer(this.$route.query.id).then(res => {
            let formData = res.data
            formData.type = formData.type ? formData.type.split(',').filter(item => item != '') : []
            this.$set(this, 'form', formData)

            if(res.data.offerProdRespVOList){
                res.data.offerProdRespVOList.forEach(item => {
                    this.addProduct({
                        "goodsType": item.goodsType,
                        "brand": item.brand,
                        "unit": item.unit,
                        "channelId": item.channelId,
                        "lineId": item.lineId,
                        "prodId": item.prodId,
                        "num": item.num,
                        "boxGauge": item.boxGauge,
                        "volume": item.volume,
                        "transportId": item.transportId,
                        "weight": item.weight,
                        "worth": item.worth,
                        "prodAttrArr": item.prodAttrIds && item.prodAttrIds != '' ? item.prodAttrIds.split(',').filter(item => item != '').map(item => +item) : []
                    })
                })
            }

            // 接口只返回了发货人和收货人ID，还需要调用接口获取详细信息回显
            getCustomerContactsSelect({ids: [res.data.consigneeId, res.data.consignorId].join(',')}).then(({data}) => {
                this.contactChooseType = 'consignee'
                this.onContactChoose(data.find(item => item.customerContactsId == res.data.consigneeId))
                this.contactChooseType = 'consignor'
                this.onContactChoose(data.find(item => item.customerContactsId == res.data.consignorId))
            })
            /* res.data.transportRespVOList.forEach(item => {
                let transport = this.transportList.find(t => t.transportId ==  item.transportId)
                console.log(item.transportId, transport)
                Object.assign(transport, item, {_enabled: true})
            }) */
            /* this.$nextTick(() => {
                this.updateEnabledTransports()
            }) */
        })
    }//else this.addProduct()
  },
  methods: {
    onContactChoose(contact){
        console.log('选择联系人', contact)
        if(!this.contactChooseType && !this.quickCreateType) return
        if(!this.contactChooseType && this.quickCreateType){
            this.contactChooseType = this.quickCreateType == 1 ? 'consignor' : 'consignee'
        }
        this.$set(this.form, this.contactChooseType + 'Company', contact.company)
        this.$set(this.form, this.contactChooseType + 'Id', contact.customerContactsId)
        this.$set(this.form, this.contactChooseType + 'CountryCode', contact.areaCode)
        this.$set(this.form, this.contactChooseType + 'Email', contact.email)
        // this.$set(this.form, this.contactChooseType + 'Id', contact.customerId)
        this.$set(this.form, this.contactChooseType + 'Name', contact.contactsName)
        this.$set(this.form, this.contactChooseType + 'Phone', contact.phoneNew)
        this.contactChooseType = null
        this.quickCreateType = null
    },
    /* onProductChange(row, product){
        row.goodsType = product.typeId;
        // 保存商品id和品名，用于优惠信息显示
        this.$set(this.productNames, product.id, product.titleZh)
        this.calculationPrice()
    }, */
    onProductChange(row, product){
        console.log(product)
        row.goodsType = product ? product.typeId : null
        row.prodAttrArr = !product ? [] : product.attrId.split(',').filter(item => item !== '').map(item => +item)
        this.$set(this.productNames, product.id, {
            titleZh: product.titleZh,
            titleEn: product.titleEn
        })
        this.calculationPrice()
    },
    onLineChange(row){
        this.calculationPrice()
        // this.updateEnabledTransports()
    },
    onChannelChange(row){
        this.calculationPrice()
    },
    onProductAttrChange(row, attr){
        this.calculationPrice()
    },
    addProduct(data){
        if(!data && !this.form.lineId){
            return this.$message.error(this.$t('请先选择路线'))
        }
        console.log('addProduct', JSON.stringify(data))
        this.productList.push(data || {prodAttrArr:[]})
    },
    // 计算商品运费
    /* getProductFee(row){
        if(!row.prodId || !row.transportId || !row.lineId || !row.num || !row.weight)return false
        if(row.prodAttrArr){
            row.prodAttrIds = row.prodAttrArr.join(',')
        }
        getProductFeeList(row).then(res => {
            this.$set(row, 'fee', res.data[0] || {})
        })
    }, */
    // 获取路线
    getOpenedRouterList(){
        let params = {}
        if(this.form.departureId){
            params.startCityId = this.form.departureId
        }
        if(this.form.objectiveId){
            params.destCityId = this.form.objectiveId
        }
        if(this.form.transportId){
            params.transportType = this.form.transportId
        }
        if(this.form.channelId){
            params.channelId = this.form.channelId
        }
        getOpenedRouterList(params).then(res => this.routerList = res.data)
    },
    // 计算体积
    calcVolume(row){
        if(!row.boxGauge || !row.num) return false
        try{
            row.volume = (eval(row.boxGauge) * row.num).toFixed(2)
        }catch(e){
            row.volume = ''
        }
    },
    // 删除一条产品
    delProduct(index){
        this.$confirm(this.$t('确定删除此条内容么？'))
            .then(res => {
                this.productList.splice(index, 1)
            })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        
        this.productList.map(item => {
            item.prodAttrIds = item.prodAttrArr.join(',')
            item.lineId = this.form.lineId
            item.channelId = this.form.channelId
            item.transportId = this.form.transportId
            item.brandType = item.brand ? 1 : 0
        })
        this.transportList.map(item => {
            if(item._enabled){
                item.lineIds = Array.from(item.lineIdSet).join(',')
                item.channelIds = Array.from(item.channelIdSet).join(',')
            }
        })
        // 修改的提交
        if (this.form.offerId != null) {
            let data = Object.assign({}, this.form, {
                transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
                prodUpdateReqVOList: this.productList
            })
            updateOffer(data).then(response => {
                this.$modal.msgSuccess(this.$t("修改成功"));
                this.$router.back()
            });
            return;
        }
        let data = Object.assign({}, this.form, {
            transportCreateReqVOList: this.transportList.filter(item => item._enabled),
            prodCreateReqVOList: this.productList
        })
        // 添加的提交
        createOffer(data).then(response => {
          this.$modal.msgSuccess(this.$t("新增成功"));
          this.$router.replace('index')
        });
      });
    },
    setLink(row){
        this.$prompt(this.$t('请输入商品链接'), {inputValue: row.link}).then(({value}) => {
            console.log('value', value)
            this.$set(row, 'link', value)
        })
    },
    // 计算商品运费
    calculationPrice(){
        let calcable = true
        if(!this.productList.length) return
        this.productList.forEach(item => {
            if(!item.weight || !item.prodId){
                console.log('重量和产品为选择', item)
                calcable = false
            }
        })
        if(this.calculating || !calcable) return false
        this.calculating = true
        
        console.log('calculationPrice')
        
        calculationPrice({
            lineId: this.form.lineId,
            transportId: this.form.transportId,
            channelId: this.form.channelId,
            prodConditionParamList: this.productList,
            consigneeCustomerContactsId: this.form.consigneeCustomerContactsId,
            consignorCustomerContactsId: this.form.consignorCustomerContactsId,
            customsType: this.form.customsType,
            isCargoControl: this.form.control,
            orderType: this.form.orderType,
        }).then(res => {
            this.$set(this, 'fee', res.data.costDto)
            this.$set(this, 'couponTotalAmountList', res.data.availableDto.couponTotalAmountList)
            this.$set(this, 'couponAvailableGroupDtoList', res.data.availableDto.couponAvailableGroupDtoList)
            
            this.productList.map((item, index) => {
                this.$set(item, 'fee', res.data.prodCostDtoList[index] || null)
            })
        }).finally(() => {
            this.calculating = false
        })
    },
  }
};
</script>
<style lang="scss" scoped>
.card-title{
    font-size: 18px;
    display: flex;
    .card-name{
        flex: 1;
    }
}
.form-section{
    .contact{
        display: flex;
        align-items: center;
        img.phonebook{
            width: 30px;
            height: 30px;
            margin-left: 10px;
            cursor: pointer;
        }
    }
    
}
</style>