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

    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-card>
            <div slot="header" class="card-title">新建报价单</div>
            <el-form-item label="所属人">
                <el-radio-group v-model="form.relation">
                  <el-radio label="1">发件人</el-radio>
                  <el-radio label="2">收件人</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="订单类型" style="margin-bottom: 0">
                <el-checkbox-group v-model="form.type">
                    <el-checkbox label="1">集运服务</el-checkbox>
                    <!-- <el-checkbox label="2">海外仓</el-checkbox> -->
                </el-checkbox-group>
            </el-form-item>

            <el-descriptions :column="3" border>
                <el-descriptions-item label="*发货人" :labelStyle="labelStyle" >
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consignorId" required error="发货人不能为空">
                        <customer-contact-selector v-model="form.consignorId" @change="consignor = $event" />
                    </el-form-item>
                </el-descriptions-item>
                <!-- <el-descriptions-item label="发货人" :labelStyle="labelStyle">
                    {{consignor.contactsName || '无'}}
                </el-descriptions-item> -->
                <el-descriptions-item label="手机号" :labelStyle="labelStyle">
                    {{consignor.areaCode}} {{consignor.phoneNew || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="发货人公司名称" :labelStyle="labelStyle">
                    {{consignor.company || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="Email" :labelStyle="labelStyle">
                    {{consignor.email || '无'}}
                </el-descriptions-item><!-- 
                <el-descriptions-item label="社交软件">
                    {{consignor.social}} {{consignor.socialNumber}}
                </el-descriptions-item>
                <el-descriptions-item label="联系地址">
                    {{consignor.address || '无'}}
                </el-descriptions-item> -->
            </el-descriptions>
            <el-descriptions :column="3" border>
                <el-descriptions-item label="*收货人" :labelStyle="labelStyle">
                    
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consigneeId" required error="收货人不能为空">
                        <customer-contact-selector v-model="form.consigneeId" @change="consignee = $event" />
                    </el-form-item>
                </el-descriptions-item>
                <!-- <el-descriptions-item label="收货人" :labelStyle="labelStyle">
                    {{consignee.contactsName || '无'}}
                </el-descriptions-item> -->
                <el-descriptions-item label="手机号" :labelStyle="labelStyle">
                    {{consignee.areaCode}} {{consignee.phoneNew}}
                </el-descriptions-item>
                <el-descriptions-item label="发货人公司名称" :labelStyle="labelStyle">
                    {{consignee.company || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="Email" :labelStyle="labelStyle">
                    {{consignee.email || '无'}}
                </el-descriptions-item><!-- 
                <el-descriptions-item label="社交软件">
                    {{consignee.social}} {{consignee.socialNumber}}
                </el-descriptions-item>
                <el-descriptions-item label="联系地址">
                    {{consignee.address || '无'}} // TODO
                </el-descriptions-item> -->
            </el-descriptions>
            
            <el-descriptions :column="2" border>
                <el-descriptions-item label="*运输方式" :labelStyle="labelStyle">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="transportId" required error="请选择运输方式">
                        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="form.transportId" @input="calculationPrice" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="出货渠道"  v-if="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass == 'channel'" :labelStyle="labelStyle">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="channelId" :required="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass == 'channel'" error="请选择出货渠道">
                        <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>
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="*始发城市" :labelStyle="labelStyle">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="departureId" required error="始发地必选">
                        <el-select v-model="form.departureId" placeholder="请选择始发地">
                            <el-option v-for="item in expoerCityList" :label="item.titleZh" :value="item.id" :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="*目的城市" :labelStyle="labelStyle">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="objectiveId" required error="目的城市必选">
                        <el-select v-model="form.objectiveId" placeholder="请选择始发地">
                        <el-option v-for="item in importCityList" :label="item.titleZh" :value="item.id" :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="*请选择线路" :span="2" :labelStyle="labelStyle">
                    <el-row :gutter="10">
                      <el-col :span="12">
                            <el-input :value="getRouterNameById(form.lineId)" readonly placeholder="请在右侧选择线路"></el-input>
                      </el-col>
                      <el-col :span="12">
                        <select size="5" v-model="form.lineId" style="min-width: 300px" @change="calculationPrice">
                            <template v-for="item in routerList">
                                <option :value="item.id" :key="item.id">{{item.startTitleZh}} >> {{item.destTitleZh}}</option>
                            </template>
                        </select>
                      </el-col>
                    </el-row>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>
        <el-card  class="mt-10">
            <div slot="header" class="card-title">
                <div class="card-name">商品信息</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="序号" width="60px" fixed>
                <template slot-scope="scope">
                    {{scope.$index + 1}}
                </template>
              </el-table-column>
              <el-table-column label="中文名" width="160px">
                <template slot-scope="{row}">
                    <product-selector v-model="row.prodId" @change="onProductChange(row, $event)" />
                </template>
              </el-table-column>
              <el-table-column label="英文名" width="160px">
                <template slot-scope="{row}">
                    <product-selector v-model="row.prodId" @change="onProductChange(row, $event)" />
                </template>
              </el-table-column>
              <el-table-column label="商品类型" width="160px">
                <template slot-scope="{row}">
                    <selector disabled v-model="row.goodsType" :options="productAttrList" label-field="attrName" value-field="id" @input="calculationPrice"></selector>
                </template>
              </el-table-column>

              <el-table-column label="品牌" 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="件数" width="90px">
                <template slot-scope="{row}">
                    <el-input v-model.number="row.num" @input="calculationPrice" />
                </template>
              </el-table-column>
              <el-table-column label="包装单位">
                <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="数量(个)">
                <template slot-scope="{row}">
                    <el-input v-model.number="row.quantity" @input="calculationPrice" />
                </template>
              </el-table-column>
              <el-table-column label="箱规(m)" width="120px">
                <template slot-scope="{row}">
                    <el-input v-model="row.boxGauge" @input="calcVolume(row);calculationPrice()" />
                </template>
              </el-table-column>
              <el-table-column label="总体积(m³)" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.volume" @input="calculationPrice"/>
                </template>
              </el-table-column>
              <el-table-column label="总重量(kg)" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.weight" @input="calculationPrice" />
                </template>
              </el-table-column>
              <el-table-column label="货值(RMB)" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.worth" />
                </template>
              </el-table-column>
              <el-table-column label="商品特性" 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="运输方式" width="150px">
                <template slot-scope="{row}">
                    <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="row.transportId"
                    @input="onTransportChange(row,$event)" formatter="number" />
                </template>
              </el-table-column>
              <el-table-column label="出货渠道" width="150px">
                <template slot-scope="{row}">
                    <selector
                    :disabled="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, row.transportId).cssClass != 'channel'"
                    v-model="row.channelId"
                    :options="channelList"
                    value-field="channelId"
                    label-field="nameZh"
                    @input="onChannelChange(row)"
                    ></selector>
                </template>
              </el-table-column>
              <el-table-column label="线路" width="200px">
                <template slot-scope="{row}">
                    <selector
                    v-model="row.lineId"
                    :options="routerList"
                    @input="onLineChange(row)"
                    clearable
                    :label-field="(item, index) => item.startTitleZh + ' >> ' + item.destTitleZh" value-field="id"></selector>
                </template>
              </el-table-column> -->
              <el-table-column label="运费" width="200px">
                <template slot-scope="{row}">
                    <template v-if="row.fee && row.fee.charging == 1">
                        <template v-if="!row.fee.freight">未报价</template>
                        <template v-else>
                            全包价：{{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">未报价</template>
                    <template v-else-if="row.fee">
                        <div>
                            运费：{{row.fee.freight}} {{currentcyMap[row.fee.freightCurrency]}} / {{unitMap[row.fee.freightVolume]}}
                        </div>
                        <div>
                            清关费：{{row.fee.clearanceFee}} {{currentcyMap[row.fee.clearanceFeeCurrency]}} / {{unitMap[row.fee.clearanceFeeVolume]}}
                        </div>
                    </template>
                </template>
              </el-table-column>
              <el-table-column label="是否预付">
                <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="商品链接" 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 ? '编辑商品链接' : '添加商品链接'}}
                    </el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180px" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="danger" @click="delProduct(scope.$index)">删除</el-button>
                    <el-button size="mini" type="primary" @click="showMorePrice($index)">更多报价</el-button>
                    <!-- <el-button size="mini" type="primary" @click="getProductFee(scope.row)">计算</el-button> -->
                </template>
              </el-table-column>
            </el-table>
            <!-- 
        </el-card>
        <el-card  class="mt-10"> -->
            <div class="card-title" style="padding:20px 0;">费用小计</div>
            <el-descriptions :column="4" border>
                <el-descriptions-item label="总件数">
                    {{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.totalWorth || 0}}人民币
                </el-descriptions-item>
                <el-descriptions-item label="保价费">
                    {{fee.insuranceFee || 0}}人民币
                </el-descriptions-item>
                <!-- <el-descriptions-item label="总运费">
                    <div>{{fee.seaNGN || 0}}泰拉</div>
                    <div>{{fee.seaRMB || 0}}人民币</div>
                    <div>{{fee.seaUSD || 0}}美元</div>
                </el-descriptions-item>
                <el-descriptions-item label="总清关费">
                    <div>{{fee.clearanceNGN || 0}}泰拉</div>
                    <div>{{fee.clearanceRMB || 0}}人民币</div>
                    <div>{{fee.clearanceUSD || 0}}美元</div>
                </el-descriptions-item>
                <el-descriptions-item label="预计费用">
                    <div>{{fee.seaNGN + fee.clearanceNGN}}泰拉</div>
                    <div>{{fee.seaRMB + fee.clearanceRMB + fee.insuranceFee	}}人民币</div>
                    <div>{{fee.seaUSD + fee.clearanceUSD}}美元</div>
                </el-descriptions-item> -->
            </el-descriptions>
        </el-card>

        <el-card class="mt-10">
            <div class="card-title" slot="header">预计费用</div>
            
            <el-descriptions :column="5" border>
                <el-descriptions-item label="保价费">
                    {{fee.insuranceFee || 0}} 人民币
                </el-descriptions-item>
                <el-descriptions-item label="总运费">
                    <div>{{fee.seaNGN || 0}}奈拉</div>
                    <div>{{fee.seaRMB || 0}}人民币</div>
                    <div>{{fee.seaUSD || 0}}美元</div>
                </el-descriptions-item>
                <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
                <el-descriptions-item label="总清关费">
                    <div>{{fee.clearanceNGN || 0}}奈拉</div>
                    <div>{{fee.clearanceRMB || 0}}人民币</div>
                    <div>{{fee.clearanceUSD || 0}}美元</div>
                </el-descriptions-item>
                <el-descriptions-item label="其他费用">
                    <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="原价" :span="2">
                    <!--TODO 缺少字段-->
                    <div>{{fee.clearanceNGN || 0}}奈拉</div>
                    <div>{{fee.clearanceRMB || 0}}人民币</div>
                    <div>{{fee.clearanceUSD || 0}}美元</div>
                </el-descriptions-item>
            </el-descriptions>

            <div class="card-title" style="padding:20px 0;">优惠信息</div>
                <div v-for="(item, index) in couponList" :key="index" style="display:flex;align-items:center">
                <div class="w-150">
                    {{index+1}}.
                    {{productNames[item.prodId] || '未知'}}
                </div>
              <div class="w-100">
                <dict-tag :type="DICT_TYPE.ECW_COUPON_TYPE" :value="item.type" />
              </div>
              <div style="display:flex; align-items:center">
                <el-select placeholder="请选择优惠" v-model="item.selectedIndex" :data-type="item.value" clearable class="w-300">
                    <template v-for="(coupon, couponIndex) in item.options">
                        <el-option :key="coupon.couponId" :label="coupon.titleZh" :value="couponIndex"></el-option>
                    </template>
                </el-select>
                <template v-if="item.selectedIndex !== null">
                    <div class="w-100 ml-20">
                        -{{item.options[item.selectedIndex].reduceAmount}} 
                        {{currentcyMap[item.options[item.selectedIndex].reduceCurrencyId]}}
                    </div>
                    <div class="ml-20">有效期：{{item.options[item.selectedIndex].endTime || '永久有效'}}</div>
                </template>
              </div>
            </div>
            <el-descriptions :column="1" class="mt-20">
                <el-descriptions-item label="优惠合计">
                    <div v-for="(discount, discountIndex) in discountArr" :key="discountIndex">
                        {{discount.reduceAmount}} {{currentcyMap[discount.reduceCurrencyId]}}
                    </div>
                    
                </el-descriptions-item>
                <el-descriptions-item label="预计费用">
                    // TODO
                </el-descriptions-item>
            </el-descriptions>
        </el-card>
        
        <el-card class="mt-10">
            <div class="card-title" slot="header">通用</div>
            
            <el-descriptions :column="2" border>
                <el-descriptions-item label="唛头">
                    <el-input v-model="form.marks" placeholder=""></el-input>
                </el-descriptions-item>
                <el-descriptions-item label="报关方式">
                    <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="form.customsType" form-type="radio" defaultable />
                </el-descriptions-item>
                <el-descriptions-item label="预计结束时间">
                    <el-date-picker v-model="form.stopTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-descriptions-item>
                <el-descriptions-item label="是否控货">
                    <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" v-model="form.control" form-type="radio" defaultable />
                </el-descriptions-item>
                <el-descriptions-item label="竞争对手">
                    <el-input v-model="form.competitor" placeholder=""></el-input>
                </el-descriptions-item>
                <el-descriptions-item label="重要程度">
                    <el-rate v-model="form.importance"></el-rate>
                </el-descriptions-item>
                <el-descriptions-item label="价格有效时间">
                    <el-date-picker v-model="form.startTime" placeholder="" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                    -
                    <el-date-picker v-model="form.endTime" placeholder="" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-descriptions-item>
                <el-descriptions-item label="交货方式">
                    <!--
                        接口要求数据为整数，所以增加trade_type类型的字典，用1234代码以下不同类型
                        FOB(离岸价)，CIF(到岸价)，CNF(成本加运费)，EXW(出厂价)
                    -->
                    <dict-selector :type="DICT_TYPE.ECW_TRADE_TYPE" fomtter="number" v-model="form.tradeType" />
                    <el-input v-model="form.tradeAdress" placeholder=""></el-input>
                </el-descriptions-item>
                <!-- <el-descriptions-item label="总运费" :span="2">
                    
                </el-descriptions-item>
                <el-descriptions-item label="总清关费" :span="2">
                    
                </el-descriptions-item>
                <el-descriptions-item label="总价格" :span="2">
                    
                </el-descriptions-item> -->
                <!-- <el-descriptions-item label="佣金类型" :span="2">
                    <dict-selector :type="DICT_TYPE.COMMISSION_TYPE" form-type="radio" fomtter="number" v-model="form.commissionType" defaultable />
                </el-descriptions-item> -->
                <el-descriptions-item label="备注" :span="2">
                    <el-input v-model="form.remarks" type="textarea" placeholder=""></el-input>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <el-card  class="mt-10" v-if="transport">
            <div class="card-title" slot="header">{{transport.label}}</div>
            <el-form-item label="快递单号">
                <el-input v-model="form.number" placeholder="请输入购买商品的快递单号"></el-input>
            </el-form-item>
            <el-form-item label="是否双清" 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="航空公司" v-if="[3,4].indexOf(+form.transportId) > -1">
                <!--待查询备选数据-->
                <el-select placeholder="" v-model="form.airlineCompany">
                </el-select>
            </el-form-item>
            
            <el-form-item label="船公司" v-if="[2].indexOf(+form.transportId) > -1">
                <el-select placeholder="" v-model="form.shippingCompany">
                </el-select>
            </el-form-item>

            <el-form-item label="清关证书" 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="清关证书备注" v-if="[2,3,4].indexOf(+form.transportId) > -1">
                <el-input v-model="form.remarks" ></el-input>
            </el-form-item>
            <el-form-item label="是否拆包" 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="单票立刻转运" 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">注：若只有一件，货到仓库立即发，选“是”，多件需仓库集运待发，选“否”</span>
            </el-form-item>

            <el-form-item label="特殊要求" >
                <dict-selector v-model="form.packageType" form-type="checkbox" :type="DICT_TYPE.ORDER_SPECIAL_NEEDS" multiple />
            </el-form-item>
            <el-form-item label="特殊要求备注">
                <el-input v-model="form.packageRemarks"  ></el-input>
            </el-form-item>
        </el-card>
        

        <el-form-item label="">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="$router.back()">取 消</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
import { createOffer, updateOffer, getOffer, getProductFeeList, getProductFee } 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 CustomerContactSelector from '@/components/CustomerContactSelector'
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 {getCustomerAvailableCouponList} from '@/api/ecw/coupon'
import {arrryToKeyedObjectBy} from '@/utils/index'

export default {
  name: "OfferEdit",
  components: {
    ProductSelector, Selector, CustomerContactSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      /* dateRangeStopTime: [],
      dateRangeStartTime: [],
      dateRangeEndTime: [],
      dateRangeCreateTime: [], */
      productList:[], // 商品信息
      productAttrList:[],  // 商品属性
      channelList: [], // 出货取到
      routerList: [],
      tradeCityList: [],
      consignor: {}, // 发货人
      consignee:{}, // 收货人
      transportList: [],
      currencyList:[],
      unitList:[],
      couponList: [{"selectedIndex":null,"options":[{"couponId":74,"titleZh":"2-1,5-2","titleEn":"2-1,5-2","type":2,"cashCondition":0,"reduceAmount":3,"reduceCurrencyId":1,"startTime":"2022-01-01 00:00:00","afterReceiveDays":0,"costType":2,"discountDetailed":"[{\"type\": 1, \"fullAmount\": 2, \"reduceAmount\": 1, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}, {\"type\": 1, \"fullAmount\": 5, \"reduceAmount\": 2, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}, {\"type\": 2, \"fullAmount\": 2, \"reduceAmount\": 1, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}, {\"type\": 2, \"fullAmount\": 6, \"reduceAmount\": 3, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}]","discountDetailedVOList":[{"type":1,"fullAmount":2,"fullCurrencyId":1,"reduceAmount":1,"reduceCurrencyId":1},{"type":1,"fullAmount":5,"fullCurrencyId":1,"reduceAmount":2,"reduceCurrencyId":1},{"type":2,"fullAmount":2,"fullCurrencyId":1,"reduceAmount":1,"reduceCurrencyId":1},{"type":2,"fullAmount":6,"fullCurrencyId":1,"reduceAmount":3,"reduceCurrencyId":1}],"isSimilarSuperposition":false,"couponIds":"","suitableUserType":0,"suitableLineType":0,"suitableProdType":0,"limitNum":1,"overdueStatus":true,"putonStatus":1,"getWay":1,"orderAttr":"1,2,3","isSiteContent":false,"brand":"0,1","isCargoControl":"1,0","documentDeclaration":"1,2,3","status":1,"prodList":[],"isDefault":false},{"couponId":73,"titleZh":"3-2,2-1","titleEn":"3-2,2-1","type":2,"cashCondition":0,"reduceAmount":2,"reduceCurrencyId":1,"startTime":"2022-01-01 00:00:00","afterReceiveDays":0,"costType":1,"discountDetailed":"[{\"type\": 1, \"fullAmount\": 2, \"reduceAmount\": 1, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}, {\"type\": 1, \"fullAmount\": 3, \"reduceAmount\": 2, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}, {\"type\": 2, \"fullAmount\": 2, \"reduceAmount\": 1, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}, {\"type\": 2, \"fullAmount\": 3, \"reduceAmount\": 2, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}]","discountDetailedVOList":[{"type":1,"fullAmount":2,"fullCurrencyId":1,"reduceAmount":1,"reduceCurrencyId":1},{"type":1,"fullAmount":3,"fullCurrencyId":1,"reduceAmount":2,"reduceCurrencyId":1},{"type":2,"fullAmount":2,"fullCurrencyId":1,"reduceAmount":1,"reduceCurrencyId":1},{"type":2,"fullAmount":3,"fullCurrencyId":1,"reduceAmount":2,"reduceCurrencyId":1}],"isSimilarSuperposition":false,"couponIds":"","suitableUserType":0,"suitableLineType":0,"suitableProdType":0,"limitNum":1,"overdueStatus":true,"putonStatus":1,"getWay":1,"orderAttr":"1,2,3","isSiteContent":false,"brand":"0,1","isCargoControl":"0,1","documentDeclaration":"1,2,3","status":1,"prodList":[],"isDefault":false},{"couponId":71,"titleZh":"金额满2减1","titleEn":"金额满2减1","type":2,"cashCondition":0,"reduceAmount":5,"reduceCurrencyId":1,"startTime":"2022-01-01 00:00:00","afterReceiveDays":0,"costType":1,"discountDetailed":"[{\"type\": 1, \"fullAmount\": 2, \"reduceAmount\": 1, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}, {\"type\": 1, \"fullAmount\": 10, \"reduceAmount\": 5, \"fullCurrencyId\": 1, \"reduceCurrencyId\": 1}]","discountDetailedVOList":[{"type":1,"fullAmount":2,"fullCurrencyId":1,"reduceAmount":1,"reduceCurrencyId":1},{"type":1,"fullAmount":10,"fullCurrencyId":1,"reduceAmount":5,"reduceCurrencyId":1}],"isSimilarSuperposition":true,"couponIds":"","suitableUserType":0,"suitableLineType":0,"suitableProdType":0,"limitNum":1,"overdueStatus":true,"putonStatus":1,"getWay":1,"orderAttr":"1,2,3","isSiteContent":false,"brand":"0,1","isCargoControl":"1,0","documentDeclaration":"1,2,3","status":1,"prodList":[],"isDefault":false}],"prodId":22,"type":2}],
      fee: {}, // 费用
      // 表单参数
      form: {
        sendstatus:0,
        type: [],
        isCargoControl: false,
      },
      // 表单校验
      rules: {
        /* number: [{ required: true, message: "报价单号不能为空", trigger: "blur" }],
        consignorId: [{ required: true, message: "客户id，发货人不能为空", trigger: "blur" }],
        consigneeId: [{ required: true, message: "收货人id不能为空", trigger: "blur" }],
        sendstatus: [{ required: true, message: "站内信状态，0未发送，1已发送不能为空", trigger: "blur" }], */
      },
      labelStyle: 'width:120px',
      productNames: {} // 品名id和名称对应关系
    };
  },
  computed:{
    expoerCityList(){
        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
    },
    // 总有优惠金额
    discount(){
        let discount = {
            // curreny: amount
        }
        this.couponList.forEach(item => {
            if(item.selectedIndex !== null){
                let selected = item.options[item.selectedIndex]
                if(!discount[selected.reduceCurrencyId]) discount[selected.reduceCurrencyId] = 0
                discount[selected.reduceCurrencyId] += selected.reduceAmount
            }
        })
        return discount
    },
    discountArr(){
        let discount = []
        for(let currency in this.discount){
            discount.push({
                reduceAmount: this.discount[currency],
                reduceCurrencyId: currency
            })
        }
        return discount
    }
    /* 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)
        this.$set(this.form, 'departureId', router.startCityId)
        this.$set(this.form, 'objectiveId', router.destCityId)
        // TODO 还需要回填渠道信息，暂时缺少渠道ID
    },
    fee(){
        this.getCoupons()
    }
  },
  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 => {
            this.$set(this, 'form', res.data)
            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) : []
                    })
                })
            }
            console.log('res.data.transportRespVOList', res.data.transportRespVOList)
            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: {
    /* onTransportChange(row, val){
        this.getProductFee(row)
        if(this.getDictData(this.DICT_TYPE.ECW_TRANSPORT_TYPE, val).cssClass != 'channel') row.channelId = null
        this.updateEnabledTransports()
    }, */
    onProductChange(row, product){
        row.goodsType = product.typeId;
        // 保存商品id和品名，用于优惠信息显示
        this.$set(this.productNames, product.id, product.titleZh)
        this.calculationPrice()
    },
    onLineChange(row){
        this.calculationPrice()
        // this.updateEnabledTransports()
    },
    onChannelChange(row){
        this.calculationPrice()
    },
    onProductAttrChange(row, attr){
        this.calculationPrice()
    },
    // 更新运输方式
    /* updateEnabledTransports(){
        
        let enabled = {}
        this.productList.forEach(prod => {
            if(prod.transportId){
                if(!enabled[prod.transportId]){
                    enabled[prod.transportId] = {
                        // transportId: prod.transportId,
                        lineIdSet: new Set(),
                        channelIdSet: new Set(),
                        routers:[]
                    }
                }
                if(prod.lineId){
                    enabled[prod.transportId].lineIdSet.add(prod.lineId)
                }
                if(prod.channelId){
                    enabled[prod.transportId].channelIdSet.add(prod.channelId)
                }
                if(prod.lineId && enabled[prod.transportId].routers.findIndex(item => { item.lineId == prod.lineId && item.channelId == prod.channelId }) < 0){
                    enabled[prod.transportId].routers.push({
                        lineId: prod.lineId,
                        channelId: prod.channelId
                    })
                }
            }
        })
        console.log(JSON.stringify(enabled))
        let enabledTransportIds = Object.keys(enabled).map(item => +item)
        this.transportList.forEach(transport => {
            this.$set(transport, '_enabled', enabledTransportIds.indexOf(transport.transportId) > -1 && enabled[transport.transportId].routers.length)
            if(transport._enabled){
                Object.assign(transport, enabled[transport.transportId])
            }
        })
    }, */
    addProduct(data){
        if(!data && !this.form.lineId){
            return this.$message.error('请先选择路线')
        }
        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('确定删除此条内容么？')
            .then(res => {
                this.productList.splice(index, 1)
            })
    },
    getCoupons(){
        console.log('getCoupons')
        // if(!this.form.consigneeContactsId || !this.form.consignorContactsId) return false
        let data = Object.assign({}, this.form, {
            prodConditionParamList: this.productList,
            consigneeCustomerContactsId: this.form.consigneeId,
            consignorCustomerContactsId: this.form.consignorId
        })
        getCustomerAvailableCouponList(data)
            .then(res => {
                // 对优惠信息按照商品 + 类型 分组展示
                let list = {}
                res.data.couponAvailableGroupDtoList.forEach(item => {
                    item.couponAvailableDtoList.forEach(coupon => {
                        let key = item.prodId + '_' + coupon.type
                        if(!list[key]){
                            list[key] = {
                                selectedIndex: null,
                                options: [],
                                prodId: item.prodId,
                                type: coupon.type
                            }
                        }
                        list[key].options.push(coupon)
                    })
                })
                this.couponList = Object.values(list)
            })
    },
    // 显示更多报价
    showMorePrice(index){
        console.log('显示更多报价', index)
    },
    /** 提交按钮 */
    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.$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.$router.replace('index')
        });
      });
    },
    setLink(row){
        this.$prompt('请输入商品链接', {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.productList.map((item, index) => {
                this.$set(item, 'fee', res.data.prodCostDtoList[index])
            })
        }).finally(() => {
            this.calculating = false
        })
    },
  }
};
</script>
<style lang="scss" scoped>
.card-title{
    font-size: 18px;
    display: flex;
    .card-name{
        flex: 1;
    }
}
.mt-10{
    margin-top: 10px;
}
</style>