import { ref } from 'vue'
import type { SearchForm } from '@/types/api/order/factoryOrderNew'

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 = () => ({
    ...searchForm.value,
    startTime: dateRange.value?.[0] || null,
    endTime: dateRange.value?.[1] || null,
  })

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

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