<template>
  <div>
    <el-form ref="cusClearanceForm" :rules="rules" :model="cusClearanceObj" label-width="120px">
      <el-form-item :label="$t('清关情况')" prop="arriveType">
        <el-radio-group v-model="cusClearanceObj.clearanceType">
          <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="clearanceOrderIdList" v-show="cusClearanceObj.clearanceType == 1">
        <el-select v-model="cusClearanceObj.clearanceOrderIdList" multiple filterable clearable reserve-keyword :filter-method="filterOrder" :placeholder="$t('请输入订单号、提单号、唛头')" @change="selectOrderId">
          <el-option v-for="item in statusOrderList" :key="item.orderId" :label="item.orderNo + ' ' + item.clear + ' ' + item.arrival" :value="item.orderId"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('已清关订单')" v-show="cusClearanceObj.clearanceType == 1">
        <span v-for="order in cusClearanceObj.clearanceOrderList" :key="order.id">{{ order.orderNo }} </span>
      </el-form-item>

      <div v-if="cusClearanceObj.clearanceOrderIdList.length > 0">
        <el-form ref="airArrivalForm" :rules="airArrivalrules" :model="airArrivalInfo" label-width="120px">
          <el-form-item :label="$t('实际二程起飞时间')" prop="actSecondTime">
            <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">
            <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>
      </div>

      <el-form-item :label="$t('预计清关时间')" prop="clEstTime">
        <el-date-picker type="datetime" :placeholder="$t('请选择日期')" v-model="cusClearanceObj.clEstTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('清关时间')" prop="clClearTime">
        <el-date-picker type="datetime" :placeholder="$t('请选择日期')" v-model="cusClearanceObj.clClearTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        <p class="message-area" v-show="showMsg">{{ $t('清关时间与预计时间不符，如有异常请登记') }}</p>
      </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="dialogVisible = false" v-bind="$attrs" />
    </el-dialog>
  </div>
</template>

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

/**
 * 清关
 */
