
import {  get_selectOptions } from '@/common/apis/controls'
import Storage from '@/common/utils/storage'
import { selectStore } from './store'
import { Types } from '@/common/apis/controls/select'
import EXEC from '@/common/utils/exec'
export const getOptionsToType = ({type, params={}, system='sec'}:any, Refresh = false) => {
    let store = selectStore()
    let storageKey = `[${system}]_[${EXEC.comp_id}]_[${type}]_[${JSON.stringify(params)}]`
        
    /**  使用API 获取下拉数据源， 这里通过API接口，传type获取；  
     *  1, 判断是否必须从接口获取，alwaysAPI==true时，该类型不读本地缓存, 直接请求；
     *  2，获取store；如果store有，则读store； 否则请求；
     *  3，请求： 请求API
     */
    return new Promise((resolve, reject) => {
        if(!Refresh){
            let storeOpts = store.options[storageKey]
            if(storeOpts && storeOpts.length>0){
                // store存在，则直接返回store
                resolve(storeOpts)
            }else{
                // store不存在，则判断storage是否存在
                let StorageData = Storage.get('Options')||{}
                if(StorageData[storageKey] && StorageData[storageKey].length>0){
                    // storage存在，则返回storage，并将storage存入store
                    store.save(StorageData[storageKey], storageKey)
                    resolve(StorageData[storageKey])
                }else{
                    api()
                }
            }
        }else{
            api()
        }

        //请求
        function api (){
            getAPI(type,params,system,Refresh).then( async (res:any) => {
                let opts:any = res['result'] || []
                let labelKey:any = '', valueKey:any = '';
                if(Types[type]){
                    labelKey = Types[type].labelKey||'', 
                    valueKey = Types[type].valueKey||'';
                }
                await opts.forEach((opt:any) => {
                    opt.value = opt[valueKey] || opt['value'] || opt['id'] || opt['code']
                    opt.label = opt[labelKey] || opt[valueKey] ||  opt['label'] || opt['value'] || opt['code'] || opt['id']
                });
                // 从接口保存到store
                store.save(opts, storageKey)
                // 从接口保存到storage
                let StorageData = await Storage.get('Options')||{}
                StorageData[storageKey] = opts
                await Storage.set('Options', StorageData)
                // 从接口返回到控件
                resolve(opts)
            })
        }
  
    })
}

const getAPI = (type:string, params:any={}, system:any='sec', Refresh=false) => {
    return get_selectOptions(type, params, system, Refresh)
}



export const filter = (options:any = [], control:any) => {
    
    /* 选项过滤器（内部） 
    * 优先级： unfilter > filter 
    * 1,过滤器unfilter:只显示参数不相等的选项;
    * 2,beLinked联动和过滤器filter:只显示参数相等的选项； 必须字段为空时，选项为空; 
    */
    let filters:any =  [] 
    let unfilters:any = [] 

    if(!filters && !unfilters) return options // 过滤器和父级联动都没有，直接返回全选项集
    let newOpts:any = options

    // 反向过滤
    if(unfilters){
        let arr = []
        for(let opt of newOpts){
            let pass = true 
            for(let key in unfilters){
                if(opt.hasOwnProperty(key) && opt[key] == unfilters[key] && unfilters[key] && unfilters[key].length>0){
                    pass = false
                    continue
                }
            }
            if(pass) arr.push(opt)
        };
        newOpts = arr
    }

    // 过滤和联动
    if(filters){
        let opts = {
            ...filters,
        }
        let arr = []
        for(let opt of newOpts){
            let pass = true 
            for(let key in opts){
                if(opt.hasOwnProperty(key) && opts[key] && opts[key].length>0){
                    
                    if(opts[key] instanceof Array){  // 判断value是否为数组 
                        if( opts[key].indexOf(opt[key])<0){
                            pass = false
                            break
                        }
                    }else{
                        if(opt[key] != opts[key]) {
                            pass = false
                            break
                        }
                    }
                }
            }
            if(pass) arr.push(opt)
        };
        newOpts = arr
    }
    return newOpts
}



//取整个行数据
export const getOption = (value:any, props:any, options:any) => { //取整个行数据
    let key = props.controls.select['valueKey'] || 'value'
    let activeOption:any
    if(value instanceof Array){  // 判断value是否为数组 
        activeOption = []
        if(value&&value.length>0){
            for(let v of value){
                for(let item of options){
                    if(item[key] == v) {
                        activeOption.push(item)
                        break;
                    }
                }
            }
        }
        return activeOption
    }else{  // 判断value为字符串
        activeOption = {}
        if(value){
            for(let item of options){
                if(item[key] == value) {
                    activeOption = item
                    break;
                }
            }
        }
        return activeOption
    }
}



// 带参 <旧>
export const setMappings = (data:any, control:any) => {
    let Mappings = control.select.mappings
    if(!Mappings) return 
    let options = control.select.activeOption 
    if(!options) return  // 行数据在
    if(options instanceof Array) return  // 如果多选 return
    for(let item of Mappings){
        let target = item['param'] || item['control']
        if(options[target] != null && options[target] != undefined){
            data[item['control']] = options[target] 
        }
    }
}
export const setMappings_dialog = (data:any, control:any) => {
    let Mappings = control.dialog.mappings
    if(!Mappings) return 
    let options = control.dialog.activeOption 
    if(!options) return  // 行数据在
    if(options instanceof Array) return  // 如果多选 return
    for(let item of Mappings){
        let target = item['param'] || item['control']
        if(options[target] != null && options[target] != undefined){
            data[item['control']] = options[target]
        }
    }
}

