<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('所属人')" prop="relation">
                <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 style="width:120px"/>
                        <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  class="w-200"/>
                </el-form-item>
                <el-form-item label="Email" prop="consignorEmail">
                    <el-input v-model="form.consignorEmail" disabled  class="w-200"/>
                </el-form-item>
            </div>
            <div class="form-section">
                <el-form-item :label="$t('收货人')" prop="consigneeId">
                    <div class="contact">
                        <el-input v-model="form.consigneeName" placeholder="请选择或新建" :disabled="true"  style="width:120px"/>
                        <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"/>
                </el-form-item>
                <el-form-item :label="$t('收货人公司')" prop="consigneeCompany">
                    <el-input v-model="form.consigneeCompany" :disabled="true"  class="w-200"/>
                </el-form-item>
                <el-form-item label="Email" prop="consigneeEmail">
                    <el-input v-model="form.consigneeEmail" :disabled="true" class="w-200"/>
                </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"  class="w-200"/>
                </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"
                    class="w-200"
                    ></selector>
                </el-form-item>
            </div>

            <div class="form-section">
                <el-form-item :label="$t('始发城市')" prop="departureId">
                    <el-select v-model="form.departureId" :placeholder="$t('请选择始发地')"  class="w-200">
                        <el-option v-for="item in exportCityList" :label="$l(item, 'title')" :value="item.id" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('目的城市')" prop="objectiveId">
                    <el-select v-model="form.objectiveId" :placeholder="$t('请选择目的地')"  class="w-200">
                        <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('请在右侧选择线路')" class="w-200"></el-input>
                </el-form-item>
                <select size="5" v-model="form.lineId" style="min-width: 300px; border:1px solid #DCDFE6; border-radius:4px">
                    <template v-for="item in routerList">
                        <option :value="item.id" :key="item.id">{{$l(item, 'startTitle')}} >> {{$l(item, 'destTitle')}}</option>
                    </template>
                </select>
            </div>
        </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="!canAddProduct"></el-button>
            </div>
            <el-table :data="form.prodCreateReqVOList" border class="product-list">
              <el-table-column :label="$t('序号')" width="60px" fixed>
                <template slot-scope="scope">
                    {{scope.$index + 1}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('中文品名')" width="160px">
                <template slot-scope="scope">
                    <el-form-item label=""
                        :prop="`prodCreateReqVOList.${scope.$index}.prodId`"
                        :rules="{
                            required: true, message: $t('请选择产品'), trigger: 'blur'
                        }"
                        class="mb-0 mr-0"
                    >
                        <product-selector v-model="scope.row.prodId" @change="onProductChange(scope.row, $event)" :disabled="!canAddProduct" />
                    </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('英文品名')" width="160px">
                <template slot-scope="{row}">
                    <product-selector lang="En" v-model="row.prodId" @change="onProductChange(row, $event)" :disabled="!canAddProduct" />
                </template>
              </el-table-column>
               <el-table-column :label="$t('品牌')" width="100px">
                <template slot-scope="scope">
                    <el-form-item label=""
                        :prop="`prodCreateReqVOList.${scope.$index}.brand`"
                        :rules="{
                            required: true, message: $t('请选择品牌'), trigger: 'blur'
                        }"
                        class="mb-0 mr-0"
                    >
                        <dict-selector v-model="scope.row.brand" :type="DICT_TYPE.ECW_IS_BRAND" defaultable @input="calculationPrice" :disabled="!canAddProduct" />
                    </el-form-item>
                </template>
              </el-table-column>
             
              <el-table-column :label="$t('件数')" width="90px">
                <template slot-scope="{row}">
                    <el-input v-model.number="row.num" @input="calculationPrice" :disabled="!canAddProduct" />
                </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" :disabled="!canAddProduct" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('数量') + '(个)'">
                <template slot-scope="{row}">
                    <el-input v-model.number="row.quantity" @input="calculationPrice" :disabled="!canAddProduct" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('总体积') + '(m³)'" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.volume" @input="calculationPrice" :disabled="!canAddProduct"/>
                </template>
              </el-table-column>
              <el-table-column :label="$t('总重量') + '(kg)'" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.weight" @input="calculationPrice" :disabled="!canAddProduct" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('总货值') + '(RMB)'" width="100px">
                <template slot-scope="scope">
                    <el-form-item label=""
                        :prop="`prodCreateReqVOList.${scope.$index}.worth`"
                        :rules="{
                            required: true, message: $t('货值不能为空'), trigger: 'blur'
                        }"
                        class="mb-0 mr-0"
                    >
                        <el-input v-model="scope.row.worth" @input="calculationPrice" :disabled="!canAddProduct" />
                    </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="$t('商品特性')" width="250px">
                <template slot-scope="{row}">
                    <el-checkbox-group v-model="row.prodAttrArr" @change="onProductAttrChange(row, $event)" :disabled="!canAddProduct">
                      <el-checkbox v-for="item in productAttrList" :label="item.id" :key="item.id">{{item.attrName}}</el-checkbox>
                    </el-checkbox-group>
                </template>
              </el-table-column>
              <el-table-column :label="$t('运费')" width="200px">
                <template slot-scope="{row}">
                    <template v-if="row.fee && row.fee.charging == 1">
                        <template v-if="!row.fee.oneFreight">{{$t('未报价')}}</template>
                        <template v-else>
                            {{$t('全包价')}}：{{row.fee.oneFreight}} {{currencyMap[row.fee.freightCurrency]}} / {{unitMap[row.fee.freightVolume]}}
                        </template>
                    </template>
                    <template v-else-if="!row.fee || !row.fee.oneFreight && !row.fee.oneClearanceFee">{{$t('未报价')}}</template>
                    <template v-else-if="row.fee">
                        <div>
                            {{$t('运费')}}：{{row.fee.oneFreight}} {{currencyMap[row.fee.freightCurrency]}} / {{unitMap[row.fee.freightVolume]}}
                        </div>
                        <div>
                            {{$t('清关费')}}：{{row.fee.oneClearanceFee}} {{currencyMap[row.fee.clearanceFeeCurrency]}} / {{unitMap[row.fee.clearanceFeeVolume]}}
                        </div>
                    </template>
                </template>
              </el-table-column>
              <el-table-column :label="$t('是否预付')">
                <template slot-scope="{row}">
                    <dict-tag v-if="row.fee" :type="DICT_TYPE.ECW_PAY_ADVANCE" :value="row.fee.isPayAdvance"  />
                </template>
              </el-table-column>
              <el-table-column :label="$t('商品链接')" width="200px" align="center">
                <template slot-scope="{row}">
                    <el-link type="primary" :href="row.link" target="_blank" style="display:block">{{row.link}}</el-link>
                    <el-button type="primary" size="mini" @click="setLink(row)" :disabled="!canAddProduct">
                        {{row.link ? $t('编辑商品链接') : $t('添加商品链接')}}
                    </el-button>
                </template>
              </el-table-column>
              <el-table-column :label="$t('快递单号')" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.expressNo" placeholder="" :disabled="!canAddProduct" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('操作')" width="180px" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="danger" @click="delProduct(scope.$index)">{{$t('删除')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 
        </el-card>
        <el-card  class="mt-10"> -->
            <div class="card-title" style="padding:20px 0;">{{$t('合计')}}</div>
            <el-descriptions :column="4" border>
                <el-descriptions-item :label="$t('总件数')">
                    {{sum.totalNum.toFixed() || 0}}
                </el-descriptions-item>
                <el-descriptions-item label="总体积">
                    {{sum.totalVolume.toFixed() || 0}}m³
                </el-descriptions-item>
                <el-descriptions-item label="总重量">
                    {{sum.totalWeight.toFixed() || 0}}kg
                </el-descriptions-item>
                <el-descriptions-item label="总数量">
                    {{sum.totalQuatity.toFixed() || 0}}
                </el-descriptions-item>
                
                <el-descriptions-item :label="$t('总货值') + '(RMB)'">
                    {{sum.totalWorth.toFixed() || 0}}{{$t('元')}}
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

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

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

            <el-descriptions :column="1" class="mt-20">
                <el-descriptions-item :label="$t('优惠费用')"  v-if="couponTotalAmountList && couponTotalAmountList.length">
                    <div v-for="(item, discountIndex) in couponTotalAmountList" :key="discountIndex">
                        {{item.totalAmount}} {{currencyMap[item.currencyId]}}
                    </div>
                </el-descriptions-item>
                <el-descriptions-item :label="$t('预计费用')" :span="1">
                    <template v-for="item in estimatedCosts">
                        <div :key="item.currencyId">{{item.amount || 0}}{{currencyMap[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="" class="w-200"></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" class="w-200"></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" />
                </el-form-item>
            </div>
            <div class="form-section">
                <el-form-item :label="$t('竞争对手')" prop="competitor">
                    <el-input v-model="form.competitor" placeholder="" class="w-200"></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" class="w-200"></el-date-picker>
                </el-form-item>
                <el-form-item label="" prop="endTime">
                    <el-date-picker v-model="form.endTime" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" class="w-200"></el-date-picker>
                </el-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"  class="w-200"/>
                    
                </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.transportVO.doubleClear" form-type="radio" :type="DICT_TYPE.ECW_DOUBLE_CLEAR" />
            </el-form-item>
            <el-form-item :label="$t('航空公司')" v-if="[3,4].indexOf(+form.transportId) > -1">
                <!--待查询备选数据-->
                <!-- <el-select placeholder="" v-model="form.airlineCompany">
                </el-select> -->
                <supplier-selector v-model="form.transportVO.airlineCompany" companyType="10" />
            </el-form-item>
            
            <el-form-item :label="$t('船公司')" v-if="[2].indexOf(+form.transportId) > -1">
                <!-- <el-select placeholder="" v-model="form.shippingCompany">
                </el-select> -->
                <supplier-selector v-model="form.transportVO.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.transportVO.customsClearCert"  form-type="radio" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" />
            </el-form-item>
            <el-form-item :label="$t('清关证书备注')" v-if="[2,3,4].indexOf(+form.transportId) > -1">
                <el-input v-model="form.transportVO.remarks" ></el-input>
            </el-form-item>
            <el-form-item :label="$t('是否拆包')" v-if="[3,4].indexOf(+form.transportId) > -1">
                <dict-selector v-model="form.transportVO.isUnpack"  form-type="radio" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" />
            </el-form-item>
            <el-form-item :label="$t('单票立刻转运')" v-if="[3,4].indexOf(+form.transportId) > -1">
                <dict-selector v-model="form.transportVO.isSingleTicketTransport"  form-type="radio" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" />
                <span style="margin-left:10px">{{$t('注：若只有一件，货到仓库立即发，选“是”，多件需仓库集运待发，选“否”')}}</span>
            </el-form-item>
            <br/>
            <el-form-item :label="$t('特殊要求')" >
                <dict-selector v-model="form.transportVO.packageTypeArr" form-type="checkbox" :type="DICT_TYPE.ORDER_SPECIAL_NEEDS" multiple />
            </el-form-item>
            <br/>
            <el-form-item :label="$t('特殊要求备注')">
                <el-input v-model="form.transportVO.packageRemarks"  ></el-input>
            </el-form-item>
        </el-card>
        

        <el-form-item label="" class="mt-20">
            <!-- 非草稿状态显示为编辑按钮 -->
            <el-button v-if="form.offerId && form.status != 2" type="primary" @click="submitForm(2)">{{$t('编辑')}}</el-button>
            
            <template v-else>
                <el-button type="primary" @click="submitForm(2)">{{$t('保存草稿')}}</el-button> <!-- 草稿 -->
                <el-button type="primary" @click="submitForm(3)">{{$t('确认报价')}}</el-button> <!-- 需求确认 -->
            </template>
            <el-button @click="$store.dispatch('tagsView/delCurrentView')">{{$t('取消')}}</el-button>
        </el-form-item>
      </el-form>


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

<script>
import { createOffer, updateOffer, getOffer} from "@/api/ecw/offer";
import ProductSelector from '@/components/ProductSelector'
import {getProductAttrList} from '@/api/ecw/productAttr'
import {getChannelList} from '@/api/ecw/channel'
import Selector from '@/components/Selector'
import {openedRouterList as getOpenedRouterList} from '@/api/ecw/warehouse'
import {getTradeCityList} from '@/api/ecw/region'
import {getDictData} from  '@/utils/dict'
import {getCurrencyList} from '@/api/ecw/currency'
import {getUnitList} from '@/api/ecw/unit'
import {calculationPrice} from '@/api/ecw/product'
import SupplierSelector from '@/components/SupplierSelector'
import ChooseContactDialog from '@/components/ChooseContactDialog'
import QuickCreateCustomer from '@/components/QuickCreateCustomer'
import {getCustomerContactsSelect} from '@/api/ecw/customerContacts'
import Decimal from 'decimal.js'
window.Decimal=  Decimal
export default {
  name: "EcwOfferEdit",
  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: [],
        control: false,
        isCargoControl: false,
        prodCreateReqVOList:[],
        transportVO: {}
      },
      // 表单校验
      rules: {
        marks: [
            {
                validator: (rule, value, callback) => {
                    if(value && !/[a-zA-Z]/.test(value.charAt(0))){
                        return callback(new Error(this.$t('唛头必须以字母开头')))
                    }
                    callback()
                },
                trigger: 'blur'
            }
        ],
        lineId:         [{ required: true, message: "请选择线路"}],
        consignorId:    [{ required: true, message: "发货人不能为空",}],
        consigneeId:    [{ required: true, message: "收货人不能为空"}],
        startTime:      [{ required: true, message: "有效期开始时间不能为空"}],
        endTime:        [{ required: true, message: "有效期结束时间不能为空"}],
        transportId:    [{ required: true, message: "选择运输方式"}],
        channelId:      [{ required: true, message: "选择出货渠道"}],
        stopTime:       [{ required: true, message: "不能为空"}],
        relation:       [{ required: true, message: "请选择所属人"}],
        control:        [{ required: true, message: "请选择是否控货"}],
        importance:     [{ 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)
    },
    currencyMap(){
        let map = {}
        this.currencyList.forEach(item => {
            map[item.id] = this.$l(item, 'title')
        })
        return map
    },
    unitMap(){
        let map = {}
        this.unitList.forEach(item => {
            map[item.id] = this.$l(item, 'title')
        })
        return map
    },
    sum(){
        let sum = {
            totalNum: new Decimal(0),
            totalVolume: new Decimal(0),
            totalWeight: new Decimal(0),
            totalWorth: new Decimal(0),
            totalQuatity: new Decimal(0)
        }
        this.form.prodCreateReqVOList.forEach(item => {
            sum.totalNum = sum.totalNum.plus(item.num || 0)
            sum.totalVolume = sum.totalVolume.plus(item.volume || 0)
            sum.totalWeight = sum.totalWeight.plus(item.weight || 0)
            sum.totaltotalWorthNum = sum.totalWorth.plus(item.worth || 0)
            sum.totalQuatity = sum.totalQuatity.plus(item.quantity || 0)
        })
        return sum
    },
    // 总有优惠金额
    couponList(){
        let arr = []
        this.couponAvailableGroupDtoList.forEach(item => {
            if(item.couponAvailableDtoList && item.couponAvailableDtoList.length){
                // 只取第一个
                let it = item.couponAvailableDtoList[0]
                arr.push({
                        prodId: item.prodId,
                        type: it.type,
                        titleZh: it.titleZh,
                        titleEn: it.titleEn,
                        endTime: it.endTime,
                        reduceAmount: it.reduceAmount,
                        reduceCurrencyId: it.reduceCurrencyId
                    })
            }
        })
        return arr
    },
    // 计算返回的费用清单
    feeDtoList(){
        return this.fee.feeDtoList || []
    },
    // 清关费
    clearanceFeeList(){
        return this.feeDtoList.filter(item => item.feeType == 2)
    },
    // 运费
    freightFeeList(){
        return this.feeDtoList.filter(item => item.feeType == 1)
    },
    // 原价（清关费 + 运费）
    originalFeeList(){
        let arr = []
        this.clearanceFeeList.forEach(item => {
            let it = {
                src: '清关费',
                currencyId: item.currencyId,
                amount: Decimal(item.amount)
            }
            let freight = this.freightFeeList.find(fee => fee.currencyId == item.currencyId)
            if(freight){
                it.amount = it.amount.plus(freight.amount)
            }
            arr.push(it)
        })
        // 判断是否有运费单位不在清关费里的
        this.freightFeeList.forEach(item => {
            if(!arr.find(arrItem => arrItem.currencyId == item.currencyId)){
                arr.push({
                    src: '未计算的运费',
                    currencyId: item.currencyId,
                    amount: Decimal(item.amount)
                })
            }
        })
        return arr
    },
    // 预计费用(原价 - 优惠金额 + 其他费用 + 保价费)
    estimatedCosts(){
        let arr = []
        let withInsuranceFee = false
        this.originalFeeList.forEach(item => {
            let it = {
                currencyId: item.currencyId,
                amount: Decimal(item.amount)
            }
            let coupon = this.couponList.find(coupon => coupon.reduceCurrencyId == item.currencyId)
            if(coupon){
                it.amount = it.amount.minus(coupon.reduceAmount)
            }
            if(this.form.otherFee && this.form.otherFeeCurrencyId == item.currencyId){
                it.amount = it.amount.plus(this.form.otherFee)
            }
            // 保价费（美元）
            if(item.currencyId == 1 && this.fee && this.fee.insuranceFee){
                it.amount = it.amount.plus(this.fee.insuranceFee)
                withInsuranceFee = true
            }
            arr.push(it)
        })
        
        // 没有累加保价费(没有美元计价)但是有保价费则需要加上去
        if(!withInsuranceFee && this.fee && this.fee.insuranceFee){
            arr.push({
                currencyId: 1,
                amount: Decimal(this.fee.insuranceFee)
            })
        }

        return arr
    },
    // 路线开通的服务
    routeOtherServices(){
        if(!this.selectedRouter || !this.selectedRouter.otherService) return []
        return this.selectedRouter.otherService.split(',')
    },
    // 是否可以添加商品
    canAddProduct(){
        if(!this.form.lineId){
            return false
        }
        // 如果是海空联运或者空运专线则必须选择渠道
        if(this.transport && this.transport.cssClass == 'channel' && !this.form.channelId ){
            return false
        }
        return true
    }
  },
  watch:{
    // 始发地
    'form.departureId'(){
        this.getOpenedRouterList()
    },
    // 目的地
    'form.objectiveId'(){
        this.getOpenedRouterList()
    },
    'form.transportId'(transportId){

        // 海空联运默认数据
        if(transportId == 4){
            this.$set(this.form.transportVO, Object.assign(this.form.transportVO, {
                "doubleClear":"1",
                "customsClearCert":false,
                "isUnpack":false,
                "isSingleTicketTransport":false,
                "packageTypeArr":[],
                "packageType":""
            }))
        }
        this.getOpenedRouterList()
    },
    '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)
    },
    'form.transportVO.packageTypeArr'(val){
        this.$set(this.form.transportVO, 'packageType', val.join(','))
    },
    // 选择的路线变化后，需要判断是否开通了对应的服务，如果没开通需要取消对应的服务选择
    selectedRouter(val){
        if(!val) return
        ['1', '4'].forEach(service => {
            if(this.routeOtherServices.indexOf(service) < 0 && this.form.type.indexOf(service) > -1){
                this.form.type.splice(this.form.type.findIndex(item => item == service), 1)
            }
        })
    }
  },
  activated(){
    if(this.form.offerId != this.$route.query.id){
        this.getOffer()
    }
  },
  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){
        this.getOffer()
    }else this.addProduct()
  },
  methods: {
    getOffer(){
        getOffer(this.$route.query.id).then(res => {
            let formData = res.data
            formData.type = formData.type ? formData.type.split(',').filter(item => item != '') : []
            formData.prodCreateReqVOList = []
            if(formData.transportVO && formData.transportVO.packageType){
                formData.transportVO.packageTypeArr = formData.transportVO.packageType.split(",").filter(item => item && item != '')
            }
            if(res.data.offerProdRespVOList){
                res.data.offerProdRespVOList.forEach(item => {
                    formData.prodCreateReqVOList.push({
                        "goodsType": item.goodsType,
                        "brand": item.brand,
                        "unit": item.unit,
                        "channelId": item.channelId,
                        "lineId": item.lineId,
                        "prodId": item.prodId,
                        "num": item.num,
                        "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) : []
                    })
                })
            }
            this.$set(this, 'form', formData)
            // 接口只返回了发货人和收货人ID，还需要调用接口获取详细信息回显
            getCustomerContactsSelect({ids: [res.data.consigneeId, res.data.consignorId].join(',')}).then(({data}) => {
                this.contactChooseType = 'consignee'
                this.onContactChoose(data.list.find(item => item.customerContactsId == res.data.consigneeId))
                this.contactChooseType = 'consignor'
                this.onContactChoose(data.list.find(item => item.customerContactsId == res.data.consignorId))
            })
        })
    },
    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){
        console.log(product)
        // row.goodsType = product ? product.typeId : null
        row.prodAttrArr = !product ? [] : product.attrId.split(',').filter(item => item !== '').map(item => +item)
        if(product){
            this.$set(this.productNames, product.id, {
                titleZh: product.titleZh,
                titleEn: product.titleEn
            })
        }
        
        this.calculationPrice()
    },
    onLineChange(row){
        this.calculationPrice()
        // this.updateEnabledTransports()
    },
    onChannelChange(row){
        this.calculationPrice()
    },
    onProductAttrChange(row, attr){
        this.calculationPrice()
    },
    addProduct(data){
        this.form.prodCreateReqVOList.push(data || {prodAttrArr:[]})
    },
    // 计算商品运费
    /* getProductFee(row){
        if(!row.prodId || !row.transportId || !row.lineId || !row.num || !row.weight)return false
        if(row.prodAttrArr){
            row.prodAttrIds = row.prodAttrArr.join(',')
        }
        getProductFeeList(row).then(res => {
            this.$set(row, 'fee', res.data[0] || {})
        })
    }, */
    // 获取路线
    getOpenedRouterList(){
        let params = {}
        if(this.form.departureId){
            params.startCityId = this.form.departureId
        }
        if(this.form.objectiveId){
            params.destCityId = this.form.objectiveId
        }
        if(this.form.transportId){
            params.transportType = this.form.transportId
        }
        if(this.form.channelId){
            params.channelId = this.form.channelId
        }
        getOpenedRouterList(params).then(res => this.routerList = res.data)
    },
    // 计算体积
    calcVolume(row){
        if(!row.boxGauge || !row.num) return false
        try{
            row.volume = (eval(row.boxGauge) * row.num).toFixed(2)
        }catch(e){
            row.volume = ''
        }
    },
    // 删除一条产品
    delProduct(index){
        this.$confirm(this.$t('确定删除此条内容么？'))
            .then(res => {
                this.form.prodCreateReqVOList.splice(index, 1)
            })
    },
    /** 提交按钮 */
    submitForm(status) {
      this.$refs["form"].validate((valid, errors) => {
        if (!valid) {
            return this.$showFormValidateErrors(errors)
        }
        
        this.form.prodCreateReqVOList.map(item => {
            item.prodAttrIds = item.prodAttrArr.join(',')
            item.lineId = this.form.lineId
            item.channelId = this.form.channelId
            item.transportId = this.form.transportId
        })
        
        // 修改的提交
        if (this.form.offerId != null) {
            let data = Object.assign({}, this.form, {
                // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
                prodUpdateReqVOList: this.getProductListWithDefaultValue()
            })
            if(data.status < 3){
                data.status = status
            }
            updateOffer(data).then(response => {
                this.$modal.msgSuccess(this.$t("修改成功"));
                this.$router.back()
            });
            return;
        }
        let data = Object.assign({}, this.form, {
            prodCreateReqVOList: this.getProductListWithDefaultValue(),
            status
        })
        // 添加的提交
        createOffer(data).then(response => {
          this.$modal.msgSuccess(this.$t("新增成功"));
          this.$redirect('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.form.prodCreateReqVOList.length) return
        this.form.prodCreateReqVOList.forEach(item => {
            if(!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.getProductListWithDefaultValue(),
            consigneeCustomerContactsId: this.form.consigneeCustomerContactsId,
            consignorCustomerContactsId: this.form.consignorCustomerContactsId,
            customsType: this.form.customsType,
            isCargoControl: this.form.control,
            orderType: this.form.orderType,
        }).then(res => {
            this.$set(this, 'fee', res.data.costDto)
            if(res.data.availableDto){
                this.$set(this, 'couponTotalAmountList', res.data.availableDto.couponTotalAmountList)
                this.$set(this, 'couponAvailableGroupDtoList', res.data.availableDto.couponAvailableGroupDtoList)
            }
            
            
            this.form.prodCreateReqVOList.map((item, index) => {
                this.$set(item, 'fee', res.data.prodCostDtoList[index] || null)
            })
        }).finally(() => {
            this.calculating = false
        })
    },
    // 体积。件数，数量，重量为选填，但是接口确实必填，所以生成一个副本并赋予默认值
    getProductListWithDefaultValue(){
        let arr = []
        this.form.prodCreateReqVOList.forEach(item => {
            let tmp = {...item}
            if(!tmp.volume)tmp.volume = 1
            if(!tmp.weight)tmp.weight = 1
            if(!tmp.quantity)tmp.quantity = 1
            if(!tmp.num)tmp.num = 1
            arr.push(tmp)
        })
        return arr
    }
  }
};
</script>
<style lang="scss" scoped>
.card-title{
    font-size: 18px;
    display: flex;
    .card-name{
        flex: 1;
    }
}
.form-section{
    .contact{
        display: flex;
        align-items: center;
        img.phonebook{
            width: 30px;
            height: 30px;
            margin-left: 10px;
            cursor: pointer;
        }
    }
    
}
::v-deep .product-list .el-form-item__error{
    position: static;
}
</style>