<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px" class="search-z">
      <el-form-item :label="$t('订单号')" prop="orderNo">
        <el-input
          v-model.trim="noParam.value"
          clearable
          class="w-200"
          :placeholder="$t('请输入订单号')"
          @input="replaceSpace(noParam, 'value')"
          @keyup.enter.native="getList">
          <template slot="prepend">
            <dict-selector :type="DICT_TYPE.ORDER_QUERY_NO_FIELD" defaultable v-model="noParam.key" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('提单号')" prop="tidanNo">
        <el-input
          v-model.trim="noParam2.value"
          clearable
          class="w-200"
          :placeholder="$t('请输入提单号')"
          @input="replaceSpace(noParam2, 'value')"
          @keyup.enter.native="getList">
          <template slot="prepend">
            <dict-selector :type="DICT_TYPE.ORDER_QUERY_PROD_FIELD" defaultable v-model="noParam2.key" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('发货人')" prop="consignorKey">
        <el-input v-model.trim="queryParams.consignorKey" :placeholder="$t('发货人')" clearable @keyup.enter.native="getList" class="w-200"/>
      </el-form-item>
      <el-form-item :label="$t('收货人')" prop="consigneeKey">
        <el-input v-model.trim="queryParams.consigneeKey" :placeholder="$t('收货人')" clearable @keyup.enter.native="getList" class="w-200"/>
      </el-form-item>
      <el-form-item :label="$t('状态')" prop="pickStateList">
        <dict-selector :type="DICT_TYPE.ECW_RELEASE_STATUS" multiple v-model="queryParams.pickStateList" @keyup.enter.native="getList" clearable class="w-200" />
      </el-form-item>
      <el-form-item :label="$t('放货日期')">
        <el-date-picker v-model="dateCreateTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item :label="$t('发货人电话')" prop="consignorPhone" v-show="showSearch">
        <el-input v-model.trim="queryParams.consignorPhone" :placeholder="$t('发货人电话')" clearable @keyup.enter.native="getList" @input="queryParams.consignorPhone = queryParams.consignorPhone.replace(/\s+/g, '')" class="w-200"/>
      </el-form-item>
      <el-form-item :label="$t('收货人电话')" prop="consignorPhone" v-show="showSearch">
        <el-input v-model.trim="queryParams.consigneePhone" :placeholder="$t('收货人电话')" clearable @keyup.enter.native="getList" @input="queryParams.consigneePhone = queryParams.consigneePhone.replace(/\s+/g, '')" class="w-200"/>
      </el-form-item>
      <el-form-item :label="$t('复核日期')" v-show="showSearch">
        <el-date-picker v-model="checkTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item :label="$t('控货状态')" prop="cargoControlStatusList" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.CONTROL_GOODS_STATUS" multiple v-model="queryParams.cargoControlStatusList" clearable class="w-200" />
      </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" clearable class="w-200" />
      </el-form-item>
      <el-form-item :label="$t('运输方式')" prop="dynamicTransportIdList" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" multiple v-model="queryParams.dynamicTransportIdList" clearable class="w-200" />
      </el-form-item>
      <el-form-item :label="$t('始发仓')" prop="consignorPhone" v-show="showSearch">
        <el-select v-model="queryParams.startWarehouseIds" multiple :placeholder="$t('请选择始发仓')" clearable>
          <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="destCountryIds" v-show="showSearch">
        <el-select v-model="queryParams.destCountryIds" multiple :placeholder="$t('请选择目的国')" clearable>
          <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="destCityIds" v-show="showSearch">
        <el-select v-model="queryParams.destCityIds" multiple :placeholder="$t('请选择目的城市')" style="width: 200px" clearable>
          <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="shippingChannelIdList" v-show="showSearch">
        <el-select v-model="queryParams.shippingChannelIdList" multiple :placeholder="$t('请选择出货渠道')" clearable>
          <el-option v-for="item in channelList" :label="$l(item, 'name')" :value="item.channelId" :key="item.channelId"></el-option>
        </el-select>
      </el-form-item>
      <div class="flex pb-20" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ECW_BEGINTIME_TYPE_ENDTIME"  v-model="dateFilterType" defaultable class="w-200 mr-5" />
        <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="getList"> </el-date-picker>
      </div>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getList" :loading="loading" class="ml-10">{{ $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="15" v-if="statistics">
        <!-- 订单列表显示搜索条件对应箱数、仓库实测、收款方数、重量 -->
        {{ $t("合计：{totalNum}箱，{totalVolume}m³(测) {totalChargeVolume}m³(重) {totalWeight}KG(测), {totalChargeWeight}kg(收费)", statistics) }}
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" border @sort-change="sortChange">
      <el-table-column :label="$t('序号')" width="50px">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column :label="$t('订单号')" prop="orderNo" width="120px">
        <template slot-scope="scope">
          <router-link :to="`/order/detail?orderId=` + scope.row.orderId">{{ scope.row.orderNo }}</router-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('发货人编号')" prop="consignerNumber" width="90px">
        <template slot-scope="{ row }">
          <router-link :to="`/customer/query/${row.consignerId}`" class="link-type">
            {{ row.consignerNumber }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('收货人编号')" prop="consigneeNumber" width="90px">
        <template slot-scope="{ row }">
          <router-link :to="`/customer/query/${row.consigneeId}`" class="link-type">
            {{ row.consigneeNumber }}
          </router-link>
        </template>
      </el-table-column>

      <el-table-column :label="$t('收货人')" prop="consigneeName" width="120px"/>
      <el-table-column :label="$t('收货人电话')" prop="consigneePhone" width="140px">
        <template slot-scope="{ row }"> +{{ row.consigneeCountryCode }} {{ row.consigneePhone }} </template>
      </el-table-column>
      <el-table-column :label="$t('入仓箱数')" prop="sumNum" sortable="custom"  width="100px"></el-table-column>
      <el-table-column :label="$t('放货箱数')" prop="pickNum" sortable="custom" width="100px" ></el-table-column>
      <el-table-column :label="$t('体积') + '(m³)'" prop="pickVolume"></el-table-column>
      <el-table-column :label="$t('收费体积') + '(m³)'" prop="chargeVolume" width="100px"></el-table-column>
      <el-table-column :label="$t('重量') + '(KG)'" prop="pickWeight"></el-table-column>
      <el-table-column :label="$t('收费重量') + '(KG)'" prop="chargeWeight" width="100px"></el-table-column>
      <el-table-column :label="$t('状态')" prop="status">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.ECW_RELEASE_STATUS" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('备注')" prop="remarks"></el-table-column>
      <el-table-column :label="$t('操作人')" prop="operator" width="120px"></el-table-column>
      <el-table-column :label="$t('放货日期')" prop="createTime" sortable="custom" width="150px">
        <template slot-scope="{ row }">
          {{ row.createTime | parseTime }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('复核日期')" prop="checkTime" sortable="custom" width="150px">
        <template slot-scope="{ row }">
          {{ row.checkTime | parseTime }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('控货状态')" prop="cargoControlStatus">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.CONTROL_GOODS_STATUS" :value="row.cargoControlStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('始发仓')" prop="startTitleZh"></el-table-column>
      <el-table-column :label="$t('运输方式-渠道/目的地')" align="center" prop="transportId" width="200px">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="row.transportId" />
          <template v-if="row.channelName"> - {{ row.channelName }} </template>
          / {{ row.destCityTitleZh }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('卸柜/到仓时间')" prop="createTime" sortable="custom" width="150px">
        <template slot-scope="{ row }">
          {{ row.unloadTime | parseTime }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" width="300px">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status == 1" type="primary" size="mini" @click="edit(scope)">{{ $t("修改") }}</el-button>
          <el-button v-if="scope.row.status == 1" type="danger" size="mini" @click="cancelCargoPick(scope)">{{ $t("取消") }}</el-button>
          <el-button v-if="scope.row.status == 1" type="success" size="mini" @click="review(scope.row.id)">{{ $t("放货复核") }}</el-button>
          <el-button v-if="scope.row.status == 3" type="danger" size="mini" @click="fallback(scope)">{{ $t("反复核") }}</el-button>
          <el-button v-if="scope.row.status == 3" type="success" size="mini" @click="cargoControlPick(scope)">{{ $t("调货") }}</el-button>

          <el-button v-if="[2, 4, 5, 6].indexOf(scope.row.status) > -1" type="primary" size="mini" @click="showApprovalDetail(scope.row)">{{ $t("审核详情") }}</el-button>
          <el-button v-if="[2, 4, 5, 6].indexOf(scope.row.status) > -1" type="danger" size="mini" @click="cancelApproval(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" />

    <fallback v-if="fallbackIndex !== null" :order="detail" :index="fallbackIndex" @close="fallbackIndex = null" @success="onFallbackSuccess" />
    <edit v-if="editIndex !== null" @close="editIndex = null" :order="detail" :index="editIndex" @success="onEditSuccess" />
    <transfer-cargo v-if="cargoControlPickId !== null" :order-id="detail.orderId" :cargo-control-pick-id="cargoControlPickId" @close="cargoControlPickId = null" @success="onTransferCargoSuccess" />
    <cancel-cargo v-if="!!cancelCargoPickId" :order="detail" :cargo-control-pick-id="cancelCargoPickId" @close="cancelCargoPickId = null" @success="onCancelCargoSuccess" />

  </div>
</template>
<script>
import edit from "./components/CargoControlEdit.vue"
import {
  review,
  cancel,
  cancelApproval,
  getCargoControlDetailListPage,
  getPickRleaseInfo,
  statisticsOrderControl
} from "@/api/ecw/orderCargoControl"
import { parseTime } from "@/utils/ruoyi"
import Fallback from "./components/Fallback"
import TransferCargo from "@/views/ecw/order/components/TransferCargo"
import Template from "@/views/cms/template/index.vue"
import { getWarehouseList } from "@/api/ecw/warehouse"
import { getChannelList } from "@/api/ecw/channel"
import { getRegionList } from "@/api/ecw/order"
import CancelCargo from "@/views/ecw/order/components/CancelCargo.vue"

export default {
  filters: { parseTime },
  components: { CancelCargo, Template, edit, Fallback, TransferCargo },
  data() {
    return {
      detail: null,
      formData: {},
      rules: {},
      editIndex: null, // 修改索引
      fallbackIndex: null, // 反复核索引
      cargoControlPickId: null, // 调货ID
      cancelCargoPickId: null ,// 取消返货ID
      queryParams: {
        page: 1,
        rows: 10,
        packageTypeArr: [],
        channelIds: [],
        goodsTypes: [],
        field: null,
        sort: null,
      },
      list: [],
      loading: false,
      // 显示搜索条件
      showSearch: false,
      // 编号搜索条件
      noParam: {
        key: "numberKey",
        value: ""
      },
      noParam2: {
        key: "prodKey",
        value: ""
      },
      dateCreateTime: [],
      checkTime: [],
      exportWarehouseList: [],
      channelList: [],
      AddressProvince: [],
      AddressCity: [],
      dateFilterType: "", //日期筛选类别
      dateFilter: [], //筛选日期
      countryIdList: null,
      destCityIdList: null,
      destWarehouseIdList: null,
      statistics: null, // 统计数据
      // 总条数
      total: 0,
      sortProp: null,
      sortType: null,
    }
  },
  created() {
    const year = new Date().getFullYear();
    const firstDay = new Date(year, 0, 1); // 第一天，月份从0开始，所以是0
    const lastDay = new Date(year, 11, 31); // 最后一天，月份从0开始，所以是11
    let year1 = firstDay.getFullYear(); //得到年份
    let month1 = (firstDay.getMonth() + 1).toString().padStart(2, "0"); //得到月份
    let day1 = firstDay.getDate().toString().padStart(2, "0"); //得到日期
    let year2 = lastDay.getFullYear(); //得到年份
    let month2 = (lastDay.getMonth() + 1).toString().padStart(2, "0"); //得到月份
    let day2 = lastDay.getDate().toString().padStart(2, "0"); //得到日期
    this.dateCreateTime = [year1+'-'+month1+'-'+day1, year2+'-'+month2+'-'+day2]
    this.getList()
    getWarehouseList().then(({ data }) => {
      this.exportWarehouseList = data.filter((item) => item.tradeType == '2' || item.type == '3')
    })
    getChannelList().then((res) => (this.channelList = res.data))
    getRegionList(1, 1).then(({ data }) => {
      this.AddressProvince = data
    })
    getRegionList(4, 4).then(({ data }) => {
      this.AddressCity = data
    })
  },
  methods: {
    // 自动去除空格
    replaceSpace(obj, field) {
      obj[field] = obj[field].replace(/\s+/g, "")
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      let timeParams = {}
      if (this.dateFilterType && this.dateFilter) {
        timeParams["begin" + this.dateFilterType] = this.dateFilter[0]
        timeParams["end" + this.dateFilterType] = this.dateFilter[1]
      }
      // 处理查询参数
      let params =Object.assign({}, this.queryParams, timeParams)
      if (this.noParam.value) {
        params[this.noParam.key] = this.noParam.value
      }
      if (this.noParam2.value) {
        params[this.noParam2.key] = this.noParam2.value
      }

      this.addBeginAndEndTime(params, this.dateCreateTime, 'releaseTime');
      this.addBeginAndEndTime(params, this.checkTime, 'checkTime');
      // 执行查询
      getCargoControlDetailListPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
      statisticsOrderControl(params).then(response => {
        this.statistics = response.data
      });
    },
    sortChange(obj) {
      if(obj.order==null) {
        this.queryParams.field = null
      } else {
        this.queryParams.field = obj.prop;   //排序字段名称
        this.queryParams.sort = obj.order=="ascending"?0:1;   //排序方式
      }
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams = {
        page: 1,
        rows: 10
      }
      this.noParam.value = ""
      this.noParam2.value = ""
      this.dateFilter = []
      this.checkTime = []
      this.dateCreateTime = []
      this.getList()
    },
    review(id) {
      this.$confirm(this.$t("已核实放货信息，确认放货？"))
        .then((res) => {
          return review(id)
        })
        .then((res) => {
          this.$message.success(this.$t("操作成功"))
          this.getList()
        })
    },
    unReview() {},
    cancel(id) {
      this.$confirm(this.$t("确定取消这条放货么？"))
        .then((res) => {
          return cancel(id)
        })
        .then((res) => {
          this.$message.success(this.$t("操作成功"))
          this.getList()
        })
    },
    onEditSuccess() {
      console.log("onEditSuccess")
      this.getList()
      this.editIndex = null
    },
    onFallbackSuccess() {
      this.fallbackIndex = null
      this.getList()
    },
    // 查看审核详情
    showApprovalDetail(row) {
      getPickRleaseInfo(row.orderId).then((res) => {
        this.detail = res.data
        this.$router.push("/bpm/process-instance/detail?id=" + this.getApproval(row.id,"formId"))
      })
    },
    // 取消审核
    cancelApproval(row) {
      this.$confirm(this.$t("确定取消此申请么？"))
        .then((res) => {
          getPickRleaseInfo(row.orderId).then((res) => {
            this.detail = res.data
            let approvalId = this.getApproval(row.id)
            return cancelApproval(approvalId, { reason: this.$t("无") })
          })
        })
        .then((res) => {
          this.$message.success(this.$t("操作成功"))
          this.getList()
        })
    },
    // 根据id查找审核id
    getApproval(id, field = "orderApprovalId") {
      if (!this.detail.orderApprovalBackVOList || !this.detail.orderApprovalBackVOList.length) {
        this.$message.error(this.$t("未找到审批ID"))
        Promise.reject(this.$t("未找到审批ID"))
      }
      let item = this.detail.orderApprovalBackVOList.find((item) => {
        let details = JSON.parse(item.details)
        return details.cargoControlPickId == id && details.applyStatus == 1
      })
      console.log({ item })
      return item[field]
    },
    onTransferCargoSuccess() {
      this.cargoControlPickId = null
      this.getList()
    },
    onCancelCargoSuccess() {
      this.cancelCargoPickId = null
      this.getList()
    },
    edit(scope) {
      getPickRleaseInfo(scope.row.orderId).then((res) => {
        this.detail = res.data
        this.editIndex = scope.$index
      })
    },
    cancelCargoPick(scope) {
      getPickRleaseInfo(scope.row.orderId).then((res) => {
        this.detail = res.data
        this.cancelCargoPickId = scope.row.id
      })
    },
    fallback(scope) {
      getPickRleaseInfo(scope.row.orderId).then((res) => {
        this.detail = res.data
        this.fallbackIndex = scope.$index
      })
    },
    cargoControlPick(scope) {
      getPickRleaseInfo(scope.row.orderId).then((res) => {
        this.detail = res.data
        this.cargoControlPickId = scope.row.id
      })
    }
  }
}
</script>
