package com.ruoyi.common.utils;

import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ApiResult extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	public ApiResult() {
		put("code", 0);
		put("msg", "操作成功");
	}

	public static ApiResult toAjax(int count){
		return count > 0 ? ApiResult.ok() : ApiResult.error();
	}

	public static ApiResult error() {
		return error(1, "操作失败");
	}

	public static ApiResult error(String msg) {
		return error(500, msg);
	}

	public static ApiResult error(int code, String msg) {
		ApiResult apiResult = new ApiResult();
		apiResult.put("code", code);
		apiResult.put("msg", msg);
		return apiResult;
	}

	public static ApiResult ok(String msg) {
		ApiResult apiResult = new ApiResult();
		apiResult.put("msg", msg);
		return apiResult;
	}

	public static ApiResult ok(Map<String, Object> map) {
		ApiResult apiResult = new ApiResult();
		apiResult.putAll(map);
		return apiResult;
	}

	public static ApiResult ok() {
		return new ApiResult();
	}

	@Override
	public ApiResult put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	/**
	 * 参数校验
	 * @param bindingResult 参数校验对象
	 * @return 结果
	 */
	public static ApiResult allParameterErrors(BindingResult bindingResult){
		String errorStr = "";
		List<ObjectError> allErrors = bindingResult.getAllErrors();
		if (!allErrors.isEmpty()){
			errorStr = allErrors.stream()
					.map(DefaultMessageSourceResolvable::getDefaultMessage)
					.collect(Collectors.toList()).toString();
		}
		return ApiResult.error(errorStr.replace("[","").replace("]",""));
	}
}
