import { api } from 'common/api'
import { mapKeys } from 'lodash'
import store from 'store'
import { toCamelCase } from 'util/format'

const { getState, dispatch } = store

const getDictData = async (...args) => {
    const dictData = getState('dictData')
    let dict = {}
    const code = []
    for (let i = 0; i < args.length; i++) {
        const codeName = toCamelCase(args[i])
        if (!dictData.hasOwnProperty(codeName)) {
            code.push(args[i])
        } else {
            dict[codeName] = dictData[codeName]
        }
    }

    if (code.length) {
        try {
            const value = mapKeys((await api.sysDictTypeDropDowns({ code })).data, (value, key) => {
                return toCamelCase(key)
            })

            dispatch({
                type: 'ADD_DICT_DATA',
                value
            })

            dict = { ...dict, ...value }
        }
        catch { }
    }

    const result = {}
    args.forEach(p => {
        const codeName = toCamelCase(p)
        result[codeName] = dict[codeName]
    })
    return result
}

export default getDictData