import { nextTick, ref } from 'vue'
import type { SearchForm } from '@/types/api/order/factoryOrderNew'
import type { FactoryOrderSearchQueryVisibilityContext } from '@/types/api/factoryOrderNew/searchQueryVisibility'
import { filterFactoryOrderListSearchPayload } from '../utils/listSearchQueryFilter'
import { normalizeProductMarkListForQuery } from '../utils/productMarkQuery'

export function useOrderSearchForm(
  refreshCurrentView: () => void,
  getVisibilityContext?: () => FactoryOrderSearchQueryVisibilityContext,
) {
  const searchForm = ref<SearchForm>({})
  const dateRange = ref<string[]>([])
  const searchVisible = ref(false)

  const pickerOptions = {
    shortcuts: [
      {
        text: '今日',
        value: () => {
          const start = new Date()
          start.setHours(0, 0, 0, 0)
          const end = new Date()
          end.setHours(23, 59, 59, 999)
          return [start, end]
        },
      },
      {
        text: '最近7天',
        value: () => {
          const end = new Date()
          end.setHours(23, 59, 59, 999)
          const start = new Date()
          start.setDate(start.getDate() - 6)
          start.setHours(0, 0, 0, 0)
          return [start, end]
        },
      },
      {
        text: '最近30天',
        value: () => {
          const end = new Date()
          end.setHours(23, 59, 59, 999)
          const start = new Date()
          start.setDate(start.getDate() - 29)
          start.setHours(0, 0, 0, 0)
          return [start, end]
        },
      },
    ],
  }

  const toggleMulti = (val: boolean) => {
    if (searchForm.value.multi === val) {
      setTimeout(() => {
        if (searchForm.value.multi === val) {
          searchForm.value.multi = undefined
        }
      }, 0)
    }
  }

  const changeReplaceShipment = () => {
    searchForm.value.shipmentType = ''
  }

  /** 扫码枪扫完一单后追加英文逗号，便于连续扫多个操作单号 */
  const handleOperationNoScanEnter = (event: KeyboardEvent) => {
    event.preventDefault()
    const val = (searchForm.value.operationNo || '').trim()
    if (!val || val.endsWith(',')) return
    searchForm.value.operationNo = `${val},`
  }

  const getQueryPayload = () => {
    const {
      productMarkList: rawProductMarks,
      tagsIdArr,
      operationNo,
      ...rest
    } = searchForm.value
    const markQuery = normalizeProductMarkListForQuery(rawProductMarks)
    const tagsId =
      Array.isArray(tagsIdArr) && tagsIdArr.length > 0
        ? tagsIdArr.join(',')
        : undefined
    const processedOperationNo = (() => {
      const originalValue = operationNo || ''
      if (!originalValue) return ''

      const values = originalValue.split(/[,，;；]/).filter((v) => v.trim())

      const processedValues = values.map((value) => {
        const trimmedValue = value.trim()
        const underscoreCount = (trimmedValue.match(/_/g) || []).length

        if (underscoreCount >= 3) {
          const parts = trimmedValue.split('_')
          return parts[3]
        }
        return trimmedValue
      })

      return processedValues.join(',')
    })()
    const raw: Record<string, unknown> = {
      ...rest,
      ...markQuery,
      ...(tagsId !== undefined ? { tagsId } : {}),
      operationNo: processedOperationNo,
      startTime: dateRange.value?.[0] || null,
      endTime: dateRange.value?.[1] || null,
    }
    return getVisibilityContext
      ? filterFactoryOrderListSearchPayload(raw, getVisibilityContext())
      : raw
  }

  const reset = () => {
    searchForm.value = {}
    dateRange.value = []
    nextTick(() => {
      refreshCurrentView()
    })
  }

  return {
    searchForm,
    dateRange,
    searchVisible,
    pickerOptions,
    toggleMulti,
    changeReplaceShipment,
    getQueryPayload,
    handleOperationNoScanEnter,
    reset,
  }
}
