package com.xhpc.pp.logic;

import com.xhpc.pp.domain.ServiceField;
import com.xhpc.pp.mapper.ServiceFieldMapper;
import com.xhpc.pp.server.ChargingPileServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Lazy
@Component
public class FieldLogic {

    // 版本->协议字段表
    private static Map<String, Map<String, List<ServiceField>>> versionMapFields;
    private static ServiceFieldMapper fieldMapper;

    @Autowired
    public FieldLogic(ServiceFieldMapper fieldMapper) {

        versionMapFields = new HashMap<>();
        FieldLogic.fieldMapper = fieldMapper;
        FieldLogic.init();
    }

    public static void refreshCache() {

        versionMapFields.clear();
        init();
    }

    public static void init() {

        List<ServiceField> list = fieldMapper.query(null);
        for (ServiceField field : list) {
            String version = field.getVersion();
            String service = field.getServiceName();
            Map<String, List<ServiceField>> versionMap = versionMapFields.computeIfAbsent(version, k -> new HashMap<>());
            List<ServiceField> fields = versionMap.computeIfAbsent(service, k -> new ArrayList<>());
            fields.add(field);
        }
    }

    public static List<ServiceField> fieldList(String version, String service) {

        Map<String, List<ServiceField>> vermap = versionMapFields.get(version);
        if (vermap == null)
            vermap = versionMapFields.get(ChargingPileServer.default_version);
        List<ServiceField> fieldList = vermap.get(service);
        if (fieldList == null || fieldList.isEmpty()) {
            vermap = versionMapFields.get(ChargingPileServer.default_version);
            fieldList = vermap.get(service);
        }
        return fieldList;
    }

    public List<Map<String, Object>> querySQL(String sql) {

        Map<String, String> query = new HashMap<>();
        query.put("sql", sql);
        return fieldMapper.querySQL(query);
    }

}
