<template>
  <div class="data-query">
    <div class="data-query-header">
      <div class="manageTitle">局方报文</div>
      <el-form
        ref="formRef"
        :model="formData"
        class="data-query-form"
        :rules="rules"
        @submit.native.prevent
      >
        <div 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 class="form-right">
          <el-form-item prop="messageType" style="width: 108px">
            <el-select
              v-model="formData.messageType"
              size="default"
              placeholder="报文类型"
              clearable
            >
              <el-option
                v-for="{ value, label } in messageTypeOptions"
                :key="value"
                :value="value"
                :label="label"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="waybillNO">
            <el-input
              v-model.trim="formData.waybillNO"
              size="default"
              placeholder="请输入运单号进行搜索"
              :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"
        :column-props="{ formatter }"
        sequence
        @scroll-over="load"
      />
    </div>
  </div>
</template>

<script lang="tsx">
export default {
  name: 'MessageQuery',
}
</script>

<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 { useTableColumnSet } from '@/hooks/useTableColumnSet'
import {
  CommonData,
  CommonTableColumn,
  CommonTableFormatter,
  CommonValue,
} from '~/common'
import { Query } from '@/api/webApi'

const today = parseTime(new Date(), '{y}-{m}-{d}') as string
const formData = reactive({
  startDate: today,
  endDate: today,
  messageType: '',
  waybillNO: '',
})

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 messageTypeOptions = ref(
  Object.entries(MESSAGE_TYPE).map(([value, label]) => ({
    label,
    value,
  }))
)

const waybillValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  const notMatched = [
    /^[0-9]{8}$/,
    /^[0-9]{11}$/,
    /^[0-9]{3}\-[0-9]{8}$/,
  ].every(reg => !reg.test(value))
  if (notMatched) {
    return callback(new Error('请输入正确的运单号'))
  }
  return callback()
}
const rules = {
  waybillNO: [{ validator: waybillValidator, 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(true)
const tableColumns = ref<CommonTableColumn[]>([])
const tableData = ref<CommonData[]>([])
const getTableData = async (defaultDataContent?: CommonValue[]) => {
  if (loading) {
    loading.value = true
  }
  try {
    let { startDate, endDate, messageType, waybillNO } = formData
    const dataContent = [startDate, endDate, messageType, waybillNO].map(
      v => v || null
    )
    const {
      code,
      returnData: { listValues },
      message,
    } = await Query<CommonData>({
      id: DATACONTENT_ID.messageDataQuery,
      dataContent: defaultDataContent ?? dataContent,
      needPage: page.value,
    })
    if (Number(code) !== 0) {
      throw new Error(message || '失败')
    }
    if (listValues.length) {
      tableData.value.push(
        ...listValues.filter(
          row =>
            !Object.values(row).some(
              cellValue =>
                typeof cellValue === 'string' && cellValue.includes('undefined')
            )
        )
      )
    } else {
      page.value--
      noMore.value = true
    }
  } catch (error) {
    console.error(error)
    page.value--
    noMore.value = true
  }
  if (loading) {
    loading.value = false
  }
}
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 columns = [
  {
    columnName: 'waybillNO',
    columnLabel: '运单号',
  },
  {
    columnName: 'fileName',
    columnLabel: '文件名称',
  },
  {
    columnName: 'messageName',
    columnLabel: '报文名称',
  },
  {
    columnName: 'messageState',
    columnLabel: '收发状态',
  },
  {
    columnName: 'execTime',
    columnLabel: '执行时间',
  },
  {
    columnName: 'airportState',
    columnLabel: '报文收发方',
  },
  {
    columnName: 'messageDetails',
    columnLabel: '报文明细',
    showOverflowTooltip: true,
    width: 300,
  },
]
onMounted(() => {
  tableColumns.value = columns.map(column => ({
    columnDescribe: '',
    dataType: '',
    needCount: null,
    needFilters: null,
    needGroup: null,
    needSearch: null,
    needShow: 1,
    needSort: null,
    listqueryTemplateID: null,
    queryTemplateColumnSetID: null,
    queryTemplateID: null,
    orderNumber: null,
    ...column,
  }))
})

const messageStateMap = {
  in: '收',
  out: '发',
}
const formatter: CommonTableFormatter = (row, column, cellValue, index) => {
  const value = String(cellValue ?? '').trim()
  if (column.property === 'fileName') {
    return MESSAGE_TYPE[value] ?? value
  }
  if (column.property === 'execTime') {
    return value.replace('T', ' ')
  }
  if (column.property === 'messageState') {
    return messageStateMap[value] ?? ''
  }
  return value
}
</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: DIN, Microsoft YaHei;
        color: #303133;
      }
    }
  }
  &-table {
    height: 0;
    flex: 1;
  }
}
</style>
