import { ref, onMounted, onUnmounted } from 'vue'
import { bus, BUS_EVENTS } from '@/utils/bus'

import useOptionsStore from '@/store/modules/options'

export function useOptions(type, apiFn, params = {}) {
    const options = ref([])
    const optionStore = useOptionsStore()

    const fetchOptions = async (force = false) => {
        // 1. 如果不是强制刷新，且 Store 中已有值，直接取 Store
        if (!force && optionStore[type] && optionStore[type].length > 0) {
            options.value = optionStore[type]
            return
        }

        // 2. 否则调接口
        try {
            const res = await apiFn(params)
            const data = res.rows || res.data || []
            options.value = data
            // 3. 更新 Store 缓存
            optionStore.setOptions(type, data)
        } catch (error) {
            console.error(`获取${type}下拉失败:`, error)
        }
    }

    // 监听刷新信号
    const handleRefresh = (refreshType) => {
        if (refreshType === type || refreshType === 'all') {
            fetchOptions(true) // 强制刷新
        }
    }

    onMounted(() => {
        fetchOptions()
        bus.on(BUS_EVENTS.REFRESH_OPTIONS, handleRefresh)
    })

    onUnmounted(() => {
        bus.off(BUS_EVENTS.REFRESH_OPTIONS, handleRefresh)
    })

    return {
        options,
    }
}
