package com.dxhy.config;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.dxhy.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.dxhy.auth.client.interceptor.UserAuthRestInterceptor;
import com.dxhy.common.handler.GlobalExceptionHandler;

/**
 * @author: jiaohongyang
 * @date: 2019年3月26日 下午6:02:48
 *
 */
@SuppressWarnings("AlibabaMethodTooLong")
@Configuration("flowWebConfig")
@Primary
public class FlowWebConfiguration implements WebMvcConfigurer {
    @Bean
    GlobalExceptionHandler getGlobalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getServiceAuthRestInterceptor()).addPathPatterns(getIncludePathPatterns())
            .addPathPatterns("/api/user/validate");
        registry.addInterceptor(getUserAuthRestInterceptor()).addPathPatterns(getIncludePathPatterns());
    }

    @Bean
    ServiceAuthRestInterceptor getServiceAuthRestInterceptor() {
        return new ServiceAuthRestInterceptor();
    }

    @Bean
    UserAuthRestInterceptor getUserAuthRestInterceptor() {
        return new UserAuthRestInterceptor();
    }

    /**
     * 需要用户和服务认证判断的路径
     *
     * @return
     */
    private ArrayList<String> getIncludePathPatterns() {
        ArrayList<String> list = new ArrayList<>();
        String[] urls = {"/cjhz/list", "/cjmx/list", "/wbfpxx/list", "/wbfpxx/insert", "/receipt/**", "/caution/**",
            "/fprz/**", "/yqsq/**", "/get/**", "/smgx/**", "/sggx/**", "/drgx/**", "/gx/**", "/ygxfp/**", "/gxfp/**",
            "/post/**", "/rzzhcx/**", "/qyxx/**", "/jks/**", "/collect/**", "/customsRecordRzdk/**", "/custom/**",
            "/sign/**", "/tax_drawback/**", "/customsRefund/**", "/countExport/**", "/exportCusRzdk/**",
            "/exportVatRzdk/**", "/smcy/info", "/fpmx/info", "/smycy/info", "/excelcy/info", "/cyls/list",
            "/cyzhcx/list", "/cyls/del", "/cytj/list", "/caution/**", "/bb/**", "/report/**", "/message/*",
            "/cyls/detail", "/smycy/updateInfo", "/monit/definitve/**", "/modules/**", "/monit/abnormalinvoice/**",
            "/monit/record/**", "/getOrgType", "/excel/apply", "/ftp/download", "/scan/get/scaninfo",
            "/passengerTicket/**", "/img/**", "/scan/**", "/mixedSignature/**", "/sgqs/list", "/sgqs/fpqs",
            "/smqs/fpqs", "/smqs/del", "/smyqs/fpqs", "/smxx/update", "/excelqs/fpqs", "/qsxx/list", "/qsxx/ecqs",
            "/sgqs/info", "/yqsxx/cancle", "/batchDownloadImg", "/yqsxx/change/business", "/elec/**", "/getRzhYesNo",
            "/yqsxx/addRemark", "/getRecord", "/forceSign", "/qsxx/batchDel", "/delInvoice/list", "/smcy/info",
            "/fpmx/info", "/smycy/info", "/excelcy/info", "/cyls/list", "/cyzhcx/list", "/cyls/del", "/cytj/list",
            "/cyls/detail", "/smycy/updateInfo", "/qsxx/listMRYX", "/cancelRelate", "/saveSettle", "/updateUser",
            "/getUser", "/gxfp/tjrz", "/fprz/fpxxrz", "/fprz/fpxxrzAll", "/elecCheck/uploadFile", "/violation/list",
            "/risk/supplier", "/risk/supplier/info", "/risk/riskInvoice","/risk/enterprise/info"};
        Collections.addAll(list, urls);
        return list;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new ByteArrayHttpMessageConverter());
        // @ResponseBody 解决乱码
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        converters.add(new ResourceHttpMessageConverter());
        converters.add(new AllEncompassingFormHttpMessageConverter());
        converters.add(fastJsonHttpMessageConverter());
    }

    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        // Long类型转String类型
        SerializeConfig serializeConfig = SerializeConfig.globalInstance;
        // ToStringSerializer 是这个包 com.alibaba.fastjson.serializer.ToStringSerializer
        serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
        serializeConfig.put(Long.class, ToStringSerializer.instance);
        serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
        config.setSerializeConfig(serializeConfig);
        config.setSerializerFeatures(
            // 保留map空的字段
            SerializerFeature.WriteMapNullValue,
            // 将String类型的null转成""
            SerializerFeature.WriteNullStringAsEmpty,
            // 将Number类型的null转成0
            SerializerFeature.WriteNullNumberAsZero,
            // 将List类型的null转成[]
            SerializerFeature.WriteNullListAsEmpty,
            // 将Boolean类型的null转成false
            SerializerFeature.WriteNullBooleanAsFalse,
            // 日期格式转换
            SerializerFeature.WriteDateUseDateFormat,
            // 避免循环引用
            SerializerFeature.DisableCircularReferenceDetect,
            // 将中文都会序列化
            SerializerFeature.BrowserCompatible);

        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        // 解决中文乱码问题，相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
        List<MediaType> mediaTypeList = new ArrayList<>();
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        return converter;
    }

}
