<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 !== 'waybill'" 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"
            />
          </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"
            />
          </el-form-item>
        </div>
        <div class="form-right">
          <el-form-item prop="keyWords">
            <el-input
              v-model.trim="formData.keyWords"
              size="default"
              placeholder="请输入要搜索的内容"
              :prefix-icon="Search"
              clearable
              @keyup.enter.prevent="dataQuery"
            />
          </el-form-item>
        </div>
      </el-form>
      <el-button size="default" type="primary" @click="dataQuery"
        >搜索</el-button
      >
      <ColumnSet
        :table-columns="tableColumns"
        @checked-submit="columnChecked"
      />
    </div>
    <div
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      class="data-query-table"
    >
      <SimpleTable
        ref="tableRef"
        :data="tableData"
        :columns="filteredColumns"
        :cell-class-name="cellClass"
        :column-props="{ formatter }"
        @cell-click="cellClickHandler"
      />
    </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'

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({
  startDate: props.name === 'waybill' ? null : today,
  endDate: props.name === 'waybill' ? null : today,
  keyWords: '',
})
watchEffect(() => {
  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 keyWordsValidator = (rule: any, value: any, callback: any) => {
  const searchTitleMap = {
    flight: '航班号',
    waybill: '运单号',
    freight: '货物编码',
  }
  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: [/^[A-Za-z0-9]{1,6}$/],
    waybill: [/^[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' }],
}
const formRef = ref<FormInstance | null>()
const dataQuery = () => {
  formRef.value?.validate(valid => {
    if (valid) {
      getTableData()
    }
  })
}

const loading = ref(false)
const { tableColumns, tableData, getTableData } = useTable(
  props.name,
  formData,
  loading
)

const { filteredColumns, columnChecked } = useTableColumnSet(tableColumns)

const formatter: CommonTableFormatter = (row, column, cellValue, index) => {
  const value = String(cellValue ?? '').trim()
  if (column.property.includes('Time')) {
    return value.replace(/(T|\s)+/, '\n')
  }
  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;
      }
    }
    .form-right {
      display: flex;
      justify-content: flex-end;
      .el-form-item {
        width: 280px;
      }
    }
    .el-form-item {
      margin: 0;

      .el-input__inner {
        font-size: 14px;
        font-family: Helvetica, Microsoft YaHei;
        color: #303133;
      }
      .el-date-editor {
        .el-input__prefix {
          flex-basis: 42px;
          padding-left: 15px;
          .date-pre-title {
            font-style: normal;
            font-size: 14px;
            font-family: Microsoft YaHei;
            color: #303133;
          }
        }
      }
    }
  }
  &-table {
    height: 0;
    flex: 1;
  }
}
</style>
