<template>
  <div>
    <el-form ref="arrivalForm" :rules="rules" :model="airArrivalInfo" label-width="120px">
      <el-form-item :label="$t('到港情况')" prop="arriveType">
        <el-radio-group v-model="airArrivalInfo.arriveType">
          <el-radio :label="0">{{ $t('一次到港') }}</el-radio>
          <el-radio :label="1">{{ $t('多次到港') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('选择订单')" prop="arriveOrderIdList" v-show="airArrivalInfo.arriveType == 1">
        <span v-for="order in selectOrders" :key="order.id">{{ order.orderNo }} </span>
        <el-button type="primary" @click="orderdialogVisible = true">{{ $t('订单列表') }}</el-button>
      </el-form-item>
      <el-form-item :label="$t('已到港订单')" v-show="airArrivalInfo.arriveType == 1">
        <span v-for="order in airArrivalInfo.arrivalOrderList" :key="order.id">{{ order.orderNo }} </span>
      </el-form-item>

      <el-form-item v-if="dtRealHeadTimeFlag || airArrivalInfo.arriveType == 1" :label="$t('实际二程起飞时间')" prop="actSecondTime">
        <template slot="label" slot-scope="scope"> <span style="color: red">*</span>{{ $t('实际二程起飞时间') }} </template>
        <el-date-picker type="datetime" :placeholder="$t('请选择日期')" v-model="airArrivalInfo.actSecondTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('预计到港时间')" prop="estTime">
        <el-date-picker type="datetime" :placeholder="$t('请选择日期')" v-model="airArrivalInfo.estTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('实际到港时间')" prop="actTime">
        <template slot="label" slot-scope="scope"> <span style="color: red">*</span>{{ $t('实际到港时间') }} </template>
        <el-date-picker type="datetime" :placeholder="$t('请选择日期')" v-model="airArrivalInfo.actTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
    </el-form>

    <el-row class="operate-button">
      <el-button type="primary" @click="onSubmit(1)">{{ $t('保存') }}</el-button>
      <el-button type="success" @click="onSubmit(2)">{{ $t('提交') }}</el-button>
      <el-button @click="cancel">{{ $t('关闭') }}</el-button>
      <el-button type="primary" @click="exceptionReg" :disabled="!showMsg">{{ $t('异常登记') }}</el-button>
    </el-row>

    <!-- 对话框 -->
    <el-dialog custom-class="shipping-dialog" :title="$t('票异常')" :visible.sync="dialogVisible" width="700px" :modal-append-to-body="false" append-to-body destroy-on-close>
      <regError @closeDialog="regCloseDialog" v-bind="$attrs" />
    </el-dialog>
    <!-- 订单列表 -->
    <el-dialog width="70%" :title="$t('选择订单')" :visible.sync="orderdialogVisible" :modal-append-to-body="false" append-to-body destroy-on-close>
      <el-row :gutter="10">
        <el-col :span="7">
          {{ $t('关键字：') }}
          <el-input style="width: 300px" v-model="searchForm.orderKeyword" :placeholder="$t('请输入订单号、提单号、唛头')" />
        </el-col>
        <el-col :span="5">
          {{ $t("到港状态") }}
          <el-select v-model="searchForm.orderPortStatus">
            <el-option :value="0" :label="$t('未到港')" />
            <el-option :value="1" :label="$t('已到港')" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="searchOrderList"> {{ $t('查询') }}</el-button>
          <el-button type="primary" @click="reloafSearch"> {{ $t('重置') }}</el-button>
        </el-col>
      </el-row>
      <div style="margin-top: 10px">
        <el-button type="primary" @click="multipleSelect">
          {{ $t('批量选择') }}
        </el-button>
      </div>
      <el-table style="margin-top: 10px" :data="statusOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column :label="$t('序号')" type="index" width="50"> </el-table-column>
        <el-table-column :label="$t('订单号')" prop="orderNo" />
        <el-table-column :label="$t('唛头')" prop="marks" />
        <el-table-column :label="$t('提单号')" prop="tidanNo" />
        <el-table-column width="150" :label="$t('总箱数/入仓箱数')">
          <template slot-scope="scope"> {{ scope.row.totalNum }}/{{ scope.row.sumNum }} </template>
        </el-table-column>
        <el-table-column :label="$t('体积/重量')" prop="">
          <template slot-scope="scope"> {{ scope.row.sumVolume }}/{{ scope.row.sumWeight }} </template>
        </el-table-column>
        <el-table-column :label="$t('到港状态')" prop="arrival" />
        <el-table-column :label="$t('控货')">
          <template slot-scope="scope">
            {{ cargoControlStatus[scope.row.cargoControlStatus] }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('订单状态')" prop="statusMsg" />
        <el-table-column :label="$t('操作')">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="selectOrder(scope.row)">{{ $t('选择') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import regError from '../../regError'
import dayjs from 'dayjs'
import { arrivalCreate } from '@/api/ecw/boxSeaAir'
import { shipmentOrderList } from '@/api/ecw/boxAir'
import { formatDateStr, serviceMsg, formatDate } from '../utils'

/**
 * 到港
 */
export default {
  name: 'arrival',
  inheritAttrs: false,
  components: {
    regError
  },
  data() {
    var validateActSecondTime = (rule, value, callback) => {
      if (!value && (this.airArrivalInfo.arriveType == 0 || (this.airArrivalInfo.arriveType == 1 && this.airArrivalInfo.arriveOrderIdList.length > 0))) {
        callback(new Error(this.$t('必填')))
      }
      callback()
    }
    var validateActTime = (rule, value, callback) => {
      if (!value && (this.airArrivalInfo.arriveType == 0 || (this.airArrivalInfo.arriveType == 1 && this.airArrivalInfo.arriveOrderIdList.length > 0))) {
        callback(new Error(this.$t('必填')))
      }
      callback()
    }
    return {
      // 到港对象
      airArrivalInfo: {},
      // 校验
      rules: {
        actSecondTime: [{ validator: validateActSecondTime, trigger: 'change' }],
        actTime: [{ validator: validateActTime, trigger: 'change' }]
      },
      // 弹窗配置
      dialogVisible: false,
      // 提示消息
      showMsg: false,
      inspectionTimeArrival: this.getDictDatas(this.DICT_TYPE.BOX_INSPECTION_TIME_ARRIVAL)[0].value,
      dtRealHeadTimeFlag: false,
      orderList: [],
      arrivalOrderList: [],
      orderdialogVisible: false,
      selectOrders: [],
      multipleSelectOrder: [],
      cargoControlStatus: [this.$t('控货中'), this.$t('已放完货'), this.$t('部分控货')],
      searchForm: {
        orderKeyword: null,
        orderPortStatus: null
      },
      searchFormFilter: {}
    }
  },
  created() {
    const voName = this.$attrs.currNode.voName
    let oldData = { ...this.$attrs.shipmentObj[voName] }
    oldData = formatDateStr(oldData, ['actSecondTime', 'estTime', 'actTime'], 'YYYY-MM-DD HH:mm:ss')
    this.airArrivalInfo = oldData
    if (this.$attrs.shipmentObj['bookAirInfo'].voyage && this.$attrs.shipmentObj['bookAirInfo'].voyage == 2) {
      this.dtRealHeadTimeFlag = true
    }
    if (!this.airArrivalInfo.arriveType) this.$set(this.airArrivalInfo, 'arriveType', 0)
    this.$set(this.airArrivalInfo, 'arriveOrderIdList', [])
    this.arrivalOrderList = this.$attrs.shipmentObj.airArrivalInfo ? this.$attrs.shipmentObj.airArrivalInfo.arrivalOrderList : []
    shipmentOrderList(this.$attrs.shipmentObj.id).then((r) => {
      this.orderList = r.data ?? []
    })
  },
  computed: {
    statusOrderList() {
      let data = []
      this.orderList.forEach((item) => {
        let json = {
          orderId: item.orderId,
          orderNo: item.orderNo,
          tidanNo: item.tidanNo,
          marks: item.marks,
          sumNum: item.sumNum,
          totalNum: item.totalNum,
          sumVolume: item.sumVolume,
          sumWeight: item.sumWeight,
          statusMsg: item.statusMsg,
          cargoControlStatus: item.cargoControlStatus
        }
        let index = this.arrivalOrderList ? this.arrivalOrderList.findIndex((p) => p.orderId == item.orderId) : -1
        if (index != -1) {
          json.arrival = this.$t('已到港')
          json.arrivalValue = 1;
        } else {
          json.arrival = this.$t('未到港')
          json.arrivalValue = 0;
        }
        data.push(json)
      })
      if (this.searchFormFilter.orderKeyword && this.searchFormFilter.orderKeyword != '') {
        data = data.filter((item) => {
          return (item.orderNo && item.orderNo.indexOf(this.searchFormFilter.orderKeyword) > -1) || (item.tidanNo && item.tidanNo.indexOf(this.searchFormFilter.orderKeyword) > -1) || (item.marks && item.marks.indexOf(this.searchFormFilter.orderKeyword) > -1)
        })
      }
      if (this.searchFormFilter.orderPortStatus != null) {
        data = data.filter((item) => {
          return item.arrivalValue == this.searchFormFilter.orderPortStatus
        })
      }

      return data
    }
  },
  watch: {
    // 实际二程起飞时间
    'airArrivalInfo.actSecondTime'(val) {
      this.compareDate(this.getHeadTravelTime(), val)
    },

    'airArrivalInfo.estTime'(val) {
      this.compareDate(this.airArrivalInfo.actTime, val)
    },

    'airArrivalInfo.actTime'(val) {
      this.compareDate(this.airArrivalInfo.estTime, val)
    },

    'airArrivalInfo.arriveType'(val) {
      if (val == 1) {
        this.$set(this.airArrivalInfo, 'actSecondTime', null)
        this.$set(this.airArrivalInfo, 'estTime', null)
        this.$set(this.airArrivalInfo, 'actTime', null)
      } else {
        let oldData = { ...this.$attrs.shipmentObj[this.$attrs.currNode.voName] }
        oldData = formatDateStr(oldData, ['actSecondTime', 'estTime', 'actTime'], 'YYYY-MM-DD HH:mm:ss')
        this.$set(this.airArrivalInfo, 'actSecondTime', oldData.actSecondTime)
        this.$set(this.airArrivalInfo, 'estTime', oldData.estTime)
        this.$set(this.airArrivalInfo, 'actTime', oldData.actTime)
      }
    }
  },
  methods: {
    searchOrderList() {
      this.searchFormFilter = JSON.parse(JSON.stringify(this.searchForm))
    },
    reloafSearch() {
      this.searchForm = {}
      this.searchOrderList()
    },
    selectOrder(val) {
      this.selectOrders = []
      this.selectOrders.push(val)
      let arr = this.arrivalOrderList.find((item) => item.orderId == val.orderId)
      console.log(arr,'arr');
      if (arr) {
        console.log(formatDate(arr.actSecondTime),arr.actSecondTime);
        this.$set(this.airArrivalInfo, 'actSecondTime', formatDate(arr.actSecondTime))
        this.$set(this.airArrivalInfo, 'estTime', formatDate(arr.estTime))
        this.$set(this.airArrivalInfo, 'actTime', formatDate(arr.actTime))
      }

      this.orderdialogVisible = false
      this.airArrivalInfo.arriveOrderIdList.push(val.orderId)
    },
    handleSelectionChange(val) {
      this.multipleSelectOrder = val
    },
    // 批量选择
    multipleSelect() {
      if (this.multipleSelectOrder.length == 0) {
        this.$message.error(this.$t('请先选择订单'))
        return
      }
      this.selectOrders = []
      this.selectOrders = this.multipleSelectOrder
      if (this.multipleSelectOrder.length == 1) {
        let arr = this.arrivalOrderList.find((item) => item.orderId == this.multipleSelectOrder[0].orderId)
        if (arr) {
          this.$set(this.airArrivalInfo, 'actSecondTime', formatDate(arr.actSecondTime))
          this.$set(this.airArrivalInfo, 'estTime', formatDate(arr.estTime))
          this.$set(this.airArrivalInfo, 'actTime', formatDate(arr.actTime))
        }
      } else {
        this.$set(this.airArrivalInfo, 'actSecondTime', null)
        this.$set(this.airArrivalInfo, 'estTime', null)
        this.$set(this.airArrivalInfo, 'actTime', null)
      }
      this.orderdialogVisible = false
      this.airArrivalInfo.arriveOrderIdList = this.multipleSelectOrder.map((item) => item.orderId)
    },
    regCloseDialog(type) {
      this.dialogVisible = false
      if (type === 'error') {
        this.$emit('getBoxInfo')
      }
    },
    // 获取实际二程起飞时间
    getHeadTravelTime() {
      const { shippingInfo } = this.$attrs.shipmentObj
      if (shippingInfo) {
        return dayjs(shippingInfo.realHeadTravelTime).format('YYYY-MM-DD HH:mm:ss')
      }
      return null
    },
    // 获取预计到港时间
    getExpectedTime() {
      const { shippingInfo } = this.$attrs.shipmentObj
      if (shippingInfo) {
        return dayjs(shippingInfo.dtEstArrivalTime).format('YYYY-MM-DD HH:mm:ss')
      }
      return null
    },
    // 时间比较
    compareDate(expectedTime, apConfirmTime) {
      this.showMsg = false
      let date1 = null,
        date2 = null
      if (expectedTime) date1 = dayjs(expectedTime)
      if (apConfirmTime) date2 = dayjs(apConfirmTime)
      if (date1 && date2) {
        const days = date2.diff(date1, 'day')
        if (days > this.inspectionTimeArrival) {
          this.showMsg = true
        }
      }
    },
    // 异常登记
    exceptionReg() {
      this.dialogVisible = true
    },
    /** 提交 */
    onSubmit(operateType) {
      this.$refs['arrivalForm'].validate((valid) => {
        if (valid) {
          arrivalCreate({
            ...this.airArrivalInfo,
            shipmentId: this.$attrs.shipmentObj.id,
            operateType
          }).then((res) => {
            serviceMsg(res, this).then(() => {
              this.cancel('submit')
            })
          })
        }
      })
    },
    /** 取消 */
    cancel(type) {
      this.$emit('closeDialog', type)
    }
  }
}
</script>

<style lang="scss" scoped>
.message-area {
  margin: 0;
  color: red;
}
</style>
