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

    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-card>
            <div slot="header" class="card-title">{{ editMode  ? '编辑订单' : '新建订单'}}</div>
            <!--默认显示类型(selectedRouter==null)，如果选择路线后没开通则隐藏-->
            <el-form-item label="订单类型" style="margin-bottom: 0" v-if="!selectedRouter || routeOtherServices.indexOf('1') > -1 || routeOtherServices.indexOf('4') > -1">
                <el-checkbox-group v-model="form.type">
                    <el-checkbox label="1" v-if="!selectedRouter || routeOtherServices.indexOf('1') > -1">集运服务</el-checkbox>
                    <el-checkbox label="2" v-if="!selectedRouter || routeOtherServices.indexOf('2') > -1">海外仓</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            
            <el-descriptions :column="3" border v-if="form.type.indexOf('1') < 0">
                <el-descriptions-item label="*发货人" :labelStyle="labelStyle">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consignorContactsId">
                        <customer-contact-selector v-model="form.consignorContactsId" @change="consignorContact = $event" type="1" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="电话" :labelStyle="labelStyle">
                    {{consignorContact.areaCode}} {{consignorContact.phoneNew || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="发货人公司" :labelStyle="labelStyle">
                    {{consignorContact.company || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="Email" :labelStyle="labelStyle">
                    {{consignorContact.email || '无'}}
                </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="consigneeContactsId">
                        <customer-contact-selector v-model="form.consigneeContactsId" @change="consigneeContact = $event" type="2" />
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="电话"  :labelStyle="labelStyle">
                    {{consigneeContact.areaCode}} {{consigneeContact.phoneNew || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="收货人公司"  :labelStyle="labelStyle">
                    {{consigneeContact.company || '无'}}
                </el-descriptions-item>
                <el-descriptions-item label="Email"  :labelStyle="labelStyle">
                    {{consigneeContact.email || '无'}}
                </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="transportId">
                        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="form.transportId" />
                    </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"
                        ></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">
                        <el-select v-model="form.departureId" placeholder="请选择始发地">
                            <el-option v-for="item in exportCityList" :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">
                        <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-form-item label="" label-width="0" style="margin-bottom: 0" prop="lineId">
                                <el-input :value="selectedRouter ? selectedRouter.startTitleZh + ' > ' + selectedRouter.destTitleZh : ''" readonly placeholder="请在右侧选择线路"></el-input>
                            </el-form-item>
                      </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)" :disabled="!form.lineId">添加货物</el-button>
                <el-button type="primary" size="mini" @click="showBatchImportDialog=true" :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)" :disabled="!form.lineId || !productEditable" />
                </template>
              </el-table-column>
              <el-table-column label="英文品名" width="160px">
                <template slot-scope="{row}">
                    <product-selector lang="En" v-model="row.prodId" @change="onProductChange(row, $event)" :disabled="!form.lineId || !productEditable" />
                </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 || !productEditable" />
                </template>
              </el-table-column>
              <el-table-column label="件数" width="90px">
                <template slot-scope="{row}">
                    <el-input v-model.number="row.num" :disabled="!form.lineId || !productEditable" />
                </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 || !productEditable" />
                </template>
              </el-table-column>
              <el-table-column label="数量(个)" width="120px">
                <template slot-scope="{row}">
                    <el-input v-model="row.quantity" type="number" :disabled="!form.lineId || !productEditable" />
                </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 || !productEditable" />
                </template>
              </el-table-column>
              <el-table-column label="重量(kg)" width="100px">
                <template slot-scope="{row}">
                    <el-input v-model="row.weight" :disabled="!form.lineId || !productEditable" />
                </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 || !productEditable">
                      <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">
                        <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)" v-if="productEditable">
                        {{row.link ? '编辑商品链接' : '添加商品链接'}}
                    </el-button>
                </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="6" 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.totalQuatity || 0}}
                </el-descriptions-item>
                <el-descriptions-item label="总货值(RMB)">
                    {{sum.totalWorth || 0}}元
                </el-descriptions-item>
                <el-descriptions-item label="保价费">
                    {{fee.insuranceFee || 0}} 美元
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <el-card class="mt-10" v-if="0">
            <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-form-item label="" prop="marks" label-width="0" style="margin-bottom: 0" >
                        <el-input v-model="form.marks" placeholder=""></el-input>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="是否控货">
                    <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" v-model="form.isCargoControl" form-type="radio" />
                </el-descriptions-item>

                <!--代收货款，只有非控货订单、并且线路开通了代收货款后，才显示是否代收货款选项-->
                <el-descriptions-item label="是否代收货款" v-if="collectionProxy">
                    <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" formatter="bool" v-model="form.isCollection" form-type="radio" />
                </el-descriptions-item>
                <el-descriptions-item label="代收货款金额" v-if="collectionProxy">
                    <el-input v-model="form.collectionProxy" placeholder="" class="w-200 mr-10"></el-input>
                    <selector v-model="form.collectionProxyCurrency" :options="currencyList" label-field="titleZh" value-field="id" defaultable class="w-100" />
                </el-descriptions-item>
                
                <el-descriptions-item label="单证报关" :span="2">
                    <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="form.customsType" form-type="radio" defaultable />
                </el-descriptions-item>
                <el-descriptions-item label="出单方式">
                    <dict-selector :type="DICT_TYPE.ECW_SUING_METHOD" v-model="form.issuingMethod" form-type="radio" defaultable />
                </el-descriptions-item>
                <el-descriptions-item label="送货日期">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="deliveryDate">
                        <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" defaultable />
                </el-descriptions-item>
                <el-descriptions-item label="收货方式">
                    <dict-selector :type="DICT_TYPE.ECW_HARVEST_METHOD" v-model="form.harvestMethod" :filter="item => item.value == 1 || homeDeliveryService" defaultable />
                </el-descriptions-item>
                <el-descriptions-item label="收货地区" :span="2" v-if="homeDeliveryService">
                    <area-selector
                    :country="form.consigneeVO ? form.consigneeVO.country : undefined"
                    :province="form.consigneeVO ? form.consigneeVO.province : undefined"
                    :city="form.consigneeVO ? form.consigneeVO.city : undefined"
                    @countryChange="onAreaChange('country', $event)"
                    @provinceChange="onAreaChange('province', $event)"
                    @cityChange="onAreaChange('city', $event)"
                    ></area-selector>
                </el-descriptions-item>
                <el-descriptions-item label="收货详细地址" :span="2" v-if="homeDeliveryService">
                    <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="consigneeAddress">
                        <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-button type="primary" slot="append" @click="getOrderCourierNumber">生成单号</el-button>
                </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>

        <el-dialog title="批量导入" :visible.sync="showBatchImportDialog" width="1000px" :close-on-click-modal="false">
            <el-steps :active="importList.length > 0 ? 1 : 0" finish-status="success" class="w-500" style="margin: 20px auto">
                <el-step title="上传集装箱"></el-step>
                <el-step title="开始导入"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <div class="mt-20">
                <el-upload :http-request="upload" :show-file-list="false" action="" class="mr-10" style="display:inline-block; ">
                    <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
                <el-button type="info" @click="downloadTpl" size="small" :loading="exportLoading">装箱单模板</el-button>
            </div>
            <el-table :data="importList" class="mt-10" height="300">
              <el-table-column label="序号">
                <template slot-scope="scope">{{scope.$index + 1}}</template>
              </el-table-column>
              <el-table-column label="中文品名" prop="prodTitleZh"></el-table-column>
              <el-table-column label="英文品名" prop="prodTitleEn"></el-table-column>
              <el-table-column label="品牌" prop="brand"></el-table-column>
              <el-table-column label="件数" prop="num"></el-table-column>
              <el-table-column label="重量(kg)" prop="weight"></el-table-column>
              <el-table-column label="体积(m³)" prop="volume"></el-table-column>
              <!-- <el-table-column label="有无单证" prop="">// TODO</el-table-column> -->
              <!-- <el-table-column label="缺货箱数" prop="lessNum"></el-table-column> -->
              <el-table-column label="数量" prop="quantity"></el-table-column>
              <el-table-column label="材质" prop="material"></el-table-column>
            </el-table>

            <div class="mt-10 center">
                <el-button type="primary" @click="addToProductList">下一步</el-button>
                <el-button type="default" @click="showBatchImportDialog=false">取消</el-button>
            </div>
        </el-dialog>
  </div>
</template>

<script>
import { createOrder, updateOrder, getOrder, getProductFeeList, getOrderDetail, getOrderCourierNumber, orderImport, exportPackingList } 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'
import FileUpload from '@/components/FileUpload' 

export default {
  name: "OrderEdit",
  components: {
    ProductSelector, Selector, CustomerContactSelector, AreaSelector, FileUpload
  },
  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,
        isCargoControl: false,
        type:[]
      },
      // 表单校验
      rules: {
        marks               : [{required: true, message: '请填写唛头'}],
        consignorContactsId : [{required: true, message: '发货人不能为空'}],
        consigneeContactsId : [{required: true, message: '收货人不能为空'}],
        transportId         : [{required: true, message: '请选择运输方式'}],
        departureId         : [{required: true, message: '请选择始发城市'}],
        objectiveId         : [{required: true, message: '请选择目的城市'}],
        lineId              : [{required: true, message: '请选择路线'}],
        channelId           : [{required: true, message: '请选择出货渠道'}],
        deliveryDate        : [{required: true, message: '请选择送货日期'}],
        consigneeAddress    : [{required: true, message: '请填写详细地址'}]
      },
      labelStyle: 'width:120px',
      showBatchImportDialog: false, // 显示批量导入弹窗
      importList:[],
      exportLoading: false, // 装下单模板下载状态
    };
  },
  computed:{
    exportCityList(){
        return this.tradeCityList.filter(item => item.type == 2 || item.type == 3)
    },
    importCityList(){
        return this.tradeCityList.filter(item => item.type == 1 || item.type == 3)
    },
    exportCityIds(){
        let ids = []
        this.exportCityList.forEach(item => {
            ids.push(item.id)
        })
        return ids
    },
    importCityIds(){
        let ids = []
        this.importCityList.forEach(item => {
            ids.push(item.id)
        })
        return ids
    },
    getDictData(){
        return (type, value) => getDictData(type, value) || {}
    },
    getDictDatas(){
        return getDictDatas
    },
    selectedRouter(){
        // otherService 1 送货上门，2非控货订单代收货款
        if(!this.form.lineId)return null
        return this.routerList.find(item => item.id == this.form.lineId)
    },
    // 送货上门
    homeDeliveryService(){
        return this.selectedRouter && this.selectedRouter.otherService && this.selectedRouter.otherService.indexOf('1') > -1
    },
    // 代收货款（非控货订单，且路线开通了代收服务）
    collectionProxy(){
        return !this.form.isCargoControl && this.selectedRouter && this.selectedRouter.otherService && this.selectedRouter.otherService.indexOf('3') > -1
    },
    // 根据渠道id显示渠道名
    getChannelNameById(){
        return channelId => {
            return this.channelList.find(item => item.channelId == channelId) ?. nameZh
        }
    },
    // 当前运输方式
    transport(){
        return this.transportList.find(item => item.value == this.form.transportId)
    },
    // 根据id获取优惠券
    getCoupon(){
        return couponId => {
            if(!couponId) return null
            return this.couponList.find(item => item.couponId == couponId)
        }
    },
    currentcyMap(){
        let map = {}
        this.currencyList.forEach(item => {
            map[item.id] = item.titleZh
        })
        return map
    },
    unitMap(){
        let map = {}
        this.unitList.forEach(item => {
            map[item.id] = item.titleZh
        })
        return map
    },
    sum(){
        let sum = {
            totalNum: 0,
            totalVolume: 0,
            totalWeight: 0,
            totalWorth: 0,
            totalQuatity: 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
            sum.totalQuatity += parseInt(item.quantity) || 0

        })
        return sum
    },
    // 总优惠金额
    discount(){
        return 0
    },
    // 是否编辑
    editMode(){
        return this.$route.path.indexOf('create') == -1
    },
    // 是否可以编辑商品基本信息（货值除外）
    productEditable(){
        // 非编辑模式 或者 草稿状态就可以编辑
        return !this.editMode || this.form.status == 0 
    },
    // 路线开通的服务
    routeOtherServices(){
        if(!this.selectedRouter || !this.selectedRouter.otherService) return []
        return this.selectedRouter.otherService.split(',')
    }
  },
  watch:{
    // 始发地
    'form.departureId'(){
        this.getOpenedRouterList()
    },
    // 目的地
    'form.objectiveId'(){
        this.getOpenedRouterList()
    },
    'form.transportId'(){
        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)
    },
    /* // 发货联系人发生变化获取发货客户
    consignorContact(){
        this.getConsignor()
    },
    // 收货联系人发生变化获取收货客户
    consigneeContact(){
        this.getConsignee()
    }, */
    productList:{
        deep: true,
        handler(){
            this.productList.map(item => {
                item.prodAttrIds = item.prodAttrArr.join(',')
            })
            this.calculationPrice()
        }
    },
    fee(){
        this.getCoupons()
    },
    // 选择的路线变化后，需要判断是否开通了对应的服务，如果没开通需要取消对应的服务选择
    selectedRouter(val){
        if(!val) return
        ['1', '4'].forEach(service => {
            if(this.routeOtherServices.indexOf(service) < 0 && this.form.type.indexOf(service) > -1){
                this.form.type.splice(this.form.type.findIndex(item => item == service), 1)
            }
        })
        
    }
  },
  created() {
    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))
            })
            this.form.type = this.form.type ? this.form.type.split(',').filter(item => 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: {
    upload(e){
        console.log({upload: e})
        let form = new FormData()
        form.append('file', e.file)
        orderImport(form).then(res => {
            this.importList = res.data.list
            this.$set(this.form, 'packingListUrl', res.data.packingListUrl)
        })
    },
    addToProductList(){
        console.log('addToProductList')
        this.importList.forEach(item => {
            this.productList.push({
                prodId: item.prodId,
                brand: item.brandType,
                num: item.num,
                quantity: item.quantity,
                volume: item.volume,
                weight: item.weight,
                prodAttrArr:[]
            })
        })
        // 重置
        this.importList = []
        this.showBatchImportDialog = false
    },
    downloadTpl(){
        this.exportLoading = true;
        exportPackingList().then(response => {
            this.$download.excel(response, '装箱单模板.xls');
            this.exportLoading = false;
        }).catch(() => { });
    },
    setLink(row){
        this.$prompt('请输入商品链接', {inputValue: row.link}).then(({value}) => {
            console.log('value', value)
            this.$set(row, 'link', value)
        })
    },
    onFileChoosed(e){
        window.choosed = e
        console.log('onFileChoosed', e)

        const reader = new FileReader();
        reader.readAsBinaryString(e.target.files[0]);
        reader.onload = function(e) {
            const data = e.target.result;
            const zzexcel = xlsx.read(data, {
                type: 'binary'
            })
            window.zzexcel = zzexcel
            window.tableJson = xlsx.utils.sheet_to_json(zzexcel.Sheets[zzexcel.SheetNames[0]])
        }
    },
    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)
    },
    // 生成快递单号
    getOrderCourierNumber(){
        getOrderCourierNumber().then(res => {
            this.$set(this.form, 'number', 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
        if(!this.productList.length) return false
        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.filter(item => {
            return this.exportCityIds.indexOf(item.startCityId) > -1 && this.importCityIds.indexOf(item.destCityId) > -1
        }))
    },
    // 计算体积
    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' ? 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(",")
            })
            data.type = data.type.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
        })
        data.type = data.type.join(',')
        // 添加的提交
        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>