<template>
  <div class="data-query scroll-y">
    <div class="data-query-header">
      <div class="manageTitle">{{ title }}</div>
      <el-form
        ref="formRef"
        :model="formData"
        class="data-query-form"
        :rules="rules"
        @submit.native.prevent
      >
        <div v-if="name === 'freight'" class="form-left">
          <el-form-item prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              size="default"
              type="date"
              placeholder="开始日期"
              :prefix-icon="datePreTitle('开始')"
              :clearable="false"
              class="pre-text"
            />
          </el-form-item>
          <el-form-item prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledEndDate"
              size="default"
              type="date"
              placeholder="结束日期"
              :prefix-icon="datePreTitle('结束')"
              :clearable="false"
              class="pre-text"
            />
          </el-form-item>
        </div>
        <div v-if="name === 'flight'" class="form-left">
          <el-form-item prop="flightDate" style="width: 148px">
            <el-date-picker
              v-model="formData.flightDate"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              size="default"
              type="date"
              placeholder="请选择航班日期"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item prop="inOrOut" style="width: 108px">
            <el-select v-model="formData.inOrOut" size="default">
              <el-option value="in" label="进港航班" />
              <el-option value="out" label="出港航班" />
            </el-select>
          </el-form-item>
          <el-form-item prop="flightType" style="width: 108px">
            <el-select
              v-model="formData.flightType"
              size="default"
              placeholder="航班类型"
              clearable
            >
              <el-option :value="0" label="货机" />
              <el-option :value="1" label="客机" />
              <el-option :value="2" label="其他" />
            </el-select>
          </el-form-item>
          <el-form-item prop="sAirport" style="width: 108px">
            <el-select
              v-model="formData.sAirport"
              :disabled="formData.inOrOut === 'out'"
              size="default"
              placeholder="始发站"
              clearable
            >
              <el-option
                v-for="{ value, label } in airportOptions"
                :key="value"
                :value="value"
                :label="label"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="eAirport" style="width: 108px">
            <el-select
              v-model="formData.eAirport"
              :disabled="formData.inOrOut === 'in'"
              size="default"
              placeholder="目的站"
              clearable
            >
              <el-option
                v-for="{ value, label } in airportOptions"
                :key="value"
                :value="value"
                :label="label"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="planeType" style="width: 108px">
            <el-select
              v-model="formData.planeType"
              size="default"
              placeholder="属性"
              clearable
            >
              <el-option value="DOM" label="国内" />
              <el-option value="INT" label="国际" />
            </el-select>
          </el-form-item>
          <el-form-item prop="sFlightDate" style="width: 148px">
            <el-date-picker
              v-model="formData.sFlightDate"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              size="default"
              type="date"
              placeholder="请选择实飞时间"
            />
          </el-form-item>
        </div>
        <div class="form-right">
          <el-form-item
            v-if="name === 'flight'"
            prop="company"
            style="width: 180px"
          >
            <el-input
              v-model.trim="formData.company"
              size="default"
              placeholder="请输入航司进行搜索"
              :prefix-icon="Search"
              clearable
              @keyup.enter.prevent="dataQuery"
            />
          </el-form-item>
          <el-form-item
            prop="keyWords"
            :style="name === 'flight' ? { width: '190px' } : {}"
          >
            <el-input
              v-model.trim="formData.keyWords"
              size="default"
              :placeholder="keyWordsPlaceHolder"
              :prefix-icon="Search"
              clearable
              @keyup.enter.prevent="dataQuery"
            />
          </el-form-item>
        </div>
      </el-form>
      <el-button size="default" color="#ac014d" @click="dataQuery"
        >搜索</el-button
      >
      <el-button size="default" plain @click="resetForm">重置</el-button>
      <ColumnSet
        :table-columns="tableColumns"
        @checked-submit="columnChecked"
      />
    </div>
    <div
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      class="data-query-table"
    >
      <SimpleTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        :cell-class-name="cellClass"
        :column-props="{ formatter }"
        @cell-click="cellClickHandler"
        @scroll-over="load"
      />
    </div>
  </div>
</template>

<script setup lang="tsx">
import { Search } from '@element-plus/icons-vue'
import ColumnSet from '@/components/ColumnSet/index.vue'
import SimpleTable from '@/components/SimpleTable/index.vue'
import { ElMessage, FormInstance } from 'element-plus'
import { parseTime } from '@/utils/validate'
import { useTable } from './useTable'
import { useTableColumnSet } from '@/hooks/useTableColumnSet'
import { CommonTableFormatter } from '~/common'
import { Query } from '@/api/webApi'

