<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="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>
      <div>
        <el-form-item :label="$t('始发仓')" prop="startWarehouseIds">
          <el-select v-model="queryParams.startWarehouseIds" multiple :placeholder="$t('请选择始发仓')" clearable  @change="handleQuery">
            <el-option v-for="item in exportWarehouseList" :label="item.titleZh" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('目的国')" prop="destCountryId">
          <el-select
            v-model="destCountryId"
            multiple
            :label="destCountryId"
            :placeholder="$t('请选择目的国')"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in AddressProvince"
              :key="item.guojia"
              :label="item.guojiaName"
              :value="item.guojia"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('目的城市')" prop="objectiveId">
          <el-select
            v-model="objectiveId"
            multiple
            :placeholder="$t('请选择目的城市')"
            style="width: 200px"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in AddressCity"
              :key="item.shi"
              :label="item.shiName"
              :value="item.shi"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('目的仓')" prop="destWarehouseId">
          <el-select
            v-model="destWarehouseId"
            multiple
            :placeholder="$t('请选择目的仓')"
            style="width: 200px"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in AddressTown"
              :key="item.id"
              :label="item.titleZh"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item :label="$t('客户经理')">
        <user-selector
          manage
          v-model="queryParams.salesmanIds"
          multiple
          clearable
          @change="handleQuery"
          :prepend="{ id: 0, nickname: $t('未分配客户经理') }"
        />
      </el-form-item>
      <el-form-item :label="$t('运输方式')" prop="transportId" v-show="showSearch">
        <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="channelIds">
        <selector clearable :options="channelList" :label-field="$l('name')" value-field="channelId" v-model="queryParams.channelIds" multiple></selector>
      </el-form-item>
      <el-form-item :label="$t('订单编号')" prop="orderNo">
        <el-input v-model="queryParams.orderNo" :placeholder="$t('订单编号')" clearable @keyup.enter.native="handleQuery" onkeyup="this.value=this.value.replace(/\s+/g, '')" />
      </el-form-item>
      <el-form-item :label="$t('商品')" prop="prodId" v-show="showSearch">
        <product-selector v-model="queryParams.prodId" @keyup.enter.native="handleQuery" clearable  @change="handleQuery" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
      </el-form-item>
      <el-form-item :label="$t('控货状态')" prop="isCargoControl">
        <dict-selector v-model="queryParams.cargoControlStatusList" multiple :type="DICT_TYPE.CONTROL_GOODS_STATUS" clearable  @change="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('订单状态')" prop="statusList" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ORDER_STATUS" multiple v-model="queryParams.statusList"
          @keyup.enter.native="handleQuery" clearable @change="handleQuery" />
      </el-form-item>
       <el-form-item :label="$t('提单号')" prop="tidanNo">
        <el-input v-model="queryParams.tidanNo" :placeholder="$t('提单号')" clearable @keyup.enter.native="handleQuery" onkeyup="this.value=this.value.replace(/\s+/g, '')" />
      </el-form-item>
      <el-form-item :label="$t('发货人')" prop="consignorKey">
        <el-input v-model="queryParams.consignorKey" :placeholder="$t('发货人')" clearable @keyup.enter.native="handleQuery" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
      </el-form-item>

      <el-form-item :label="$t('收货人')" prop="consigneeKey">
        <el-input v-model="queryParams.consigneeKey" :placeholder="$t('收货人')" clearable @keyup.enter.native="handleQuery" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
      </el-form-item>

      <el-form-item :label="$t('报关方式')" prop="customsTypes">
        <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" multiple v-model="queryParams.customsTypes" clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('唛头')" prop="marks">
        <el-input v-model="queryParams.marks" :placeholder="$t('唛头')" clearable @keyup.enter.native="handleQuery" onkeyup="this.value=this.value.replace(/\s+/g, '')" />
      </el-form-item>
      <el-form-item :label="$t('备案属性')" prop="productRecords" v-show="showSearch">
        <dict-selector
          :type="DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE"
          multiple
          v-model="queryParams.productRecords"
          clearable
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('外部仓')" prop="isExternalWarehouse" v-show="showSearch">
        <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="type" v-show="showSearch">
        <el-select v-model="queryParams.type" :placeholder="$t('请选择')" clearable @change="handleQuery" >
          <el-option :label="$t('普通订单')" :value="0"></el-option>
          <el-option :label="$t('集运服务')" :value="1"></el-option>
          <el-option :label="$t('海外仓')" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{$t('搜索')}}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <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.sumNum > 0 ? 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="left" prop="status">
        <template slot-scope="{row}">
          {{row.statusMsg}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('已卸柜/已到仓时间')" align="center" prop="unloadTime" />
      <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">{{$t('放货中')}}</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">
          <el-button type="text"  size="mini" @click="toDetail(scope.row)"  v-hasPermi="['ecw:cargo_control:show']">{{$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"   />
    <!--控货日志-->
    <cargo-log-list v-if="showLogOrderId" :order-id="showLogOrderId" @close="showLogOrderId=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 { getWarningCargoControlOrderPage, batchReview, orderReview, getPickRleaseInfo, exportCargoControl } from "@/api/ecw/orderCargoControl"
import TransferCargo from '@/views/ecw/order/components/TransferCargo'
import Fallback from './components/Fallback'
import {getWarehouseList} from '@/api/ecw/warehouse'
import CargoLogList from "@/views/ecw/order/components/CargoLogList.vue";
import {getRegionList} from "@/api/ecw/order"
import UserSelector from "@/components/UserSelector";
import {getChannelList} from "@/api/ecw/channel";

export default {
  name: "EcwOrderWarningCargocontrol",
  components: {
    CargoLogList,
    UserSelector,
    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: [],
      warehouseList: [],
      productAttrList: [],  // 商品属性
      molecule: '', //重货比分子
      denominator: '', //重货比分母
      dateFilterType: '', //日期筛选类别
      dateFilter: [], //筛选日期
      showTransferOrder: null, // 控制权转移操作订单
      showReleaseOrderId: null, // 放货ID
      showTransferCargoOrderId: null, // 调货ID
      showFallbackOrder: null, // 调货订单
      pickInfo: null, // 当前操作的提货信息
      showLogOrderId: null, // 显示控货日志的订单ID
      channelList: [],
      AddressProvince: [],
      AddressCity: [],
      AddressTown: [],
      destCountryId: null,
      objectiveId: null,
      destWarehouseId: null,
    };
  },
  computed: {
    expoerCityList() {
      return this.tradeCityList.filter(item => item.type == 2)
    },
    importCityList() {
      return this.tradeCityList.filter(item => item.type == 1)
    },
    exportWarehouseList(){
      return this.warehouseList.filter(item => item.tradeType == 2 || item.tradeType == 3)
    },
    importWarehouseList(){
      return this.warehouseList.filter(item => item.tradeType == 1 || item.tradeType == 3)
    },
    combinedQueryParams(){
      let timeParams = {}
      if(this.dateFilterType && this.dateFilter){
        timeParams['begin' + this.dateFilterType] = this.dateFilter[0]
        timeParams['end' + this.dateFilterType] = this.dateFilter[1]
      }
      let queryParams = {}
      //目的国
      if (this.destCountryId != null && this.destCountryId != "") {
        queryParams.destCountryIds = this.destCountryId;
      }
      //目的城市
      if (this.objectiveId != null && this.objectiveId != "") {
        queryParams.objectiveIds = this.objectiveId;
      }
      //目的仓
      if (this.destWarehouseId != null && this.destWarehouseId != "") {
        queryParams.destWarehouseIds = this.destWarehouseId;
      }
      return Object.assign({}, this.queryParams, timeParams, queryParams)
    }
  },
  watch: {
    destCountryId: {
      //监听当前地区值的变化,于与上方地区值进行了双向绑定
      deep: true, //深度监听
      handler() {
        //每当值省份值改变时其下地区值进行清空
        this.AddressCity = [];
        this.AddressTown = [];
        this.objectiveId = "";
        this.destWarehouseId = "";
        this.findByprovinceCode();
        if (this.destCountryId == "") {
          this.getAddressCity()
          this.getAddressTown()
        } else if (
          this.destCountryId != "" &&
          this.objectiveId == "" &&
          this.destWarehouseId == ""
        ) {
          this.getAddressTown()
        }
      },
    },
    objectiveId: {
      deep: true, //深度监听
      handler() {
        this.AddressTown = [];
        this.destWarehouseId = "";
        this.findBycityCode();

        if (
          this.objectiveId != "" &&
          this.destCountryId != "" &&
          this.destWarehouseId == ""
        ) {
          //获取当前城市值id,获取该城市下区域
        } else if (
          this.destCountryId == "" &&
          this.objectiveId == "" &&
          this.destWarehouseId == ""
        ) {
          this.getAddressTown()
        } else if (
          this.destCountryId != "" &&
          this.objectiveId == "" &&
          this.destWarehouseId == ""
        ) {
          this.findByprovinceCode();
          this.getAddressTown()
        }
      },
    },
    destWarehouseId: {
      deep: true, //深度监听
      handler() {
        if (
          this.objectiveId != "" &&
          this.destCountryId != "" &&
          this.destWarehouseId == ""
        ) {
          //获取当前城市值id,获取该城市下区域
          this.findBycityCode();
        } else if (
          this.destCountryId != "" &&
          this.objectiveId == "" &&
          this.destWarehouseId == ""
        ) {
          this.getAddressTown()
        }
      },
    },
  },
  activated(){
    // 要求保留页码 https://zentao.test.jdshangmen.com/bug-view-3079.html
    this.getList()
  },
  created() {
    this.getList();
    getProductAttrList().then(res => this.productAttrList = res.data)
    // getTradeCityList().then(res => this.tradeCityList = res.data)
    getWarehouseList().then(res => this.warehouseList = res.data)
    getChannelList().then(res => this.channelList = res.data)
    this.getAddressProvince()
    this.getAddressCity()
    this.getAddressTown()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getWarningCargoControlOrderPage(this.combinedQueryParams).then(response => {
        this.list = []
        // 直接更细数据,可能因为elTable的部分渲染产生bug,比如权限控制异常
        this.$nextTick( () => {
          this.list = response.data.list;
          this.total = response.data.total;
        })

        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.$nextTick(this.getList)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      // 执行导出
      this.$modal.confirm('是否确认导出所有订单数据项?').then(() => {
        this.exportLoading = true;
        return exportCargoControl(this.combinedQueryParams);
      }).then(response => {
        this.$message.success(this.$t('已加入导出队列,请稍后在下载日志中下载'))
        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.getList()
            })
    },
    // 批量复核
    batchReview(){
      this.$confirm(this.$t('确定复核选中的订单么?')).then(() => {
        return batchReview("orderIds=" + this.ids.join(','))
      }).then(() => {
        this.$message.success(this.$t('操作成功'))
        this.getList()
      })
    },
    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.getList()
    },
    onFallbackSuccess(){
      this.showFallbackOrder = null
      this.getList()
    },
    onTransferCargoSuccess(){
      this.showTransferCargoOrderId = null
      this.getList()
    },
    getAddressProvince() {
      getRegionList(1, 1).then(({ data }) => {
        this.AddressProvince = data;
      })
    },
    getAddressCity() {
      getRegionList(4, 4).then(({ data }) => {
        this.AddressCity = data;
      })
    },
    getAddressTown() {
      getRegionList(5, 5).then(({ data }) => {
        this.AddressTown = data;
      })
    },
    findByprovinceCode() {
      if (this.destCountryId != null && this.destCountryId != '') {
        //获取当前省份值id,获取该省份下城市 destCountryId provinceCode
        getRegionList(2, this.destCountryId).then(({ data }) => {
          this.AddressCity = data;
        })
      }
    },
    findBycityCode() {
      if (this.objectiveId != null && this.objectiveId != '') {
        //获取当前城市值id,获取该城市下区域
        getRegionList(3, this.objectiveId).then(({ data }) => {
          this.AddressTown = data;
        })
      }
    }
  }
};
</script>