package com.xunhong.erp.turbo.web.handler;

import com.alibaba.cola.dto.*;
import com.github.houbb.sensitive.core.api.SensitiveUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 脱敏响应体处理
 *
 * @author hollis
 */
@ControllerAdvice
public class SensitiveResponseBodyAdvice implements ResponseBodyAdvice<Object> {
	/**
	 * 处理空格
	 *
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}

	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		// 只对特定类型的返回值执行处理逻辑，这里可以根据需要调整判断条件
		return Response.class.isAssignableFrom(returnType.getParameterType());
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		try {
			if (body instanceof SingleResponse) {
				SingleResponse<DTO> singleResponse = (SingleResponse<DTO>) body;
				if (Objects.nonNull(singleResponse.getData())) {
					Schema annotation = singleResponse.getData().getClass().getAnnotation(Schema.class);
					if (Objects.nonNull(annotation) && annotation.title().equals("系统设置")) {
						return body;
					}

					singleResponse.setData(SensitiveUtil.desCopy(singleResponse.getData()));
				}
			}

			if (body instanceof MultiResponse) {
				MultiResponse<DTO> multiResponse = (MultiResponse<DTO>) body;
				if (Objects.nonNull(multiResponse.getData())) {
					multiResponse.setData(SensitiveUtil.desCopyCollection(multiResponse.getData()));
				}
			}

			if (body instanceof PageResponse<?>) {
				PageResponse<DTO> pageResponse = (PageResponse<DTO>) body;
				if (Objects.nonNull(pageResponse.getData())) {
					pageResponse.setData(SensitiveUtil.desCopyCollection(pageResponse.getData()));
				}
			}
		} catch (Exception ignored) {

		}

		return body;
	}
}