const props = defineProps({
  name: {
    type: String,
    required: true,
  },
  title: {
    type: String,
    required: true,
  },
})

const today = parseTime(new Date(), '{y}-{m}-{d}') as string
const formData = reactive({
  flightDate: today,
  inOrOut: 'out',
  flightType: '',
  sAirport: '',
  eAirport: '',
  planeType: '',
  sFlightDate: '',
  company: '',
  startDate: today,
  endDate: today,
  keyWords: '',
})
watchEffect(() => {
  if (formData.inOrOut === 'in') {
    formData.sAirport = ''
    formData.eAirport = 'SZX'
  } else {
    formData.sAirport = 'SZX'
    formData.eAirport = ''
  }
  if (!formData.startDate || !formData.endDate) {
    return
  }
  const start = new Date(formData.startDate).getTime()
  const end = new Date(formData.endDate).getTime()
  if (start > end) {
    ElMessage.warning('开始时间不能晚于结束时间')
    formData.endDate = ''
  }
  if (start <= end - 2 * 24 * 60 * 60 * 1000) {
    ElMessage.warning('间隔不能超过2天')
    formData.endDate = ''
  }
})
const disabledEndDate = (endDate: Date) => {
  const start = new Date(formData.startDate + ' 00:00:00').getTime()
  const end = endDate.getTime()
  return start > end || start <= end - 2 * 24 * 60 * 60 * 1000
}
const datePreTitle = (title: string) => {
  return <div class="date-pre-title">{title}：</div>
}

const searchTitleMap = {
  flight: '航班号',
  waybill: '运单号',
  freight: '货物编码',
}

const keyWordsPlaceHolder = computed(
  () => `请输入${searchTitleMap[props.name] ?? '内容'}进行搜索`
)

const airportOptions = ref<{ value: string; label: string }[]>([])
const getAirports = async () => {
  try {
    const {
      code,
      returnData: { listValues },
      message,
    } = await Query<{ [x: string]: string }>({
      id: DATACONTENT_ID.airportCode,
      dataContent: [],
    })
    if (Number(code) !== 0) {
      throw new Error(message || '失败')
    }
    airportOptions.value = listValues.map(({ code3 }) => ({
      value: code3,
      label: code3,
    }))
  } catch (error) {
    console.error(error)
  }
}
onMounted(() => {
  if (props.name === 'flight') {
    getAirports()
  }
})

const keyWordsValidator = (rule: any, value: any, callback: any) => {
  const searchTitle = searchTitleMap[props.name] ?? '关键词'
  if (!value) {
    if (['flight'].includes(props.name)) {
      return callback()
    } else {
      return callback(new Error(`请输入${searchTitle}`))
    }
  }
  const regsMap: { [x: string]: RegExp[] } = {
    // flight: [/^[A-Za-z0-9][A-Za-z][0-9]{3,4}$/, /^[0-9]{3,4}$/],
    flight: [/^[0-9]{1,4}$/],
    waybill: [/^[0-9]{8}$/, /^[0-9]{11}$/, /^[0-9]{3}\-[0-9]{8}$/],
    freight: [/^[0-9]{5}$/, /^[0-9]{3}\-[0-9]{8}\-[0-9]{5}$/],
  }
  const regs = regsMap[props.name] ?? []
  const notMatched = regs.length && regs.every(reg => !reg.test(value))
  if (notMatched) {
    return callback(new Error(`请输入正确的${searchTitle}`))
  }
  return callback()
}
const rules = {
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
  keyWords: [{ validator: keyWordsValidator, trigger: 'blur' }],
  flightDate: [{ required: true, message: '请选择航班日期', trigger: 'blur' }],
  company: [
    {
      pattern: /^[A-Za-z0-9][A-Za-z]$/,
      message: '请输入正确的航司',
      trigger: 'blur',
    },
  ],
}
const formRef = ref<FormInstance | null>()
const dataQuery = () => {
  formRef.value?.validate(valid => {
    if (valid) {
      tableInit()
      load()
    }
  })
}

const resetForm = () => {
  formRef.value?.resetFields()
}

const loading = ref(false)
const page = ref(1)
const noMore = ref(false)
const { tableColumns, tableData, getTableData } = useTable(
  props.name,
  formData,
  page,
  noMore,
  loading
)
const load = () => {
  if (loading.value || noMore.value) {
    return
  }
  page.value++
  getTableData()
}
const tableInit = () => {
  page.value = 0
  noMore.value = false
  tableData.value = []
}

