package com.gxwebsoft.payment.exception;

import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.payment.constants.PaymentConstants;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 统一支付异常处理器
 * 处理所有支付相关的异常和参数验证异常
 *
 * @author 科技小王子
 * @since 2025-01-26
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.gxwebsoft.payment.controller", "com.gxwebsoft.shop.controller"})
public class PaymentExceptionHandler extends BaseController {

    /**
     * 处理支付业务异常
     */
    @ExceptionHandler(PaymentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<?> handlePaymentException(PaymentException e) {
        log.warn("支付业务异常: {}", e.getMessage());

        // 记录详细的异常信息
        if (e.getTenantId() != null) {
            log.warn("异常租户ID: {}", e.getTenantId());
        }

        if (e.getPaymentType() != null) {
            log.warn("异常支付类型: {}", e.getPaymentType());
        }

        if (e.getOrderNo() != null) {
            log.warn("异常订单号: {}", e.getOrderNo());
        }

        if (e.getErrorCode() != null) {
            log.warn("错误代码: {}", e.getErrorCode());
        }

        return fail(e.getMessage());
    }



    /**
     * 处理参数验证异常（@Valid注解）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        String errorMessage = fieldErrors.stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));

        log.warn("参数验证失败: {}", errorMessage);

        return fail(PaymentConstants.ErrorMessage.PARAM_ERROR + ": " + errorMessage);
    }

    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<?> handleBindException(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        String errorMessage = fieldErrors.stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));

        log.warn("数据绑定失败: {}", errorMessage);

        return fail(PaymentConstants.ErrorMessage.PARAM_ERROR + ": " + errorMessage);
    }

    /**
     * 处理约束违反异常（@Validated注解）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<?> handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();

        String errorMessage = violations.stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .collect(Collectors.joining("; "));

        log.warn("约束验证失败: {}", errorMessage);

        return fail(PaymentConstants.ErrorMessage.PARAM_ERROR + ": " + errorMessage);
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<?> handleIllegalArgumentException(IllegalArgumentException e) {
        log.warn("非法参数异常: {}", e.getMessage());
        return fail(PaymentConstants.ErrorMessage.PARAM_ERROR + ": " + e.getMessage());
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult<?> handleNullPointerException(NullPointerException e) {
        log.error("空指针异常", e);
        return fail(PaymentConstants.ErrorMessage.SYSTEM_ERROR);
    }

    /**
     * 处理其他运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult<?> handleRuntimeException(RuntimeException e) {
        log.error("运行时异常: {}", e.getMessage(), e);
        return fail(PaymentConstants.ErrorMessage.SYSTEM_ERROR);
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult<?> handleException(Exception e) {
        log.error("未知异常: {}", e.getMessage(), e);
        return fail(PaymentConstants.ErrorMessage.SYSTEM_ERROR);
    }
}
