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

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

      <el-form-item label="发货人" prop="consignorId">
        <el-input v-model="queryParams.consignorId" placeholder="发货人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="收货人" prop="consigneeId">
        <el-input v-model="queryParams.consigneeId" placeholder="收货人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="日期筛选">
        <dict-selector :type="DICT_TYPE.ECW_BEGINTIME_TYPE_ENDTIME" v-model="dateFilterType" style="width: 150px; margin-right: 5px" />
        <el-date-picker v-model="dateFilter" type="daterange" range-separator="-"  start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>

      <el-form-item label="始发地" prop="startWarehouseId">
        <el-select v-model="queryParams.startWarehouseId" 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-form-item label="目的地" prop="destWarehouseId">
        <el-select v-model="queryParams.destWarehouseId" 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-form-item label="运输方式" prop="transportId">
        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="queryParams.transportId" formatter="number" />
      </el-form-item>

      <el-form-item label="商品分类" prop="goodsType">
        <selector v-model="queryParams.goodsType" :options="productAttrList" label-field="attrName" value-field="id">
        </selector>
      </el-form-item>
      <el-form-item label="品名" prop="prodId">
        <product-selector v-model="queryParams.prodId" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="品牌" 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="提单号" prop="tidanNo">
        <el-input v-model="queryParams.tidanNo" placeholder="提单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="控货" prop="isCargoControl">
        <dict-selector v-model="queryParams.isCargoControl" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" fomatter="bool" />
      </el-form-item>
      <el-form-item label="入仓类型" prop="warehouseType">
        <dict-selector :type="DICT_TYPE.ECW_WAREHOUSING_TYPE" v-model="queryParams.warehousingType" />
      </el-form-item>
      <el-form-item label="跟进客服" >
        <customer-selector />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <dict-selector :type="DICT_TYPE.PAY_ORDER_STATUS" v-model="queryParams.status"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="报关方式" prop="customsType">
        <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="queryParams.customsType" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否齐货" >
        <dict-selector v-model="queryParams.isCargoControl" :type="DICT_TYPE.INFRA_BOOLEAN_STRING" fomatter="bool" />
      </el-form-item>
      <el-form-item label="重货比" 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="备案属性" prop="productRecord">
        <dict-selector :type="DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE" v-model="queryParams.productRecord" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="快递单号" prop="number">
        <el-input v-model="queryParams.number" placeholder="快递单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</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']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-setting" size="mini" @click="handleEdit" :disabled="multiple">批量调仓
        </el-button>
        <el-button type="primary" plain icon="el-icon-setting" size="mini" @click="showBatchPickup=true">批量提货
        </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']">导出</el-button>
      </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="订单编号" 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;">
            <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="唛头" align="center" prop="marks" />
      <el-table-column label="总箱数/入仓箱数" align="center" prop="sumNum">
        <template slot-scope="{row}">{{row.totalNum}}箱/{{row.sumNum}}箱</template>
      </el-table-column>
      <el-table-column label="体积/重量" align="center" prop="sumWeight">
        <template slot-scope="{row}">{{row.totalVolume}}m³ /{{row.totalWeight}}Kg</template>
      </el-table-column>
      <el-table-column label="始发仓" align="center" prop="departureName" />
      <el-table-column label="运输方式/目的地" align="center" prop="transportId">
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="row.transportId" /> / {{row.objectiveName}}
        </template>
      </el-table-column>
      <el-table-column label="控货" 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="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <!--操作相关的-->
          <el-popover
            style="margin-left: 10px;"
            placement="bottom"
            width="100"
            trigger="hover">
            <el-button type="text" slot="reference">操作</el-button>
            <div style=" display:flex; flex-direction:column">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['ecw:order:update']">编辑</el-button>
              <el-button v-if="[0, 88].indexOf(scope.row.status) > -1" size="mini" type="text" icon="el-icon-delete" @click="oprateOrder(scope.row.orderId, 'deleteOrder')"
                v-hasPermi="['ecw:order:delete']">删除</el-button>
              <el-button v-if="scope.row.status < 5" size="mini" type="text" icon="el-icon-delete" @click="oprateOrder(scope.row.orderId, 'cancelOrder')">取消订单</el-button>
              <el-button v-if="scope.row.status == 88" size="mini" type="text" icon="el-icon-delete" @click="oprateOrder(scope.row.orderId, 'recoveryOrder')">恢复订单</el-button>

              <el-button type="text"  size="mini" @click="$router.push(`/order/fee-application/${scope.row.orderId}`)">费用申请</el-button>
              <el-button type="text"  size="mini" @click="orderId = scope.row.orderId;isShow = true" >特需</el-button>
              <el-button type="text"  size="mini" @click="$router.push(`/order/associated-order/${scope.row.orderId}`)" >关联</el-button>
              <el-button type="text"  size="mini" @click="$router.push(`/order/mutex-order/${scope.row.orderId}`)" >互斥</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="$router.push('/order/special?id=' + scope.row.orderId)"
                     v-hasPermi="['ecw:order:update']">特价</el-button>

              <el-button type="text"  size="mini" @click="$router.push(`/order/release?orderId=${scope.row.orderId}`)">确认放货</el-button>
            </div>

          </el-popover>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ecw:order:update']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="$router.push('/order/warehousing?id=' + scope.row.orderId)"
            v-hasPermi="['ecw:order:update']">入仓</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ecw:order:update']">退仓</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="$router.push('/order/special?id=' + scope.row.orderId)"
                     v-hasPermi="['ecw:order:update']">特价</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ecw:order:delete']">删除</el-button>
          <!--仓库相关的-->
          <el-popover
            style="margin-left: 10px;"
            placement="bottom"
            width="100"
            trigger="hover">
            <el-button type="text" slot="reference">仓库</el-button>
            <div style=" display:flex; flex-direction:column">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="$router.push('/order/warehousing?id=' + scope.row.orderId)"
                v-hasPermi="['ecw:order:update']">入仓</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="show = true;orderId = scope.row.orderId; "
                v-hasPermi="['ecw:order:update']">退仓</el-button>
              <el-button type="text" v-if="scope.row.status === 5"  size="mini" @click="$router.push({path:'/order/batch-single-application',query:{list:scope.row.orderId}})" >调仓</el-button>
              <el-button type="text"  size="mini" @click="$router.push({path:'/order/transfer-warehousing/' + scope.row.orderId + '/'  + 1 })" >调拨出仓</el-button>
            </div>

          </el-popover>

          <!--打印相关的-->
          <el-popover
            style="margin-left: 10px;"
            placement="bottom"
            width="100"
            trigger="hover">
            <div style=" display:flex; flex-direction:column">
              <el-button size="mini" type="text" @click="printTagOrderId=scope.row.orderId">打印标签</el-button>
              <el-button size="mini" type="text" @click="printWarehouseReceiptOrderId=scope.row.orderId">打印入仓单</el-button>
              <el-button size="mini" type="text" @click="printLadingBillInfo={tidanNO: scope.row.tidanNo, transportType: scope.row.transportId}" :disabled="!scope.row.tidanNo">打印提单</el-button>
            </div>
            <el-button type="text" slot="reference">打印</el-button>
          </el-popover>

        </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 :show.sync="isShow":order-id="orderId" @determine="getList" ></special-needs>

    <!-- <el-dialog :title="'打印标签'" visible.sync="showPrintTag">

    </el-dialog> -->
    <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="printLadingBillInfo !== null" v-bind="printLadingBillInfo" @close="printLadingBillInfo=null" />
    <batch-pickup v-if="showBatchPickup" @close="showBatchPickup=false"/>
    <withdrawal v-if="show" :dialog-visible="show"  :orderId="orderId" ></withdrawal>
  </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
} 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";
export default {
  name: "Order",
  components: {
    CustomerSelector, ProductSelector, Selector,specialNeeds,PrintTag, PrintWarehouseReceipt, PrintLadingBill, BatchPickup,withdrawal
  },
  props: {
    mine: Boolean
  },
  /* filters: {
    cargoControlStatusFilter(e, cargoControlStatusList) {
      if (e) return cargoControlStatusList.find(item => item.value == e).label
    },
    recordFilter(e, productRecordList) {
      if (e) return productRecordList.find(item => item.value == e).label
    },
    customsTypeFilter(e, customsTypeList) {
      if (e) return customsTypeList.find(item => item.value == e).label
    },
    orderStatusFilter(e, orderStatusList) {
      if (e) return orderStatusList.find(item => item.value == e) ? orderStatusList.find(item => item.value == e).label : ''
    },
    transportFilter(e, transportList) {
      if (e) return transportList.find(item => item.value == e).label
    }
  }, */
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      /* dateRangeRucangtime: [],
      dateRangeDaogangtime: [],
      dateRangeQingguantime: [],
      dateRangePreLoadTime: [],
      dateRangeLoadTime: [],
      dateRangeUnloadTime: [],
      dateRangeTakeTime: [],
      dateRangeSplitTime: [],
      dateRangeCreateTime: [], */
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10
      },

      /* productRecordList: getDictDatas(DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE),
      cargoControlStatusList: getDictDatas(DICT_TYPE.CONTROL_GOODS_STATUS),
      customsTypeList: getDictDatas(DICT_TYPE.ECW_CUSTOMS_TYPE),
      orderStatusList: getDictDatas(DICT_TYPE.PAY_ORDER_STATUS),
      transportList: getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE), */
      tradeCityList: [],
      productAttrList: [],  // 商品属性
      molecule: '', //重货比分子
      denominator: '', //重货比分母
      dateFilterType: '', //日期筛选类别
      dateFilter: [], //筛选日期

      printTagOrderId: null, // 显示打印标签的订单ID
      printWarehouseReceiptOrderId: null, // 打印入仓单的订单ID
      printLadingBillInfo: null, // 打印提单
      showBatchPickup: false, // 是否显示批量提货弹窗
      isShow:false,//特殊显示
      orderId:undefined,
      /* DICT_TYPE,
      getDictDatas */
      adjustmentList:[],
      show:false,

    };
  },
  computed: {
    expoerCityList() {
      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]
        }
        return Object.assign({}, this.queryParams, timeParams)
    }
  },
  created() {
    this.getList();
    getProductAttrList().then(res => this.productAttrList = res.data)
    getTradeCityList().then(res => this.tradeCityList = res.data)
  },
  methods: {
    oprateOrder(orderId, type){
      let actions = {
        cancelOrder: {
          callable: cancelOrder,
          confirm: '确定要取消此订单么？'
        },
        recoveryOrder: {
          callable: recoveryOrder,
          confirm: '确定要恢复此订单么？'
        },
        deleteOrder: {
          callable: deleteOrder,
          confirm: '确定要删除此订单么？'
        }
      }
      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)
      if(this.mine){
        return getMyOrderPage(this.combinedQueryParams).then(response => {
          this.list = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        });
      }
      // 执行查询
      getOrderPage(this.combinedQueryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },

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

    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      // 执行导出
      this.$modal.confirm('是否确认导出所有订单数据项?').then(() => {
        this.exportLoading = true;
        return exportOrderExcel(this.combinedQueryParams);
      }).then(response => {
        this.$download.excel(response, '${table.classComment}.xls');
        this.exportLoading = false;
      }).catch(() => { });
    },
    // 表格多选
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleEdit() {
      this.$router.push({
        path:'/order/batch-single-application',
        query:{list: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){
      orderSpecialNeed({orderId:orderId,advanceType:id}).then(
        r =>{
          if(r.code === 0){
            this.getList()
          }
        }
      )
    },
  }
};
</script>
