import type { Dayjs } from 'dayjs'

import { registerWidgetFactory, unpackWidgetInstance } from '../../utils'
import type { TimeBarInstance, TimeBarProps } from './types'

// 组件名称
export const name = 'TimeBarWidget'

/**
 * 顶部时间栏组件响应式 Hook
 * @param props 组件参数
 * @returns 组件响应式数据
 */
export function useTimeBarWidget<T extends TimeBarInstance, P extends TimeBarProps>(
    props: P,
): [(instance: T) => void, TimeBarInstance] {
    const instanceRef = ref<T>()
    const register = registerWidgetFactory(instanceRef, props)
    const { get, ...fns } = unpackWidgetInstance(instanceRef, name)

    return [
        register,
        {
            ...fns,
            getTime: () => get()?.getTime(),
            setTime: (time: Dayjs[]) => get()?.setTime(time),
            getCheckedOption: () => get()?.getCheckedOption(),
            setCheckedOption: (index: number) => get()?.setCheckedOption(index),
            getTimeBarValue: () => get()?.getTimeBarValue(),
        },
    ]
}

/**
 * 格式化时间
 * @param time 时间
 * @param format 格式化
 * @returns 格式化后的时间，如果时间为空则返回空字符串
 */
export function formatTime(time: Dayjs, format = 'YYYY-MM-DD HH:mm:ss') {
    return time?.format(format) ?? ''
}

/**
 * 根据 type 属性返回对应的格式化字符串
 * @param type fui-date-picker 组件的 type 属性
 * @returns 根据 type 属性返回对应的格式化字符串
 */
export function getFormatByType(type: number) {
    switch (type) {
        case 1:
            return 'YYYY'
        case 2:
            return 'YYYY-MM'
        case 3:
            return 'YYYY-MM-DD'
        case 4:
            return 'YYYY-MM-DD HH:00:00'
        case 5:
            return 'YYYY-MM-DD HH:mm:00'
        case 6:
            return 'YYYY-MM-DD HH:mm:ss'
        default:
            return 'YYYY-MM-DD HH:mm:ss'
    }
}
