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 getQueryPayload = () => {
    const { productMarkList: rawProductMarks, tagsIdArr, ...rest } =
      searchForm.value
    const markQuery = normalizeProductMarkListForQuery(rawProductMarks)
    const tagsId =
      Array.isArray(tagsIdArr) && tagsIdArr.length > 0
        ? tagsIdArr.join(',')
        : undefined
    const raw: Record<string, unknown> = {
      ...rest,
      ...markQuery,
      ...(tagsId !== undefined ? { tagsId } : {}),
      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,
    reset,
  }
}
