/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pig4cloud.pig.common.feign.sentinel.handle;

import com.alibaba.csp.sentinel.Tracer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.pig4cloud.pig.common.core.util.R;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.util.Assert;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.List;
import java.util.Set;

/**
 * 全局业务异常处理器，结合Sentinel处理系统异常
 * <p>
 * 注意：全局异常处理器不能作用在OAuth Server
 * </p>
 *
 * @author lengleng
 * @date 2025/05/31
 */
@Slf4j
@Order(10000)
@RestControllerAdvice
@ConditionalOnExpression("!'${security.oauth2.client.clientId}'.isEmpty()")
public class GlobalBizExceptionHandler {


	/**
	 * 处理控制器方法参数校验异常（如@RequestParam/@PathVariable的校验失败）
	 */
	@ExceptionHandler(HandlerMethodValidationException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R handleHandlerMethodValidationException(HandlerMethodValidationException e) {
		log.error("控制器方法参数校验失败 ex={}", e.getMessage(), e);

		List<? extends MessageSourceResolvable> errors = e.getAllErrors();
		if (!errors.isEmpty()) {
			MessageSourceResolvable firstError = errors.get(0);
			String errorMsg = firstError.getDefaultMessage();
			if (errorMsg == null && firstError.getCodes() != null && firstError.getCodes().length > 0) {
				errorMsg = firstError.getCodes()[0];
			}
			return R.failed("参数校验失败：" + (errorMsg != null ? errorMsg : "未知错误,请联系管理员"));
		}

		// 兜底提示
		return R.failed("参数校验失败，请检查请求参数");
	}


	/**
	 * 处理HTTP消息解析异常（优先捕获，包括JSON类型不匹配）
	 */
	@ExceptionHandler(HttpMessageNotReadableException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
		log.error("HTTP消息解析异常 ex={}", e.getMessage(), e);

		// 检查根原因是否为JSON映射异常（包含字段信息）
		Throwable rootCause = e.getRootCause();
		if (rootCause instanceof JsonMappingException jsonMappingEx) {
			// 提取出错的字段路径
			String fieldPath = jsonMappingEx.getPath().stream()
					.map(JsonMappingException.Reference::getFieldName)
					.reduce((a, b) -> a + "." + b)
					.orElse("");

			return R.failed("参数类型错误：字段 [" + fieldPath + "] 类型不匹配，请检查");
		}

		// 其他解析错误（如JSON格式错误）
		return R.failed("请求参数格式错误，请检查JSON格式是否正确");
	}

	/**
	 * 处理类型转换相关的异常（表单/路径参数）
	 * 包括：方法参数类型不匹配、绑定参数类型错误等
	 */
	@ExceptionHandler({
			MethodArgumentTypeMismatchException.class,
			TypeMismatchException.class
	})
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R handleTypeMismatchException(Exception e) {
		log.error("参数类型错误 ex={}", e.getMessage(), e);

		// 提取具体字段名
		String fieldName = "";
		if (e instanceof MethodArgumentTypeMismatchException methodEx) {
			fieldName = methodEx.getName();
		} else if (e instanceof TypeMismatchException typeEx && typeEx.getPropertyName() != null) {
			fieldName = typeEx.getPropertyName();
		}

		return R.failed("参数类型错误：字段 [" + fieldName + "] 类型不匹配，请检查");
	}

	/**
	 * 处理缺少参数的异常
	 */
	@ExceptionHandler(MissingServletRequestParameterException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R handleMissingParamException(MissingServletRequestParameterException e) {
		log.error("缺少请求参数 ex={}", e.getMessage(), e);
		return R.failed("缺少必要参数：[" + e.getParameterName() + "]，类型：" + e.getParameterType());
	}


	/**
	 * 全局异常.
	 * @param e the e
	 * @return R
	 */
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public R handleGlobalException(Exception e) {
		log.error("全局异常信息 ex={}", e.getMessage(), e);

		// 业务异常交由 sentinel 记录
		Tracer.trace(e);
		return R.failed(e.getLocalizedMessage());
	}

	/**
	 * 处理业务校验过程中碰到的非法参数异常 该异常基本由{@link org.springframework.util.Assert}抛出
	 * @param exception 参数校验异常
	 * @return API返回结果对象包装后的错误输出结果
	 * @see Assert#hasLength(String, String)
	 * @see Assert#hasText(String, String)
	 * @see Assert#isTrue(boolean, String)
	 * @see Assert#isNull(Object, String)
	 * @see Assert#notNull(Object, String)
	 */
	@ExceptionHandler(IllegalArgumentException.class)
	@ResponseStatus(HttpStatus.OK)
	public R handleIllegalArgumentException(IllegalArgumentException exception) {
		log.error("非法参数,ex = {}", exception.getMessage(), exception);
		return R.failed(exception.getMessage());
	}

	/**
	 * AccessDeniedException
	 * @param e the e
	 * @return R
	 */
	@ExceptionHandler(AccessDeniedException.class)
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public R handleAccessDeniedException(AccessDeniedException e) {
		String msg = SpringSecurityMessageSource.getAccessor()
			.getMessage("AbstractAccessDecisionManager.accessDenied", e.getMessage());
		log.warn("拒绝授权异常信息 ex={}", msg);
		return R.failed(msg);
	}

	/**
	 * validation Exception
	 * @param exception
	 * @return R
	 */
	@ExceptionHandler({ MethodArgumentNotValidException.class })
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R handleBodyValidException(MethodArgumentNotValidException exception) {
		// 优先处理类级别的校验错误（如@IPValidation）
		List<ObjectError> globalErrors = exception.getBindingResult().getGlobalErrors();
		if (!globalErrors.isEmpty()) {
			String errorMsg = globalErrors.get(0).getDefaultMessage();
			log.error("类级参数校验异常, ex = {}", errorMsg);
			return R.failed(errorMsg);
		}

		// 处理字段级别的校验错误
		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		if (!fieldErrors.isEmpty()) {
			FieldError firstError = fieldErrors.get(0);
			String fieldName = firstError.getField(); // 错误字段名
			String errorCode = firstError.getCode();  // 错误代码（关键：区分错误类型）
			String defaultMsg = firstError.getDefaultMessage(); // 注解中定义的message

			// 1. 如果是类型转换错误（code为"typeMismatch"）
			if ("typeMismatch".equals(errorCode)) {
				log.error("字段[{}]类型转换异常: {}", fieldName, defaultMsg);
				return R.failed("参数类型错误：字段 [" + fieldName + "] 类型不匹配，请检查");
			}

			// 2. 普通校验错误（如@NotNull、@Size等，使用注解中定义的message）
			log.error("字段[{}]校验异常: {}", fieldName, defaultMsg);
			return R.failed(defaultMsg);
		}

		// 兜底错误信息
		log.error("参数校验异常，但未获取到具体错误信息");
		return R.failed("参数校验失败");
	}

	/**
	 * validation Exception (以form-data形式传参)
	 * @param exception
	 * @return R
	 */
	@ExceptionHandler({ BindException.class })
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R bindExceptionHandler(BindException exception) {
		// 优先获取字段错误信息
		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		if (!fieldErrors.isEmpty()) {
			String errorMsg = fieldErrors.get(0).getDefaultMessage();
			log.warn("参数绑定异常,ex = {}", errorMsg);
			return R.failed("参数类型错误：" + errorMsg); // 明确提示类型错误
		}

		// 处理全局错误
		List<ObjectError> globalErrors = exception.getBindingResult().getGlobalErrors();
		if (!globalErrors.isEmpty()) {
			String errorMsg = globalErrors.get(0).getDefaultMessage();
			log.warn("参数绑定全局异常,ex = {}", errorMsg);
			return R.failed(errorMsg);
		}
		// 兜底提示
		return R.failed("参数绑定错误，请检查参数类型");
//		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
//		log.warn("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
//		return R.failed(fieldErrors.get(0).getDefaultMessage());
	}

	/**
	 * 保持和低版本请求路径不存在的行为一致
	 * <p>
	 * <a href="https://github.com/spring-projects/spring-boot/issues/38733">[Spring Boot
	 * 3.2.0] 404 Not Found behavior #38733</a>
	 * @param exception
	 * @return R
	 */
	@ExceptionHandler({ NoResourceFoundException.class })
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public R notFoundExceptionHandler(NoResourceFoundException exception) {
		log.debug("请求路径 404 {}", exception.getMessage());
		return R.failed(exception.getMessage());
	}

	// 新增：处理自定义校验注解异常
	@ExceptionHandler(ConstraintViolationException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R handleConstraintViolationException(ConstraintViolationException exception) {
		Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
		// 避免空集合导致的类似错误
		if (violations.isEmpty()) {
			return R.failed("参数校验失败，但未获取到具体错误信息");
		}
		// 获取第一个错误信息（自定义校验器中设置的message）
		String errorMsg = violations.iterator().next().getMessage();
		log.warn("自定义校验异常: {}", errorMsg);
		return R.failed(errorMsg);
	}

}
