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

export function useOrderSearchForm(refreshCurrentView: () => void) {
  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
    return {
      ...rest,
      ...markQuery,
      ...(tagsId !== undefined ? { tagsId } : {}),
      startTime: dateRange.value?.[0] || null,
      endTime: dateRange.value?.[1] || null,
    }
  }

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

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