/*
 * @Author: Badguy
 * @Date: 2022-03-04 14:45:03
 * @LastEditTime: 2022-06-16 10:51:52
 * @LastEditors: your name
 * @Description: 航站视图通用表单部分
 * have a nice day!
 */

import { parseTime } from '@/utils'
// const defaultStartTime = new Date(new Date(new Date().toLocaleDateString()).getTime())
// const defaultEndTime = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
const defaultDate = parseTime(new Date(), '{y}-{m}-{d}')
const dateValidator = (rule, value, callback) => {
  if (value && value[0] && value[1]) {
    callback()
  } else {
    callback(new Error('请选择航班日期'))
  }
}

export default {
  data () {
    return {
      formData: {
        // 搜索表单数据
        currentAirport: [],
        relatedAirport: [],
        inboundCarrier: [],
        outgoingAirline: [],
        craftType: [],
        flightAttr: [],
        flightDate: [defaultDate, defaultDate],
        // startDate: defaultDate,
        // endDate: defaultDate,
        search: ''
      },
      dateRangePickerOptions: {
        onPick: this.dateRangePickHandler,
        disabledDate: this.dateRangeDisabled
      },
      currentAirportList: [],
      relatedAirportList: [],
      carrierList: [],
      craftTypeList: [],
      flightAttrList: [],
      currentAirportProps: {
        // multiple: true,
        checkStrictly: true,
        expandTrigger: 'hover',
        value: 'code3',
        label: 'name',
        children: 'builds'
      },
      relatedAirportProps: {
        multiple: true,
        value: 'code3',
        label: 'name'
      },
      carrierProps: {
        multiple: true,
        value: 'code2',
        label: 'name'
      },
      craftTypeProps: {
        multiple: true,
        value: 'code3',
        label: 'name'
      },
      flightAttrProps: {
        multiple: true,
        value: 'code',
        label: 'name'
      },
      // 表单规则
      rules: {
        currentAirport: [{ required: true, message: '请选择当前机场', trigger: ['change', 'blur'] }],
        // startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        // endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
        flightDate: [{ validator: dateValidator, trigger: ['change', 'blur'] }]
      }
    }
  },
  computed: {
    currentAirport () {
      return this.getSingleData(this.formData.currentAirport)
    },
    relatedAirport () {
      return this.formData.relatedAirport.map(item => item[0])
    },
    inboundCarrier () {
      return this.formData.inboundCarrier.map(item => item[0])
    },
    outgoingAirline () {
      return this.formData.outgoingAirline.map(item => item[0])
    },
    craftType () {
      return this.formData.craftType.map(item => item[0])
    },
    flightAttr () {
      return this.formData.flightAttr.map(item => item[0])
    },
    startDate () {
      // return parseTime(this.formData.startDate).split(' ')[0]
      // return this.formData.startDate
      return this.formData.flightDate[0]
    },
    endDate () {
      // return parseTime(this.formData.endDate).split(' ')[0]
      // return this.formData.endDate
      return this.formData.flightDate[1]
    }
  },
  watch: {
    'formData.flightDate': {
      handler (val) {

        if (val === null) {
          this.formData.flightDate = ['', '']
        }
      },
      deep: true
    }
  },
  methods: {
    dateRangePickHandler ({ maxDate, minDate }) {
      if (!maxDate) {
        this.pickedDate = minDate
      } else {
        this.pickedDate = null
      }
    },
    dateRangeDisabled (date) {
      return this.pickedDate ? Math.abs(date - this.pickedDate) > 2 * 24 * 60 * 60 * 1000 : false
    },
    // 机场数据处理（多选）
    getMultipleData (arr) {
      const newArr = []
      arr.length &&
        arr.forEach(airport => {
          const temp = this._.cloneDeep(this.currentAirportList.find(airport1 => airport1.code3 === airport[0]))
          if (temp) {
            temp.builds = airport[1] ? [{ name: airport[1] }] : []
            const item = newArr.find(item => item.code3 === temp.code3)
            if (item) {
              item.builds.push(...temp.builds)
            } else {
              newArr.push(temp)
            }
          }
        })
      return newArr
    },
    // 机场数据处理（单选）
    getSingleData (arr) {
      const newArr = []
      if (arr.length > 0) {
        const temp = this._.cloneDeep(this.currentAirportList.find(airport1 => airport1.code3 === arr[0]))
        if (temp) {
          temp.builds = arr[1] ? [{ name: arr[1] }] : []
          newArr.push(temp)
        }
      }
      return newArr
    },
    // 清除表单数据
    formClear (range) {
      if (range === 'all') {
        this.formData.currentAirport = []
        this.currentAirportList = []
      }
      this.formData.relatedAirport = []
      this.relatedAirportList = []
      this.formData.inboundCarrier = []
      this.formData.outgoingAirline = []
      this.carrierList = []
      this.formData.craftType = []
      this.craftTypeList = []
      this.formData.flightAttr = []
      this.flightAttrList = []
    },
    // 当前机场变更
    setCurrentAirport (data) {
      this.formClear()
      if (data.length === 0) {
        return
      }
      const params = {
        currentAirport: this.currentAirport,
        startDate: this.startDate,
        endDate: this.endDate
      }
      this.getFormData(params)
    },
    // 日期限制
    // startDateChangeHandler(val) {
    //   if (!val || !this.endDate) {
    //     return
    //   }
    //   const startDate = new Date(val)
    //   const endDate = new Date(this.endDate)
    //   if (startDate > endDate) {
    //     this.formData.endDate = ''
    //     this.$message.info('结束时间不能早于开始时间，请重新选择')
    //   } else if (endDate - startDate > 2 * 24 * 60 * 60 * 1000) {
    //     this.formData.endDate = ''
    //     this.$message.info('时间跨度不能超过三天，请重新选择')
    //   } else {
    //     this.getTableData()
    //   }
    // },
    // endDateChangeHandler(val) {
    //   if (!val || !this.startDate) {
    //     return
    //   }
    //   const startDate = new Date(this.startDate)
    //   const endDate = new Date(val)
    //   if (startDate > endDate) {
    //     this.formData.startDate = ''
    //     this.$message.info('开始时间不能晚于结束时间，请重新选择')
    //   } else if (endDate - startDate > 2 * 24 * 60 * 60 * 1000) {
    //     this.formData.startDate = ''
    //     this.$message.info('时间跨度不能超过三天，请重新选择')
    //   } else {
    //     this.getTableData()
    //   }
    // },
    // 搜索
    onSubmit () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const az = /^[a-zA-Z]+$/
          const azNum = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]*$/
          // const top2 = /^[a-zA-Z]{2}\w*$/
          const top2 = /^([a-zA-Z][0-9])|([0-9][a-zA-Z])|([a-zA-Z]{2})/
          const num = /^[0-9]+$/
          const bagNo = /^[a-zA-Z]{2}[0-9]{6}$/
          const queryData = {
            startDate: this.startDate,
            endDate: this.endDate
          }
          queryData['outAirport'] = this.formData.currentAirport
          if (azNum.test(this.formData.search) && top2.test(this.formData.search) && this.formData.search.length < 8) {
            // 字母加数字且前两位为字母则为航班号
            queryData['carrierFlights'] = this.formData.search
          } else if ((num.test(this.formData.search) && this.formData.search.length === 10) || ((bagNo.test(this.formData.search) && this.formData.search.length > 7))) {
            // 纯数字且位数等于10则为行李牌号
            queryData['luggageNum'] = this.formData.search
          } else {
            // this.$message.error('请输入有效查询信息如航班号、行李牌号')
            // return
          }
          this.$router.push({
            path: '/newQuery',
            query: {
              ...queryData,
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
