package com.lightinit.hsdatashow.controller.admin;

import com.lightinit.hsdatashow.annotation.FieldDescriberHelper;
import com.lightinit.hsdatashow.model.ResultState;
import com.lightinit.hsdatashow.model.ResultStateCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author WangYao
 * @date 2018/6/2 11:33
 * @description 控制器基类
 */
public class BaseController {

    public static <T> LinkedHashMap<String, String> getAllFieldInvalidMsg(T modelObj, BindingResult bindingResult){
        if (modelObj == null || bindingResult == null){
            return null;
        }
        LinkedHashMap<String, String> result = new LinkedHashMap<>();
        for (FieldError error : bindingResult.getFieldErrors()){
            String fieldName = error.getField();
            String fieldDescription = FieldDescriberHelper.getFieldDescription(modelObj, fieldName);
            result.put(fieldName, fieldDescription + error.getDefaultMessage());
        }

        return result;
    }

    public static <T> Map.Entry<String, String> getFirstFieldInvalidMsg(T modelObj, BindingResult bindingResult){
        LinkedHashMap<String, String> allFieldInvalidMsg = getAllFieldInvalidMsg(modelObj, bindingResult);
        return allFieldInvalidMsg == null ? null : allFieldInvalidMsg.entrySet().stream().findFirst().get();
    }

    public static ResultState buildInvalidResultState(String message){
        return buildInvalidResultState(message, null);
    }

    public static <T> ResultState<T> buildInvalidResultState(int stateCode, String message){
        return buildInvalidResultState(stateCode, message, null);
    }

    public static <T> ResultState<T> buildInvalidResultState(String message, T data){
        return buildInvalidResultState(ResultStateCode.INVALID_DATA, message, data);
    }

    public static <T> ResultState<T> buildInvalidResultState(int stateCode, String message, T data){
        return new ResultState(stateCode, message, data);
    }

    public static <T> ResultState<LinkedHashMap<String, String>> getAllFieldInvalidResultState(T modelObj, BindingResult bindingResult){
        return buildInvalidResultState("", getAllFieldInvalidMsg(modelObj, bindingResult));
    }

    public static <T> ResultState getFirstInvalidResultState(T modelObj, BindingResult bindingResult){
        Map.Entry<String, String> firstFieldInvalidMsg = getFirstFieldInvalidMsg(modelObj, bindingResult);
        return buildInvalidResultState(firstFieldInvalidMsg == null ? "" : firstFieldInvalidMsg.getValue());
    }
}
