import { Store } from 'vuex';

/**
 * 动态代码表服务类
 *
 * @export
 * @class CodeListService
 */
export default class CodeListService {

    /**
     * Vue 状态管理器
     *
     * @private
     * @type {(any | null)}
     * @memberof CodeListService
     */
    private $store: Store<any> | null = null;

    constructor(opts: any = {}) {
        this.$store = opts.$store;
    }

    /**
     * 获取状态管理器
     *
     * @returns {(any | null)}
     * @memberof CodeListService
     */
    public getStore(): Store<any> | null {
        return this.$store;
    }


    /**
     * 动态代码表缓存(加载中)
     *
     * @type {Map<string,any>}
     * @memberof CodeListService
     */
    public static codelistCache:Map<string,any> = new Map();


    /**
     * 获取动态代码表
     *
     * @param {string} tag 代码表标识
     * @param {string} context
     * @returns {Promise<any[]>}
     * @memberof CodeListService
     */
    public getItems(tag: string,context:any = {}, data?: any, isloading?: boolean,): Promise<any[]> {
        let _this: any = this;
        return new Promise((resolve:any,reject:any) =>{
            if(!data){
                if(this.$store &&  _this.$store.getters){
                    let items:any = _this.$store.getters.getCodeListItems(tag);
                    if(items.length >0){
                        return resolve(items);
                    }
                }
                if (_this[tag]) {
                    const callback:Function = (tag:string,promise:Promise<any>) =>{
                        promise.then((result:any) =>{
                            if(result.length > 0){
                                _this.$store.commit('updateCodeList',{srfkey:tag,items:result});
                                return resolve(result);
                            }else{
                                return resolve([]);
                            }
                        }).catch((result:any) =>{
                            return reject(result);
                        })
                    }
                    if(CodeListService.codelistCache.get(tag)){
                        callback(tag,CodeListService.codelistCache.get(tag));
                    }else{
                        let result:Promise<any> = _this[tag].getItems(context,data,isloading);
                        CodeListService.codelistCache.set(tag,result);
                        callback(tag,result);
                    }
                }
            }else{
                if (_this[tag]) {
                    _this[tag].getItems(context,data,isloading).then((result:any) =>{
                        resolve(result);
                    }).catch((error:any) =>{
                        Promise.reject([]);
                    })
                }else{
                    return Promise.reject([]);
                }
            }
        })
    }
}