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

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item :label="$t('编号')" prop="orderNo">
        <el-input v-model="queryParams.numberKey" :placeholder="$t('请输入订单号、唛头、提单号')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item :label="$t('唛头')" prop="marks">
        <el-input v-model="queryParams.marks" :placeholder="$t('唛头')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->

      <el-form-item :label="$t('发货人')" prop="consignorKey">
        <el-input v-model="queryParams.consignorKey" :placeholder="$t('发货人')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('收货人')" prop="consigneeKey">
        <el-input v-model="queryParams.consigneeKey" :placeholder="$t('收货人')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="">
        <dict-selector :type="DICT_TYPE.ECW_BEGINTIME_TYPE_ENDTIME" v-model="dateFilterType" defaultable style="width: 150px; margin-right: 5px" />
        <el-date-picker v-model="dateFilter" type="datetimerange"  range-separator="-"
          :start-placeholder="$t('开始日期')"
          :end-placeholder="$t('结束日期')"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="handleQuery"
          >
          </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('始发仓')" prop="startWarehouseId">
        <el-select v-model="queryParams.startWarehouseId" :placeholder="$t('请选择始发仓')" clearable @change="handleQuery">
          <el-option v-for="item in exportWarehouseList" :label="$l(item, 'title')" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('目的仓')" prop="destWarehouseId">
        <el-select v-model="queryParams.destWarehouseId" :placeholder="$t('请选择目的仓')" clearable @change="handleQuery">
          <el-option v-for="item in importWarehouseList" :label="$l(item, 'title')" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('运输方式')" prop="transportId" v-if="!transportId">
        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model.number="queryParams.transportId" clearable @change="handleQuery"/>
      </el-form-item>

      <!-- <el-form-item :label="$t('商品分类')" prop="goodsType">
        <selector v-model="queryParams.goodsType" :options="productAttrList" label-field="attrName" value-field="id">
        </selector>
      </el-form-item>
      <el-form-item :label="$t('品名')" prop="prodId">
        <product-selector v-model="queryParams.prodId" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('品牌')" prop="brand">
        <dict-selector v-model="queryParams.brand" :type="DICT_TYPE.ECW_IS_BRAND" formatter="bool" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->

      <el-form-item :label="$t('商品')" prop="tidanNo">
        <el-input v-model="queryParams.prodKey" :placeholder="$t('请输入商品类型、品名或品牌')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('控货')" prop="isCargoControl">
        <dict-selector v-model="queryParams.isCargoControl" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" fomatter="bool" clearable />
      </el-form-item>
      <el-form-item :label="$t('入仓类型')" prop="warehouseType">
        <dict-selector :type="DICT_TYPE.ECW_WAREHOUSING_TYPE" v-model="queryParams.warehouseType"  clearable/>
      </el-form-item>
      <el-form-item :label="$t('客户经理')" >
        <user-selector v-model="queryParams.salesmanId" clearable @change="handleQuery"/>
      </el-form-item>
      <el-form-item :label="$t('订单状态')" prop="status">
        <dict-selector :type="DICT_TYPE.ORDER_STATUS" v-model="queryParams.status"
          @keyup.enter.native="handleQuery" clearable />
      </el-form-item>
      <el-form-item :label="$t('报关方式')" prop="customsType">
        <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="queryParams.customsType" clearable @change="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('是否齐货')" >
        <!--// 字段存疑-->
        <dict-selector v-model="queryParams.isNeat" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" fomatter="bool"  clearable @change="handleQuery"/>
      </el-form-item>
      <!-- <el-form-item :label="$t('重货比')" prop="weightRatio">
        <el-input style="width: 100px;" v-model="molecule" placeholder="" clearable @change="moleculeChange"
          @keyup.enter.native="handleQuery" />
        -
        <el-input style="width: 100px;" v-model="denominator" placeholder="" clearable @change="denominatorChange"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item :label="$t('备案属性')" prop="productRecord">
        <dict-selector :type="DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE" v-model="queryParams.productRecord" clearable @change="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('快递单号')" prop="number">
        <el-input v-model="queryParams.number" :placeholder="$t('快递单号')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('外部仓')" prop="number">
        <el-select v-model="queryParams.isExternalWarehouse" :placeholder="$t('请选择')" clearable @change="handleQuery">
          <el-option :label="$t('外部仓')" :value="1"></el-option>
          <el-option :label="$t('自有仓')" :value="0"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('异常状态')" prop="status">
        <dict-selector :type="DICT_TYPE.ORDER_ABNORMAL_STATE" v-model="queryParams.abnormalState"
          @keyup.enter.native="handleQuery" clearable />
      </el-form-item>
      <el-form-item :label="$t('审核状态')" prop="status">
        <dict-selector :type="DICT_TYPE.ECW_ORDER_APPROVAL_TYPE" v-model="queryParams.auditType"
          @keyup.enter.native="handleQuery" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{$t('搜索')}}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{$t('重置')}}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ecw:order:create']">{{$t('新增')}}</el-button>
      </el-col>
      <el-col :span="1.5">