export default {
  name: 'cusClearance',
  inheritAttrs: false,
  components: {
    regError
  },
  data() {
    return {
      // 清关对象
      cusClearanceObj: {},
      // 校验
      rules: {
        clEstTime: [{ required: true, message: this.$t('必填'), trigger: 'change' }],
        clClearTime: [{ required: true, message: this.$t('必填'), trigger: 'change' }]
      },
      airArrivalrules: {
        actSecondTime: [{ required: true, message: this.$t('必填'), trigger: 'change' }],
        actTime: [{ required: true, message: this.$t('必填'), trigger: 'change' }]
      },
      // 弹窗配置
      dialogVisible: false,
      // 提示消息
      showMsg: false,
      orderList: [],
      orderListFilter: [],
      arrivalOrderList: [],
      clearanceOrderList: [],
      airArrivalInfo: {}
    }
  },
  created() {
    const voName = this.$attrs.currNode.voName
    let oldData = { ...this.$attrs.shipmentObj[voName] }
    oldData = formatDateStr(oldData, ['clEstTime'])
    oldData = formatDateStr(oldData, ['clClearTime'], 'YYYY-MM-DD HH:mm:ss')
    this.cusClearanceObj = oldData
    if (!this.cusClearanceObj.clearanceType) this.$set(this.cusClearanceObj, 'clearanceType', 0)
    this.$set(this.cusClearanceObj, 'clearanceOrderIdList', [])
    if (this.$attrs.shipmentObj.airArrivalInfo.arrivalOrderList) this.arrivalOrderList = this.$attrs.shipmentObj.airArrivalInfo.arrivalOrderList
    if (this.$attrs.shipmentObj.clearanceInfo.clearanceOrderList) this.clearanceOrderList = this.$attrs.shipmentObj.clearanceInfo.clearanceOrderList
    shipmentOrderList(this.$attrs.shipmentObj.id).then((r) => {
      this.orderList = r.data
      this.orderListFilter = r.data
    })
  },
  watch: {
    // 预计清关时间
    'cusClearanceObj.clEstTime'(val) {
      this.compareDate(val, this.cusClearanceObj.clClearTime)
    },
    // 清关时间
    'cusClearanceObj.clClearTime'(val) {
      this.compareDate(this.cusClearanceObj.clEstTime, val)
    },
    'cusClearanceObj.clearanceType'(val) {
      if (val == 1) {
        this.$set(this.cusClearanceObj, 'clEstTime', null)
        this.$set(this.cusClearanceObj, 'clClearTime', null)
      } else {
        let oldData = { ...this.$attrs.shipmentObj[this.$attrs.currNode.voName] }
        oldData = formatDateStr(oldData, ['clEstTime', 'clClearTime'], 'YYYY-MM-DD HH:mm:ss')
        this.$set(this.cusClearanceObj, 'clClearTime', oldData.clClearTime)
        this.$set(this.cusClearanceObj, 'clEstTime', oldData.clEstTime)
      }
    }
  },
  computed: {
    statusOrderList() {
      let data = []
      this.orderListFilter.forEach((item) => {
        let json = {
          orderId: item.orderId,
          orderNo: item.orderNo,
          tidanNo: item.tidanNo,
          marks: item.marks
        }
        let clearindex = this.cusClearanceObj.clearanceOrderList ? this.cusClearanceObj.clearanceOrderList.findIndex((p) => p.orderId == item.orderId) : -1
        if (clearindex != -1) {
          json.clear = this.$t('已清关')
        } else {
          json.clear = this.$t('未清关')
        }
        let arrivalindex = this.arrivalOrderList ? this.arrivalOrderList.findIndex((p) => p.orderId == item.orderId) : -1
        if (arrivalindex != -1) {
          json.arrival = this.$t('已到港')
        } else {
          json.arrival = this.$t('未到港')
        }
        data.push(json)
      })
      return data
    }
  },
  methods: {
    formatDate,
    filterOrder(val) {
      if (val != '') {
        this.orderListFilter = this.orderList.filter((item) => {
          return item.orderNo&&item.orderNo.indexOf(val) > -1 || item.tidanNo&&item.tidanNo.indexOf(val) > -1 || item.marks&&item.marks.indexOf(val) > -1
        })
      } else {
        this.orderListFilter = this.orderList
      }
    },
    selectOrderId(val) {
      if (val.length == 1) {
        let arr = this.arrivalOrderList.find((item) => item.orderId == val[0])
        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))
        }
        let clear = this.clearanceOrderList.find((item) => item.orderId == val[0])
        if(clear){
          this.$set(this.cusClearanceObj, 'clEstTime', formatDate(clear.clEstTime))
          this.$set(this.cusClearanceObj, 'clClearTime', formatDate(clear.clClearTime))
        }
      } else {
        this.$set(this.airArrivalInfo, 'actSecondTime', null)
        this.$set(this.airArrivalInfo, 'estTime', null)
        this.$set(this.airArrivalInfo, 'actTime', null)
        this.$set(this.cusClearanceObj, 'clEstTime', null)
        this.$set(this.cusClearanceObj, 'clClearTime', null)
      }
    },
    getClAgent(type) {
      const agentId = this.$attrs.shipmentObj.agentInfo.agentId
      if (type === 'label') {
        const selected = this.$attrs.allSupplier.find((item) => item.id === agentId)
        return this.$l(selected, 'company') ?? agentId
      }
      return agentId
    },
    // 时间比较
    compareDate(clEstTime, clClearTime) {
      this.showMsg = false
      let date1 = null,
        date2 = null
      if (clEstTime) date1 = dayjs(clEstTime)
      if (clClearTime) date2 = dayjs(clClearTime)
      if (date1 && date2 && !date2.isSame(date1)) {
        this.showMsg = true
      }
    },
    // 异常登记
    exceptionReg() {
      this.dialogVisible = true
    },
    /** 提交 */
    onSubmit(operateType) {
      this.$refs['cusClearanceForm'].validate((valid) => {
        if (valid) {
          if (this.cusClearanceObj.clearanceType == 1 && this.cusClearanceObj.clearanceOrderIdList.length > 0) {
            this.$refs['airArrivalForm'].validate((arrvalid) => {
              if (arrvalid) {
                updateOrderArrival({
                  ...this.airArrivalInfo,
                  shipmentId: this.$attrs.shipmentObj.id,
                  orderIdList: this.cusClearanceObj.clearanceOrderIdList
                }).then(() => {
                  clearanceCreate({
                    ...this.cusClearanceObj,
                    shipmentId: this.$attrs.shipmentObj.id,
                    clAgentId: this.getClAgent(),
                    operateType
                  }).then((res) => {
                    serviceMsg(res, this).then(() => {
                      this.cancel('submit')
                    })
                  })
                })
              }
            })
          } else {
            clearanceCreate({
              ...this.cusClearanceObj,
              shipmentId: this.$attrs.shipmentObj.id,
              clAgentId: this.getClAgent(),
              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>
