import {computed} from 'vue'
import {injectLocal, provideLocal} from "@vueuse/core";
import {useConditionEventManager} from "@/components/mx-condition/useConditionEventManager";
import {useConditionDataManager} from "@/components/mx-condition/useConditionDataManager";
import {fnPlaceholder} from "@/utils/uni-helper";

const key = Symbol('SEARCH_MODEL_SERVICE')

/* 给业务方使用，希望只是定制查询条件的动态参数与静态参数 */
export const useProvideSearchModel = function (configs, queryParams, formRef = null, sharedData = {}) {
    const silence = true
    // console
    const log = silence
        ? {log: fnPlaceholder, warn: console.warn, error: console.error}
        : {log: console.log, warn: console.warn, error: console.error}
    // uv-form validation
    const validator = computed(() => formRef?.value?.validate || fnPlaceholder)
    // event manager for trigger onSearch/onInit
    const eventManager = useConditionEventManager(queryParams, validator, log)
    // request data manager. configs必须提供当前场景所需要的所有condition
    const dataManager = useConditionDataManager(configs, eventManager, queryParams, sharedData, log)
    const reset = () => {
        dataManager.reset()
        eventManager.reset()
    }
    const options = {
        queryParams, // 原样返回
        sharedData, // 原样返回
        rules: dataManager.rules, // 给forms用的校验规则，因为利用uv-form的校验是最简便的
        conditions: dataManager.conditions, // 显示条件选项的数据
        needValidation: dataManager.needValidation, // 是否需要校验，和渲染uv-form有关
        onSearch: eventManager.onSearch, // 搜索事件
        onInit: eventManager.onInit, // 搜索事件，第一次
        reset // 重置搜索条件状态
    }
    provideLocal(key, options)
    window.searchModel = options
    return options
}

export const useInjectSearchModel = function () {
    return injectLocal(key)
}