const { columnChecked } = useTableColumnSet(tableColumns)

const flightStateMap = {
  CAN: '取消',
  DLY: '延误',
}
const flightTypeMap = ['货机', '客机', '其他']
const formatter: CommonTableFormatter = (row, column, cellValue, index) => {
  const value = String(cellValue ?? '').trim()
  if (column.property.includes('Time')) {
    return value.replace(/[T|\s]+/, '\n')
  }
  if (column.property === 'DIType' && value) {
    return value === 'DOM' ? '国内' : '国际'
  }
  if (column.property === 'flightState') {
    return value ? flightStateMap[value] ?? '正常' : '正常'
  }
  if (column.property === 'flightType') {
    return typeof cellValue === 'number'
      ? flightTypeMap[cellValue] ?? '其他'
      : '其他'
  }
  return value
}

const cellClass = ({ row, column, rowIndex, columnIndex }) => {
  const classes: string[] = []
  switch (props.name) {
    case 'flight':
      if (['flightNO'].includes(column.property) && row[column.property]) {
        classes.push('cell-click')
      }
      break
    case 'waybill':
      if (['stockCode'].includes(column.property) && row[column.property]) {
        classes.push('cell-click')
      }
      break
    case 'freight':
      break
    default:
      break
  }
  return classes.join(' ')
}

const router = useRouter()

const cellClickHandler = (row, column, cell, event) => {
  switch (props.name) {
    case 'flight': {
      switch (column.property) {
        case 'flightNO': {
          if (
            !row.flightAllNO ||
            !row.flightDate ||
            !['INT', 'DOM'].includes(row.DIType) ||
            typeof row.FFID !== 'string' ||
            !['A', 'D'].includes(row.FFID.at(-1))
          ) {
            ElMessage.error('航班信息缺失!')
            return
          }
          const viewName = `${row.DIType === 'DOM' ? '' : 'International'}${
            row.FFID.at(-1) === 'D' ? 'Departure' : 'Arrival'
          }Flight`
          router.push({
            path: `/dataQuery/flightQuery/${viewName}`,
            query: {
              flightNO: row.flightAllNO,
              flightDate: row.flightDate,
            },
          })
          break
        }
        default:
          break
      }
      break
    }
    case 'waybill': {
      switch (column.property) {
        case 'stockCode': {
          if (
            !row.stockCode ||
            !row.flightDate ||
            !['INT', 'DOM'].includes(row.DIType) ||
            typeof row.FFID !== 'string' ||
            !['A', 'D'].includes(row.FFID.at(-1))
          ) {
            ElMessage.error('运单信息缺失!')
            return
          }
          const viewName = `${row.DIType === 'DOM' ? '' : 'International'}${
            row.FFID.at(-1) === 'D' ? 'Departure' : 'Arrival'
          }Waybill`
          router.push({
            path: `/dataQuery/waybillQuery/${viewName}`,
            query: {
              waybillNO: row.stockCode,
              flightDate: row.flightDate,
            },
          })
          break
        }
      }
      break
    }
    case 'freight':
      break
    default:
      break
  }
}
</script>

<style lang="scss" scoped>
.data-query {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  &-header {
    width: 100%;
    height: 32px;
    margin: 12px 0;
    display: flex;
  }
  &-form :deep {
    margin-right: 12px;
    flex: 1;
    display: flex;
    justify-content: flex-end;
    .form-left {
      flex: 1;
      display: flex;
      .el-form-item {
        width: 168px;
        margin-right: 8px;
        .el-date-editor.pre-text {
          .el-input__prefix {
            flex-basis: 42px;
            padding-left: 15px;
            .date-pre-title {
              font-style: normal;
              font-size: 14px;
              font-family: Microsoft YaHei;
              color: #303133;
            }
          }
        }
      }
    }
    .form-right {
      display: flex;
      justify-content: flex-end;
      .el-form-item {
        width: 280px;
        &:not(:last-of-type) {
          margin-right: 10px;
        }
        .el-select,
        .el-date-editor {
          width: 100%;
        }
      }
    }
    .el-form-item {
      margin: 0;

      .el-input__inner {
        font-size: 14px;
        font-family: Helvetica, Microsoft YaHei;
        color: #303133;
      }
    }
  }
  &-table {
    height: 0;
    flex: 1;
  }
}
</style>