<!--        <el-button type="primary" plain icon="el-icon-setting" size="mini" @click="handleEdit" :disabled="!batchWarehouseAdjustment">{{$t('批量调仓')}}-->
<!--        </el-button>-->
        <el-button type="primary" plain icon="el-icon-setting" size="mini" @click="showBatchPickup=true">{{$t('批量提货')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          :loading="exportLoading" v-hasPermi="['ecw:order:export']">{{$t('导出')}}</el-button> -->
        <el-dropdown v-hasPermi="isAll ? ['ecw:order:export','ecw:order:export:other']:[exportPermiString]">
          <el-button type="primary" :loading="exportLoading" size="mini">
            导出 <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-hasPermi="[exportPermiString]" @click.native="exportChecked">导出勾选</el-dropdown-item>
            <el-dropdown-item v-hasPermi="[exportPermiString]" @click.native="exportSearch">导出搜索</el-dropdown-item>
            <template v-if="isAll" v-hasPermi="['ecw:order:export:other']">
              <el-dropdown-item @click.native="$message('// TODO')">异常单统计</el-dropdown-item>
              <el-dropdown-item @click.native="$message('// TODO')">重货单统计</el-dropdown-item>
              <el-dropdown-item @click.native="$message('// TODO')">退仓单统计</el-dropdown-item>
              <el-dropdown-item @click.native="$message('// TODO')">售后赔偿金额统计</el-dropdown-item>
              <el-dropdown-item @click.native="$message('// TODO')">报关数据统计</el-dropdown-item>
              <el-dropdown-item @click.native="$message('// TODO')">客户出货量统计</el-dropdown-item>
              <el-dropdown-item @click.native="$message('// TODO')">预付运费统计</el-dropdown-item>
              <el-dropdown-item @click.native="$message('// TODO')">卸货费统计</el-dropdown-item>
            </template>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="15" v-if="statistics">
        <!-- 订单列表显示搜索条件对应箱数、仓库实测、收款方数、重量 -->
        合计：{{statistics.totalNum}}箱，{{statistics.totalVolume}}m³(测) {{statistics.totalChargeVolume}}m³(重) {{statistics.totalWeight}}KG
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column :label="$t('订单编号')" width="120px" align="center" prop="orderNo" >
        <template slot-scope="scope">
          <router-link :to="{path: '/order/detail',query: {orderId: scope.row.orderId}}" class="link-type">
            <span>{{ scope.row.orderNo }}</span>
          </router-link>
          <div style="display: flex;flex-wrap: wrap;" v-if="scope.row.advanceType">
            <el-button @click="deleteSpecial(item.value,scope.row.orderId)" size="mini" style="margin-left: 20px" type="danger" circle v-for="(item,index) in specialRendering(scope.row.advanceType)" :key="index">{{item.label[0]}}</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('唛头')" align="center" prop="marks" />
      <el-table-column :label="$t('总箱数/入仓箱数')" align="center" prop="sumNum">
        <template slot-scope="{row}">
          <div :style="{color:row.customsType != 1 ? 'red' : null}">{{row.totalNum}}{{$t('箱')}}/{{row.sumNum}}{{$t('箱')}}</div>
          <dict-tag v-if="row.customsType != 1" style="color:red" :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="row.customsType"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('体积/重量')" align="center" prop="sumWeight">
        <template slot-scope="{row}">
          <!--入仓前是填单数据，入仓后是入仓数据，装柜审核通过等状态inwarehouseState会变成0，所以只能通过sumNum来判断-->
          <component
          :is="row.orderType ==  2 ? 'el-tooltip' : 'div'"
          class="item"
          :style="{
            color: row.orderType ==  2 ? 'red' : null
          }"
          effect="dark"
          :content="(row.wvolume||0)+'m³'"
          placement="bottom">
            <div v-if="row.sumNum > 0">{{row.sumVolume}}m³ /{{row.sumWeight}}Kg</div>
            <div v-else>{{row.costVO.totalVolume}}m³ /{{row.costVO.totalWeight}}Kg</div>
          </component>
          <!-- <el-tooltip v-if="scope.row.orderExceptionType=='order_heavy_cargo_exception'" class="item" effect="dark" :content="(scope.row.wvolume||0)+'m³'" placement="bottom">
            <span style="color:#ff4949" v-if="scope.row.orderStatus >= 5 ">{{scope.row.volume+"m³/"+scope.row.weight+"kg"}}</span>
            <span style="color:#ff4949" v-else>{{scope.row.totalVolume+"m³/"+scope.row.totalWeight+"kg"}}</span>
          </el-tooltip> -->
        </template>
      </el-table-column>
      <el-table-column :label="$t('始发仓')" align="center" prop="startWarehouseName">
        <template slot-scope="{row}">
          {{row.startWarehouseName}}
          <span style="color:red" v-if="row.isExternalWarehouse">({{$t('外部仓')}})</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('运输方式/目的地')" align="center" prop="transportId">
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="row.transportId" /> / {{row.dstWarehouseName}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('控货')" align="center" prop="transportId">
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="row.isCargoControl" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('订单状态')" align="center" prop="status">
        <template slot-scope="scope">
          <!-- <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.status" /> -->
          {{scope.row.statusMsg}}
        </template>
      </el-table-column>

      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width actions" width="150px">
        <template slot-scope="scope">
          <!-- 已删除的订单只需要删除和查看 https://zentao.jdshangmen.com/bug-view-684.html -->
          <template v-if="scope.row.status == 88">
            <el-button type="text" @click.native="oprateOrder(scope.row.orderId, 'deleteOrder')" v-hasPermi="['ecw:order:delete']" >{{$t('删除')}}</el-button>
          </template>
          <template v-else>
            <!--操作相关的-->
            <el-dropdown>
              <el-button type="text">{{$t('操作')}}</el-button>
              <el-dropdown-menu slot="dropdown">
                <!-- 编辑 -->
                <template v-if="
                  ( scope.row.status < 12 || (scope.row.status == 12 && scope.row.shipmentState == 314) ) && !scope.row.abnormalState && exclude(scope.row.inWarehouseState, [204,205,206])
                  ">
                  <el-dropdown-item @click.native="handleUpdate(scope.row)" v-hasPermi="['ecw:order:update']" >{{$t('编辑')}}</el-dropdown-item>
                </template>

                <!-- 删除 -->
                <template v-if="include(scope.row.status, [0,2, 88])">
                  <el-dropdown-item @click.native="oprateOrder(scope.row.orderId, 'deleteOrder')" v-hasPermi="['ecw:order:delete']" >{{$t('删除')}}</el-dropdown-item>
                </template>

                <!-- 取消 -->
                <template v-if="include(scope.row.status, [2])">
                  <el-dropdown-item @click.native="oprateOrder(scope.row.orderId, 'cancelOrder')" >{{$t('取消订单')}}</el-dropdown-item>
                </template>

                <!-- 恢复 -->
                <!-- <el-dropdown-item @click.native="oprateOrder(scope.row.orderId, 'recoveryOrder')" >{{$t('恢复订单')}}</el-dropdown-item>-->

                <!-- 费用申请 -->
                <template v-if="
                  exclude(scope.row.status, [0, 88]) && exclude(scope.row.inWarehouseState, [204,205,206])
                  ">
                  <el-dropdown-item @click.native="feeApplicationBol = true; orderId = scope.row.orderId"  >{{$t('费用申请')}}</el-dropdown-item>
                </template>

                <!-- 特需,互斥，关联 -->
                <template v-if="
                  include(scope.row.status, [2,3,5,8,9,10]) &&
                  exclude(scope.row.abnormalState, [1 ,99 ,2 ,3 ,4 ,9 ,10 ,11 ,12 ,14]) &&
                  exclude(scope.row.inWarehouseState, [204])
                  ">
                  <el-dropdown-item @click.native="orderId = scope.row.orderId;orderNo = scope.row.orderNo;isShow = true" >{{$t('特需')}}</el-dropdown-item>
                  <el-dropdown-item @click.native="$router.push(`/order/associated-order/${scope.row.orderId}`)"          >{{$t('关联')}}</el-dropdown-item>
                  <el-dropdown-item @click.native="$router.push(`/order/mutex-order/${scope.row.orderId}`)"               >{{$t('互斥')}}</el-dropdown-item>
                </template>

                <!-- 特价 -->
                <template v-if="
                  exclude(scope.row.status, [0]) &&
                  // exclude(scope.row.abnormalState, [1 ,99 ,2 ,3 ,4 ,9 ,10 ,11 ,12 ,14]) &&
                  exclude(scope.row.inWarehouseState, [204,205,206])
                  ">
                  <el-dropdown-item @click.native="$router.push('/order/special/' + scope.row.orderId)" v-hasPermi="['ecw:order:update']" >{{$t('特价')}}</el-dropdown-item>
                </template>

                <!-- 确认提货 -->
                <template v-if="
                  scope.row.status >= 5 &&
                  !scope.row.abnormalState &&
                  exclude(scope.row.inWarehouseState, [204,205,206])
                  ">
                  <el-dropdown-item @click.native="$router.push(`/order/release?orderId=${scope.row.orderId}`)" >{{$t('确认提货')}}</el-dropdown-item>
                </template>

                <!-- 合单，拆单 -->
                <template v-if=" (scope.row.status < 12 || (scope.row.status == 12 && scope.row.shipmentState == 314)) && !scope.row.abnormalState && scope.row.status > 3 && exclude(scope.row.inWarehouseState, [204,205,206])">
                  <el-dropdown-item @click.native="$router.push(`/order/singleApply?orderNo=${scope.row.orderNo}`)" >{{$t('合单申请')}}</el-dropdown-item>
                  <el-dropdown-item @click.native="$router.push(`/order/splitApply?orderId=${scope.row.orderId}`)"  >{{$t('拆单申请')}}</el-dropdown-item>
                </template>

                <!-- 合单日志，提货日志 -->
                <template v-if="(
                  scope.row.status > 2 &&
                  exclude(scope.row.status + '-' + scope.row.shipmentState, ['17-391', '18-392', '15-332', '15-330']) &&
                  exclude(scope.row.status + '-' + scope.row.inWarehouseState, ['16-202'])
                )">
                  <el-dropdown-item @click.native="showMergedLogOrderNo=scope.row.orderNo" >{{$t('合单日志')}}</el-dropdown-item>
                  <el-dropdown-item @click.native="showPickupLogOrderNo=scope.row.orderNo" >{{$t('提货日志')}}</el-dropdown-item>
                </template>
              </el-dropdown-menu>
            </el-dropdown>

            <template v-if="exclude(scope.row.status, [0, 11,12,13,14,15,17,18]) && exclude(scope.row.inWarehouseState, [204,205,206])">
              <!-- <el-divider direction="vertical"></el-divider> -->
              <!--仓库相关的-->
              <el-dropdown>
                <el-button type="text">{{$t('仓库')}}</el-button>
                <el-dropdown-menu slot="dropdown">
                  <!-- 入仓操作 -->
                  <template v-if="include(scope.row.status, [0,2]) || include(scope.row.abnormalState, [1]) || scope.row.inWarehouseState == 208">
                    <el-dropdown-item @click.native="$router.push('/order/warehousing?id=' + scope.row.orderId)" v-hasPermi="['ecw:order:update']">{{$t('入仓操作')}}</el-dropdown-item>
                  </template>
                  <!-- 入仓补充 -->
                  <template v-if="
                    include(scope.row.inWarehouseState, [201,202, 202, 210, 202, 211, 202, 213, 214, 215, 216]) &&
                    scope.row.abnormalState != 1 &&
                    include(scope.row.status, [2,3,5,10,9,8])
                    ">
                    <el-dropdown-item @click.native="$router.push('/order/warehousing-add?id=' + scope.row.orderId)" v-hasPermi="['ecw:order:update']">{{$t('入仓补充')}}</el-dropdown-item>
                  </template>
                  <!-- 入仓修改 -->
                  <template v-if="
                      (
                        include(scope.row.inWarehouseState, [202, 207, 202, 209, 210, 202, 211, 212, 202, 213, 214, 215, 216, 204, 205]) &&
                        scope.row.status != 11 && exclude(scope.row.shipmentState, [314,315,317,318])
                      )
                    ">
                    <el-dropdown-item @click.native="$router.push('/order/warehousing-update?id=' + scope.row.orderId)"  v-hasPermi="['ecw:order:update']" :disabled2="scope.row.parentOrderId">{{$t('入仓修改')}}</el-dropdown-item>
                  </template>

                  <!-- 退仓 -->
                  <template v-if="
                      (
                        include(scope.row.inWarehouseState, [202, 210, 211, 213, 214, 215, 216]) &&
                        exclude(scope.row.abnormalState, [1])
                      ) ||
                      include(scope.row.status, [16])
                    ">
                    <el-dropdown-item @click.native="show = true;orderId = scope.row.orderId; " v-hasPermi="['ecw:order:update']">{{$t('退仓')}}</el-dropdown-item>
                  </template>


                  <!-- 调仓 -->
                  <template v-if="
                      include(scope.row.inWarehouseState, [202, 207, 209, 210, 202, 211, 212, 215, 216, 218]) ||
                      (include(scope.row.status, [16]) && exclude(scope.row.inWarehouseState, [213,214]))
                    ">
                    <el-dropdown-item @click.native="orderId = scope.row.orderId;warehouseBol=true;" >{{$t('调仓')}}</el-dropdown-item>
                  </template>

                  <!-- 取消调仓 -->
                  <!-- <template v-if="
                      include(scope.row.inWarehouseState, [212,213,214])
                    ">
                    <el-dropdown-item @click.native="$alert('// TODO')" >{{$t('取消调仓')}}</el-dropdown-item>
                  </template> -->

                  <!-- 调拨出仓 -->
                  <template v-if="
                      include(scope.row.inWarehouseState, [213])
                    ">
                    <el-dropdown-item @click.native="$router.push({path:'/order/transfer-warehousing/' + scope.row.orderId + '/'  + 1 })"  >{{$t('调拨出仓')}}</el-dropdown-item>
                  </template>

                  <!-- 调拨到仓 -->
                  <template v-if="
                      include(scope.row.inWarehouseState, [214])
                    ">
                    <el-dropdown-item @click.native="$router.push({path:'/order/transfer-to-warehouse/' + scope.row.orderId + '/'  + 2 })" >{{$t('调拨到仓')}}</el-dropdown-item>
                  </template>

                </el-dropdown-menu>
              </el-dropdown>
            </template>

            <!-- <el-divider direction="vertical" v-if="scope.row.status != 0"></el-divider> -->
            <!--打印相关的-->
            <el-dropdown v-if="scope.row.status != 0">
              <el-button type="text">{{$t('打印')}}</el-button>
              <el-dropdown-menu slot="dropdown">
                <!-- 打印标签 -->
                <template v-if="
                  exclude(scope.row.status, [0]) &&
                  exclude(scope.row.abnormalState, [5,6,7,8])
                ">
                  <el-dropdown-item @click.native="printTagOrderId=scope.row.orderId">{{$t('打印标签')}}</el-dropdown-item>
                </template>

                <!-- 打印入仓单 -->
                <template v-if="
                  exclude(scope.row.status, [0, 2]) &&
                  exclude(scope.row.shipmentState, [320,322,323]) &&
                  exclude(scope.row.abnormalState, [1, 5,6,7,8])
                ">
                  <el-dropdown-item @click.native="printWarehouseReceiptOrderId=scope.row.orderId">{{$t('打印入仓单')}}</el-dropdown-item>
                </template>

                <!-- 打印提单 -->
                <el-dropdown-item @click.native="printLadingBillOrderId=scope.row.orderId" :disabled="!scope.row.tidanNo">{{$t('打印提单')}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </template>

      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
      @pagination="getList" />

    <special-needs :orderNo="orderNo" :show.sync="isShow" :currency="JSON.stringify(currencyList)" :order-id="orderId" @determine="getList" ></special-needs>
    <print-tag v-if="printTagOrderId !== null" :order-id="printTagOrderId" @close="printTagOrderId=null" />
    <print-warehouse-receipt v-if="printWarehouseReceiptOrderId !== null" :order-id="printWarehouseReceiptOrderId" @close="printWarehouseReceiptOrderId=null" />
    <print-lading-bill v-if="printLadingBillOrderId !== null" :order-id="printLadingBillOrderId" @close="printLadingBillOrderId=null" />
    <batch-pickup v-if="showBatchPickup" @close="onBatchClose" @success="onBatchClose"/>
    <withdrawal v-if="show" :dialog-visible="show"  :orderId="orderId" ></withdrawal>
    <batch-single-application :order-list="orderId" :dialog-visible.sync="warehouseBol"></batch-single-application>
    <fee-application :order-id="orderId" :currencys="JSON.stringify(currencyList)" :dialog-visible.sync="feeApplicationBol"></fee-application>
    <merge-log :order-no="showMergedLogOrderNo" v-if="showMergedLogOrderNo !== null" @close="showMergedLogOrderNo=null" />
    <pickup-log v-if="showPickupLogOrderNo" :order-no="showPickupLogOrderNo" @close="showPickupLogOrderNo=null" @delete="getList" />
  </div>
</template>

<script>
import Selector from '@/components/Selector'
import ProductSelector from '@/components/ProductSelector'
import { getProductAttrList } from '@/api/ecw/productAttr'
import CustomerSelector from '@/components/CustomerSelector'
import specialNeeds from '@/views/ecw/order/components/specialNeeds';
import { getTradeCityList } from '@/api/ecw/region'
import {
  createOrder,
  updateOrder,
  deleteOrder,
  getOrder,
  getOrderPage,
  exportOrderExcel,
  orderSpecialNeed,
  cancelOrder,
  recoveryOrder,
  getMyOrderPage,
  deptOrderPage,
  orderStatistics,
  orderMyStatistics,
  orderDeptStatistics,
  orderExportSearch,
  orderExportMySearch,
  orderExportDeptSearch
} from "@/api/ecw/order";
/* import { getDictDatas, DICT_TYPE } from '@/utils/dict'; */
import PrintTag from './components/PrintTag'
import PrintWarehouseReceipt from './components/PrintWarehouseReceipt'
import PrintLadingBill from './components/PrintLadingBill'
import BatchPickup from './components/BatchPickup'
import withdrawal from "@/views/ecw/order/withdrawal";
import UserSelector from '@/components/UserSelector'
import BatchSingleApplication from "@/views/ecw/order/batchSingleApplication";
import FeeApplication from "@/views/ecw/order/feeApplication";
import MergeLog from '@/views/ecw/order/components/MergeLog'
import PickupLog from './components/PickupLog'
import {getWarehouseList} from '@/api/ecw/warehouse'
import { getCurrencyPage } from "@/api/ecw/currency";
export default {
  name: "EcwOrderIndex",
  components: {
    UserSelector,
    FeeApplication,
    BatchSingleApplication,
    MergeLog,
    PickupLog,
    CustomerSelector, ProductSelector, Selector,specialNeeds,PrintTag, PrintWarehouseReceipt, PrintLadingBill, BatchPickup,withdrawal
  },
  props: {
    mine: Boolean, // 标识我的订单列表
    dept: Boolean // 标识部门订单列表
  },
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10
      },
      warehouseList:[],
      // tradeCityList: [],
      productAttrList: [],  // 商品属性
      molecule: '', //重货比分子
      denominator: '', //重货比分母
      dateFilterType: '', //日期筛选类别
      dateFilter: [], //筛选日期

      printTagOrderId: null, // 显示打印标签的订单ID
      printWarehouseReceiptOrderId: null, // 打印入仓单的订单ID
      printLadingBillOrderId: null, // 打印提单的订单ID
      showBatchPickup: false, // 是否显示批量提货弹窗
      showMergedLogOrderNo:null, // 显示合单日志订单号
      showPickupLogOrderNo: null, // 显示提货日志的订单号
      isShow:false,//特殊显示
      orderId:undefined,
      adjustmentList:[],
      show:false,
      warehouseBol:false,//调仓申请
      feeApplicationBol:false,//费用申请
      multipleSelection:[],

      transportId: null, // 指定运输方式
      orderNo:'',
      params: {
        page: 1,
        rows: 20,
      },
      currencyList:[],
      statistics: null ,// 统计数据
    };
  },
  watch:{
    isChinese(){
      this.getList()
    }
  },
  computed: {
    // 导出的权限字符串
    exportPermiString(){
      let arr = ['ecw:order:export']
      if(this.mine)arr.push('my')
      if(this.dept)arr.push('dept')
      if(this.transportId)arr.push(this.transportId)
      return arr.join(":")
    },
    // 是否全部订单
    isAll(){
      return !(this.mine || this.dept || this.transportId)
    },
    isChinese(){
      return this.$i18n.locale === 'zh_CN'
    },
    exportWarehouseList(){
      /* tradeType 1 进口，2出口，3进出口 */
      return this.warehouseList.filter(item => item.tradeType == 2 || item.tradeType == 3)
    },
    importWarehouseList(){
      return this.warehouseList.filter(item => item.tradeType == 1 || item.tradeType == 3)
    },
    /* exportCityList() {
      return this.tradeCityList.filter(item => item.type == 2)
    },
    importCityList() {
      return this.tradeCityList.filter(item => item.type == 1)
    }, */
    combinedQueryParams(){
        let timeParams = {}
        if(this.dateFilterType && this.dateFilter){
          timeParams['begin' + this.dateFilterType] = this.dateFilter[0]
          timeParams['end' + this.dateFilterType] = this.dateFilter[1]
        }
        let queryParams = Object.assign({}, this.queryParams, timeParams)
        if(this.transportId){
          queryParams.transportId = this.transportId
        }
        return queryParams
    },
    batchWarehouseAdjustment(){
      return  this.multipleSelection.length > 0 && this.multipleSelection.every(e => e.status === 5)
    },
    include(){
      return (state, arr) => {
        return arr.indexOf(state) > -1
      }
    },
    exclude(){
      return (state, arr) => {
        return arr.indexOf(state) == -1
      }
    }
  },
  activated(){
    this.handleQuery()
  },
  created() {
    this.getTransportFromRoute()
    this.getList();
    getProductAttrList().then(res => this.productAttrList = res.data)
    // getTradeCityList().then(res => this.tradeCityList = res.data)
    getWarehouseList().then(res => this.warehouseList = res.data)

    getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)
  },
  methods: {
    // 获得导出函数
    getExportFunc(){
      let func = orderExportSearch
      if(this.mine)func = orderExportMySearch
      if(this.dept)func = orderExportDeptSearch
      return func
    },
    // 导出勾选
    exportChecked(){
      if(!this.ids.length){
        return this.$message.error(this.$t('请勾选需要导出的订单'))
      }
      return this.exportExcel(this.getExportFunc(), {orderIdList: this.ids}, this.$t("导出勾选"))
    },
    // 导出搜索
    exportSearch(){
      return this.exportExcel(this.getExportFunc(), this.combinedQueryParams, this.$t("导出搜索"))
    },
    // 通用导出函数
    exportExcel(func, params, fileName = null){
      this.exportLoading = true;
      func(params).then(res => {
        console.log({res})
        if(!fileName){
          fileName = this.$t('订单')
        }
        this.$download.excel(res, fileName + '.xls');
      }).finally(() => {
        this.exportLoading = false
      })
    },
    // 提取路径中的运输方式
    getTransportFromRoute(){
        let match = this.$route.path.match(/transport_(\d)/)
        if(!match) return
        this.transportId = match[1]
    },
    oprateOrder(orderId, type){
      let actions = {
        cancelOrder: {
          callable: cancelOrder,
          confirm: this.$t('确定要取消此订单么？')
        },
        recoveryOrder: {
          callable: recoveryOrder,
          confirm: this.$t('确定要恢复此订单么？')
        },
        deleteOrder: {
          callable: deleteOrder,
          confirm: this.$t('确定要删除此订单么？')
        }
      }
      let action = actions[type]
      if(!action){
        return this.$alert('不支持此操作')
      }
      this.$confirm(action.confirm)
        .then(res => {
          return action.callable(orderId)
        })
        .then(res => {
          this.getList()
        })
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      console.log('this.combinedQueryParams', this.combinedQueryParams)
      let func = getOrderPage
      if(this.mine){
        func = getMyOrderPage
        /* return getMyOrderPage(this.combinedQueryParams).then(response => {
          this.list = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }); */
      }else if(this.dept){
        func = deptOrderPage
      }
      // 执行查询
      func(this.combinedQueryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });

      this.getStatistics()
    },
    // 获得统计数据
    getStatistics(){
      let func = orderStatistics
      if(this.mine){
        func = orderMyStatistics
      }else if(this.dept){
        func = orderDeptStatistics
      }
      func(this.combinedQueryParams).then(res => {
        this.statistics = res.data
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        rows: 10
      }
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('create')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push('edit?id=' + row.orderId)
    },

    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      // 执行导出
      this.$modal.confirm(this.$t('是否确认导出所有订单数据项?')).then(() => {
        this.exportLoading = true;
        return exportOrderExcel(this.combinedQueryParams);
      }).then(response => {
        this.$download.excel(response, '${table.classComment}.xls');
        this.exportLoading = false;
      }).catch(() => { });
    },
    // 表格多选
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleEdit() {
      this.warehouseBol = true
      this.orderId = this.ids.join(',')
    },
    moleculeChange() { },
    denominatorChange() { },
    specialRendering(val){
      if(val !== undefined){
        let i = val.split(',')
       let special = this.getDictDatas(this.DICT_TYPE.ORDER_SPECIAL_NEEDS).filter(e => {
           return i.indexOf(e.value) > -1
        })
        return special
      }
    },
    deleteSpecial(id,orderId){
      this.$confirm(this.$t('确定删除此特需么?')).then(res => {
        return orderSpecialNeed({orderId:orderId,advanceType:id})
      }).then(() => {
        this.getList()
      })
    },
    onBatchClose(){
      this.showBatchPickup = false
      this.handleQuery()
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .actions{
    .el-dropdown{
      margin-right: 10px;
      &::last-child{
        margin-right: 0;
      }
    }
}
</style>
