package com.docus.server.collection.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.docus.core.util.Func;
import com.docus.server.collection.util.TableJsonRead;
import lombok.Data;

import java.util.List;

/**
 * 系统映射配置
 *
 * @author wyb
 */
@Data
public class SystemMappingConfig {
    private static final String CONFIG_FILE_PATH = "dataConfig";
    private static final String CONFIG_FILE_NAME = "System-Mapping.json";
    private static volatile boolean FLUSH;
    private static volatile SystemMappingConfig INSTANCE;
    private List<SystemMapping> mappings;

    @Override
    public String toString() {
        return "SystemMappingConfig{" +
                "mappings=" + mappings +
                '}';
    }

    private SystemMappingConfig() {
        TableJsonRead jsonRead = new TableJsonRead();
        String readJson = jsonRead.readContent(CONFIG_FILE_PATH, CONFIG_FILE_NAME);
        JSONObject jsonObject = Func.readJson(readJson, JSONObject.class);
        if (jsonObject != null && jsonObject.getJSONArray("mappings") != null) {
            JSONArray mappings = jsonObject.getJSONArray("mappings");
            this.mappings = Func.parseJsonArray(Func.toJson(mappings), SystemMapping.class);
        }
    }

    public static SystemMappingConfig getInstance() {
        if (INSTANCE == null || FLUSH) {
            synchronized (SystemMappingConfig.class) {
                if (INSTANCE == null || FLUSH) {
                    INSTANCE = new SystemMappingConfig();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 配置文件有更新，适用于不是程序动态改变的配置文件
     */
    public static void flush() {
        FLUSH = true;
    }


    public List<SystemMapping> getMappings() {
        return mappings;
    }

    public static void main(String[] args) {
        SystemMappingConfig instance = getInstance();
        System.out.println(instance);
        SystemMappingConfig instance2 = getInstance();
        System.out.println(instance == instance2);
        SystemMappingConfig.flush();
        SystemMappingConfig instance3 = getInstance();
        System.out.println(instance3 == instance2);
    }

    @Data
    public static class SystemMapping {
        /**
         * 医院系统标识
         */
        private String hospital;
        /**
         * 无纸化医院标识
         */
        private String wzh;
    }
}
