<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-descriptions :column="3" border>
                <el-descriptions-item label="*发货人" >
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consignorContactsId" required error="发货人不能为空">
                        <customer-contact-selector v-model="form.consignorContactsId" @change="consignorContact = $event" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="电话">
                    {{consignorContact.phoneNew || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="发货人公司">
                    {{consignorContact.customerName || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="Email">
                    {{consignorContact.email || '无'}}
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions :column="3" border>
                <el-descriptions-item label="*收货人" >
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consigneeContactsId" required error="收货人不能为空">
                        <customer-contact-selector v-model="form.consigneeContactsId" @change="consigneeContact = $event" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="电话">
                    {{consigneeContact.phoneNew || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="收货人公司">
                    {{consigneeContact.customerName || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="Email">
                    {{consigneeContact.email || '无'}}
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions :column="3" border>
                <el-descriptions-item label="*运输方式">
                    <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" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="出货渠道">
                    <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"
                        ></selector>
                    </el-form-item>
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="*始发城市">
                    <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="*目的城市">
                    <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">
                    <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">
                            <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" @click="addProduct(null)">添加货物</el-button>
                <el-button type="primary" size="mini">批量添加货物</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)" :disabled="!form.lineId" />
                </template>
              </el-table-column>
              <el-table-column label="英文品名" width="160px">
                <template slot-scope="{row}">
                    <product-selector v-model="row.prodId" @change="onProductChange(row, $event)" :disabled="!form.lineId" />
                </template>
              </el-table-column>
              <!-- <el-table-column label="商品类型" width="160px">
                <template slot-scope="{row}">
                    <selector disabled v-model="row.goodsType" :options="productAttrList" label-field="attrName" value-field="id"></selector>
                </template>
              </el-table-column> -->

              <el-table-column label="品牌" width="100px">
                <template slot-scope="{row}">
                    <dict-selector v-model="row.brand" :type="DICT_TYPE.ECW_IS_BRAND" defaultable @input="calculationPrice(row)" :disabled="!form.lineId" />
                </template>
              </el-table-column>
              <el-table-column label="件数" width="90px">
                <template slot-scope="{row}">
                    <el-input v-model.number="row.num" :disabled="!form.lineId" />
                </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 :disabled="!form.lineId" />
                </template>
              </el-table-column>
              <el-table-column label="数量">
                <template slot-scope="{row}">
                    <el-input v-model="row.quantity" type="number" :disabled="!form.lineId" />
                </template>
              </el-table-column>
              <!-- <el-table-column label="箱规(m)" width="120px">
                <template slot-scope="{row}">
                    <el-input v-model="row.boxGauge" @input="calcVolume(row)" />
                </template>
              </el-table-column> -->
              <el-table-column label="体积(m³)" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.volume" :disabled="!form.lineId" />
                </template>
              </el-table-column>
              <el-table-column label="重量(kg)" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.weight" :disabled="!form.lineId" />
                </template>
              </el-table-column>
              <el-table-column label="货值(RMB)" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.worth" :disabled="!form.lineId" />
                </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); calculationPrice(row)" :disabled="!form.lineId">
                      <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="200px">
                <template slot-scope="{row}">
                    <template v-if="row.fee && row.fee.charging == 1">
                        全包价：{{row.fee.freight}} {{currentcyMap[row.fee.freightCurrency]}} / {{unitMap[row.fee.freightVolume]}}
                    </template>
                    <template v-else-if="row.fee">
                        <div>
                            运费：{{row.fee.freight}} {{currentcyMap[row.fee.freightCurrency]}} / {{unitMap[row.fee.freightVolume]}}
                        </div>
                        <div>
                            清关费：{{row.fee.clearanceFee}} {{currentcyMap[row.fee.clearanceFeeCurrency]}} / {{unitMap[row.fee.clearanceFeeVolume]}}
                        </div>
                    </template>
                </template>
              </el-table-column>
              <el-table-column label="是否预付">
                <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="80px" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="danger" @click="delProduct(scope.$index)">删除</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="总货值(RMB)">
                    {{sum.totalWorth || 0}}元
                </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="" style="width:100px"></el-input>
                    <selector v-model="form.otherFeeCurrencyId" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
                </el-descriptions-item>
                
                <el-descriptions-item label="原价" :span="2">
                    <!--TODO 缺少字段-->
                    <div>{{fee.clearanceNGN || 0}}奈拉</div>
                    <div>{{fee.clearanceRMB || 0}}人民币</div>
                    <div>{{fee.clearanceUSD || 0}}美元</div>
                </el-descriptions-item>
            </el-descriptions>

            <div class="card-title" style="padding:20px 0;">优惠信息</div>
            <el-row v-for="(item, index) in couponTypeList" :key="item.value" :gutter="10">
              <el-col :span="2">{{index+1}}.{{item.label}}</el-col>
              <el-col :span="4">
                <el-select placeholder="请选择优惠" v-model="selectedCoupons[item.value]" :data-type="item.value" clearable>
                    <template v-for="(coupon, index) in couponList">
                        <el-option v-if="coupon.type == +item.value" :key="coupon.couponId + '_' + index" :label="coupon.titleZh" :value="coupon.couponId"></el-option>
                    </template>
                </el-select>
              </el-col>
              <el-col :span="2" v-if="getCoupon(selectedCoupons[item.value])">
                -{{getCoupon(selectedCoupons[item.value]).reduceAmount}} 
                {{currentcyMap[getCoupon(selectedCoupons[item.value]).reduceCurrencyId]}}
              </el-col>
              <el-col :span="5" v-if="getCoupon(selectedCoupons[item.value])">有效期：{{getCoupon(selectedCoupons[item.value]).endTime || '永久有效'}}</el-col>
            </el-row>
            <el-descriptions :column="1" border>
                <el-descriptions-item label="优惠合计">
                    {{discount}}美元
                </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.INFRA_BOOLEAN_STRING" formatter="bool" v-model="form.control" form-type="radio" />
                </el-descriptions-item>
                <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
                <el-descriptions-item label="是否代收货款">
                    <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" v-model="form.isCollection" form-type="radio" />
                </el-descriptions-item>
                <el-descriptions-item label="代收货款金额">
                    <el-input v-model="form.collectionProxy" placeholder="" style="width:200px"></el-input>
                    <selector v-model="form.collectionProxyCurrency" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
                </el-descriptions-item>
                
                <el-descriptions-item label="单证报关" :span="2">
                    <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="form.customsType" form-type="radio" />
                </el-descriptions-item>
                <el-descriptions-item label="出单方式">
                    <dict-selector :type="DICT_TYPE.ECW_SUING_METHOD" v-model="form.issuingMethod" form-type="radio" />
                </el-descriptions-item>
                <el-descriptions-item label="送货日期">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="deliveryDate" required error="送货日期不能为空">
                        <el-date-picker v-model="form.deliveryDate" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                    </el-form-item>
                    
                </el-descriptions-item>
                
                <el-descriptions-item label="入仓类型">
                    <dict-selector :type="DICT_TYPE.ECW_WAREHOUSING_TYPE" v-model="form.warehouseType" />
                </el-descriptions-item>
                <el-descriptions-item label="收货方式">
                    <dict-selector :type="DICT_TYPE.ECW_HARVEST_METHOD" v-model="form.harvestMethod" />
                </el-descriptions-item>
                <el-descriptions-item label="收货地区" :span="2">
                    <area-selector
                    @countryChange="onAreaChange('country', $event)"
                    @provinceChange="onAreaChange('province', $event)"
                    @cityChange="onAreaChange('city', $event)"
                    ></area-selector>
                </el-descriptions-item>
                <el-descriptions-item label="收货详细地址" :span="2">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consigneeAddress" required error="收货详细地址不能为空">
                        <el-input v-model="form.consigneeAddress" placeholder=""></el-input>
                    </el-form-item>
                    
                </el-descriptions-item>
                
                <el-descriptions-item label="付款人" :span="2">
                     <dict-selector :type="DICT_TYPE.DRAWEE" v-model="form.drawee" defaultable form-type="radio" />
                </el-descriptions-item>
                <el-descriptions-item v-if="form.drawee==3" label="费用类型" :span="2">
                    <template v-for="(item,index) in customDraweeList" v-key="index">
                      <el-form-item :label="item.label" :key="index" >
                        <dict-selector :type="DICT_TYPE.DRAWEE" :filter="(e) => e.value == '1' || e.value == '2'" v-model="item.value" form-type="radio" />
                      </el-form-item>
                    </template>
                </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="" style="margin: 30px 0">
            <el-button type="primary" @click="submitForm(0)">保 存</el-button> <!--草稿-->
            <el-button type="primary" @click="submitForm(2)">新建</el-button> <!--待入仓-->
            <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
import { createOrder, updateOrder, getOrder, getProductFeeList, getOrderDetail } from "@/api/ecw/order";
import ProductSelector from '@/components/ProductSelector'
import {getProductAttrList} from '@/api/ecw/productAttr'
import {getChannelList} from '@/api/ecw/channel'
import Selector from '@/components/Selector'
import CustomerContactSelector from '@/components/CustomerContactSelector'
import {openedRouterList as getOpenedRouterList} from '@/api/ecw/warehouse'
import {getTradeCityList} from '@/api/ecw/region'
import {getDictData, getDictDatas} from  '@/utils/dict'
import {getCurrencyList} from '@/api/ecw/currency'
import {getUnitList} from '@/api/ecw/unit'
import { getCustomer } from '@/api/ecw/customer';
import AreaSelector from '@/components/AreaSelector'
import {calculationPrice} from '@/api/ecw/product'
import {getCustomerAvailableCouponList} from '@/api/ecw/coupon'
export default {
  name: "OrderEdit",
  components: {
    ProductSelector, Selector, CustomerContactSelector, AreaSelector
  },
  data() {
    return {
      customDraweeList: [],
      // draweeList: [],
      // 遮罩层
      loading: true,
      productList:[], // 商品信息
      productAttrList:[],  // 商品属性
      channelList: [], // 出货取到
      routerList: [],
      tradeCityList: [],
      treeList: [],
      consignorContact: {}, // 发货联系人
      consigneeContact:{}, // 收货联系人
      /* consignee: null,
      consignor: null,  */
      transportList: [],
      currencyList:[],
      unitList:[],
      couponList: [],
      couponTypeList: [],
      selectedCoupons: {},
      fee: {}, // 费用
      // 表单参数
      form: {
        sendstatus:0
      },
      // 表单校验
      rules: {
        
      }
    };
  },
  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) || {}
    },
    getDictDatas(){
        return getDictDatas
    },
    
    // 根据线路id显示线路名称
    getRouterNameById(){
        return routerId => {
            let router = this.routerList.find(item => item.id == routerId)
            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)
    },
    // 根据id获取优惠券
    getCoupon(){
        return couponId => {
            if(!couponId) return null
            return this.couponList.find(item => item.couponId == couponId)
        }
    },
    currentcyMap(){
        let map = {}
        this.currencyList.forEach(item => {
            map[item.id] = item.titleZh
        })
        return map
    },
    unitMap(){
        let map = {}
        this.unitList.forEach(item => {
            map[item.id] = item.titleZh
        })
        return map
    },
    sum(){
        let sum = {
            totalNum: 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(){
        return 0
    }
  },
  watch:{
    // 始发地
    'form.departureId'(){
        this.getOpenedRouterList()
    },
    // 目的地
    'form.objectiveId'(){
        this.getOpenedRouterList()
    },
    'form.transportId'(){
        this.getOpenedRouterList
    },
    /* // 发货联系人发生变化获取发货客户
    consignorContact(){
        this.getConsignor()
    },
    // 收货联系人发生变化获取收货客户
    consigneeContact(){
        this.getConsignee()
    }, */
    productList:{
        deep: true,
        handler(){
            this.productList.map(item => {
                item.prodAttrIds = item.prodAttrArr.join(',')
            })
            this.calculationPrice()
        }
    },
    fee(){
        this.getCoupons()
    }
  },
  created() {
    this.couponTypeList = this.getDictDatas(this.DICT_TYPE.ECW_COUPON_TYPE)
    this.couponTypeList.forEach(item => {
        this.$set(this.selectedCoupons, item.value, null)
    })
    if(this.$route.query.id){
        getOrderDetail(this.$route.query.id).then(res => {
            this.form = res.data
            /* this.form.consignorContactsId = res.data.consignorVO.customerContactsId
            this.form.consigneeContactsId = res.data.consigneeVO.customerContactsId */
            this.form.deliveryDate = res.data.consigneeVO.deliveryDate
            this.form.orderItemVOList.forEach(item => {
                item.prodAttrArr = item.prodAttrIds.split(',').filter(item => item != '')
                this.addProduct(Object.assign({}, item))
            })
        })
    }else this.addProduct()

    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)
    this.getDictDatas(this.DICT_TYPE.ECW_CUSTOM_DRAWEE).forEach(item => {
        this.customDraweeList.push({
            label: item.label, // 显示文字
            name: item.value, // key值
            value: 2 // 1 发货人，2收货人，默认收货人，可修改
        })
    })
  },
  methods: {
    onProductChange(row, product){
        console.log(product)
        row.goodsType = product ? product.typeId : null
        row.prodAttrArr = !product ? [] : product.attrId.split(',').filter(item => item !== '').map(item => +item)
    },
    onAreaChange(type, val){
        this.$set(this.form, type, val)
    },
    /* // 获取发货人
    getConsignor(){
        if(!this.consignorContact){
            this.consignor = null
        }
        getCustomer(this.consignorContact.customerId).then(res => {
            this.consignor = res.data
        })
    },
    // 获取收货人
    getConsignee(){
        if(!this.consigneeContact){
            this.consignee = null
        }
        getCustomer(this.consigneeContact.customerId).then(res => {
            this.consignee = res.data
        })
    }, */
    onProductAttrChange(row, attr){
        console.log(attr)
        this.calculationPrice(row)
        /* // 需要强制刷新，否则勾选框不更新
        this.$forceUpdate() */
    },
    
    addProduct(data){
        this.productList.push(data || {prodAttrArr:[]})
    },
    // 计算商品运费
    calculationPrice(row){
        let calcable = true
        this.productList.forEach(item => {
            if(!item.weight || !item.prodId){
                calcable = false
            }
        })
        if(this.calculating || !calcable) return false
        this.calculating = true
        
        console.log('calculationPrice', row)
        /* if(!row.prodId || !this.form.transportId || !this.form.lineId)return false
        if(row.prodAttrArr){
            row.prodAttrIds = row.prodAttrArr.join(',')
        } */
        calculationPrice({
            lineId: this.form.lineId,
            transportId: this.form.transportId,
            channelId: this.form.channelId,
            prodConditionParamList: this.productList //[row]
        }).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
        })
    },
    // 获取路线
    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
        }
        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(){
        if(!this.form.consigneeContactsId || !this.form.consignorContactsId) return false
        let data = Object.assign({}, this.form, {
            prodConditionParamList: this.productList,
            consigneeCustomerContactsId: this.form.consigneeContactsId,
            consignorCustomerContactsId: this.form.consignorContactsId
        })
        getCustomerAvailableCouponList(data)
            .then(res => {
                this.couponList = res.data
            })
    },
    /** 提交按钮 */
    // type 在新建的时候表示状态，0草稿，2带入仓
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        
        this.productList.map(item => {
            item.prodAttrIds = item.prodAttrArr.join(',')
            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(',')
            }
        })
        let coupons = Object.values(this.selectedCoupons).filter(item => !!item)
        // 修改的提交
        if (this.form.orderNo != null) {
            let data = Object.assign({}, this.form, {
              customDraweeVOList: this.customDraweeList,
              // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
              orderItemVOList: this.productList,
              couponIds: coupons.join(",")
            })
            updateOrder(data).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.$router.back()
            });
            return;
        }
        let data = Object.assign({
            consigneeId: this.consigneeContact.customerId,
            consignorId: this.consignorContact.customerId,
            customerId : this.consignorContact.customerId,
            couponIds: coupons.join(","),
            status: type
        }, this.form, {
            customDraweeVOList: this.customDraweeList,
            // transportUpdateReqVOList: this.transportList.filter(item => item._enabled),
            orderItemVOList: this.productList
        })
        // 添加的提交
        createOrder(data).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.$router.replace('success?orderId=' + response.data)
        });
      });
    },
    
  }
};
</script>
<style lang="scss" scoped>
.card-title{
    font-size: 18px;
    display: flex;
    .card-name{
        flex: 1;
    }
}
.mt-10{
    margin-top: 10px;
}
</style>