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

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item :label="$t('日期筛选')">
        <dict-selector defaultable :type="DICT_TYPE.ECW_BEGINTIME_TYPE_ENDTIME" v-model="dateFilterType" class="w-100 mr-10" />
        <el-date-picker v-model="dateFilter" type="daterange" range-separator="-"  :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('始发地')" prop="startWarehouseId">
        <el-select v-model="queryParams.startWarehouseId" :placeholder="$t('请选择始发地')" clearable>
          <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="$t('目的地')" prop="destWarehouseId">
        <el-select v-model="queryParams.destWarehouseId" :placeholder="$t('请选择目的地')" clearable>
          <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="$t('运输方式')" prop="transportId">
        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model.number="queryParams.transportId" clearable />
      </el-form-item>
      <el-form-item :label="$t('订单编号')" prop="orderNo">
        <el-input v-model="queryParams.orderNo" :placeholder="$t('订单编号')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('品名')" prop="prodId">
        <product-selector v-model="queryParams.prodId" @keyup.enter.native="handleQuery" clearable/>
      </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="status">
        <dict-selector :type="DICT_TYPE.PAY_ORDER_STATUS" v-model="queryParams.status" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
       <el-form-item :label="$t('提单号')" prop="tidanNo">
        <el-input v-model="queryParams.tidanNo" :placeholder="$t('提单号')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发货人" prop="consignorId">
        <el-input v-model="queryParams.consignorId" :placeholder="$t('发货人')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('收货人')" prop="consigneeId">
        <el-input v-model="queryParams.consigneeId" :placeholder="$t('收货人')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('报关方式')" 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="$t('唛头')" prop="marks">
        <el-input v-model="queryParams.marks" placeholder="唛头" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{$t('搜索')}}</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          :loading="exportLoading" v-hasPermi="['ecw:order:export']">{{$t('导出')}}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="2">
        <el-button type="primary" plain icon="el-icon-setting" size="mini" :disabled="multiple" @click="batchReview">{{$t('批量复核')}}</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="$t('订单编号')" width="120px" align="center" prop="orderNo" >
        <template slot-scope="scope">
          <router-link :to="`detail?orderId=` + scope.row.orderId">{{ scope.row.orderNo }}</router-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('唛头')" align="center" prop="marks" />
      <el-table-column :label="$t('箱数')" align="center" prop="sumNum" >
        <template v-slot="{row}">
          {{row.inWarehouseState > 1 ? row.sumNum : row.totalNum}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('已放箱数')" align="center" prop="sumWeight">
        <template slot-scope="{row}">{{row.releaseNum}}</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" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('提单号')" align="center" prop="status">
        <template slot-scope="scope">
          {{scope.row.tidanNo}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('放货人')" align="center" prop="sumWeight">
        <template slot-scope="{row}">{{row.cargoControlName}}</template>
      </el-table-column>
      <el-table-column :label="$t('控货状态')" align="center" prop="transportId">
        <template slot-scope="{row}">
          <template v-if="row.cargoControlStatus == 1 && row.isToReview">放货中</template>
          <dict-tag v-else :type="DICT_TYPE.CONTROL_GOODS_STATUS" :value="row.cargoControlStatus" />
        </template>
      </el-table-column>
      
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <!--控货中,已入仓-->
          <template v-if="[0,2].indexOf(scope.row.cargoControlStatus) > -1 && scope.row.sumNum > 0">
            <el-button type="text"  size="mini" @click="showReleaseOrderId=scope.row.orderId">{{$t('放货')}}</el-button>
            <el-button type="text"  size="mini" @click="showTransferOrder = scope.row" >{{$t('控货权转移')}}</el-button>
          </template>

          <!--部分控货-->
          <template v-if="scope.row.cargoControlStatus == 2">
            <el-button type="text"  size="mini" @click="toDetail(scope.row)" >{{$t('修改')}}</el-button>
            <el-button type="text"  size="mini" @click="toDetail(scope.row)" >{{$t('取消')}}</el-button>
            <el-button type="text"  size="mini" @click="review(scope.row)" v-if="scope.row.isToReview">{{$t('放货复核')}}</el-button>
          </template>

          <!--已全部放货，但是未复核-->
          <template v-if="scope.row.cargoControlStatus == 1 && scope.row.isToReview">
            <el-button type="text"  size="mini" @click="review(scope.row)">{{$t('放货复核')}}</el-button>
            <el-button type="text"  size="mini" @click="toDetail(scope.row)" >{{$t('修改')}}</el-button>
            <el-button type="text"  size="mini" @click="toDetail(scope.row)" >{{$t('取消')}}</el-button>
          </template>

          <!--已完成放货,且没有待复核；真正的放货完成-->
          <template v-if="scope.row.cargoControlStatus == 1 && !scope.row.isToReview">
            <!-- <el-button type="text"  size="mini" @click="toDetail(scope.row)" >{{$t('查看')}}</el-button> -->
            <el-button type="text"  size="mini" @click="cargoTransfer(scope.row)" >{{$t('调货')}}</el-button>
            <el-button type="text"  size="mini" @click="showFallbackOrder=scope.row" v-if="scope.row.isReleaseAfterGoods">{{$t('反复核')}}</el-button>
          </template>       
          <el-button type="text"  size="mini" @click="toDetail(scope.row)" >{{$t('查看')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
      @pagination="getList" />

    <transfer       v-if="showTransferOrder"          v-bind="showTransferOrder"            @close="showTransferOrder=null" />
    <release        v-if="showReleaseOrderId"         :order-id="showReleaseOrderId"        @close="showReleaseOrderId=null"        @success="onReleaseSuccess" />
    <transfer-cargo v-if="showTransferCargoOrderId"   :order-id="showTransferCargoOrderId"  @close="showTransferCargoOrderId=null"  @success="onTransferCargoSuccess" :cargoControlPickId="pickInfo ? pickInfo.id : 0" />
    <fallback       v-if="showFallbackOrder !== null" :order="showFallbackOrder"            @close="showFallbackOrder=null"         @success="onFallbackSuccess" :index="null"   />
  </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 { getTradeCityList } from '@/api/ecw/region'
import Transfer from '@/views/ecw/order/components/Transfer'
import Release from './components/Release'
import CargoControlEdit from './components/CargoControlEdit'
import { getCargoControlOrderPage, batchReview, orderReview, getPickRleaseInfo } from "@/api/ecw/orderCargoControl"
import TransferCargo from '@/views/ecw/order/components/TransferCargo'
import Fallback from './components/Fallback'

export default {
  name: "OrderCargonControl",
  components: {
    CustomerSelector, ProductSelector, Selector, Transfer, Release,CargoControlEdit, TransferCargo, Fallback
  },
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单列表
      list: [],
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10
      },
      tradeCityList: [],
      productAttrList: [],  // 商品属性
      molecule: '', //重货比分子
      denominator: '', //重货比分母
      dateFilterType: '', //日期筛选类别
      dateFilter: [], //筛选日期
      showTransferOrder: null, // 控制权转移操作订单
      showReleaseOrderId: null, // 放货ID
      showTransferCargoOrderId: null, // 调货ID
      showFallbackOrder: null, // 调货订单
      pickInfo: null, // 当前操作的提货信息
    };
  },
  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: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getCargoControlOrderPage(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();
    },
    
    /** 导出按钮操作 */
    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
    },
    toDetail(row){
      this.$router.push('cargo_control/detail?id=' + row.orderId)
    },
    // 复核
    review(row){
        // 未放货完成则打开详情，已完成放货则弹窗
        if(row.releaseNum < row.sumNum){
          return this.toDetail(row)
        }
        this.$confirm('已核实放货信息，确认放货？')
            .then(res => {
                return orderReview(row.orderId)
            })
            .then(res => {
              this.$message.success('操作成功')
              this.handleQuery()
            })
    },
    // 批量复核
    batchReview(){
      this.$confirm(this.$t('确定复核选中的订单么？')).then(() => {
        return batchReview("orderIds=" + this.ids.join(','))
      }).then(() => {
        this.$message.success(this.$t('操作成功'))
        this.handleQuery()
      })
    },
    cargoTransfer(row){
      getPickRleaseInfo(row.orderId).then(res => {
        if(res.data.cargoControlPickBackVOList && res.data.cargoControlPickBackVOList.length > 1){
          this.toDetail(row)
        }
        this.pickInfo = res.data.cargoControlPickBackVOList[0]
        this.showTransferCargoOrderId=row.orderId
      })
    },
    onReleaseSuccess(){
      this.showReleaseOrderId = null
      this.handleQuery()
    },
    onFallbackSuccess(){
      this.showFallbackOrder = null
      this.handleQuery()
    },
    onTransferCargoSuccess(){
      this.showTransferCargoOrderId = null
      this.handleQuery()
    }
  }
};
</script>
