package com.diagbot.config;

import com.diagbot.util.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;

/**
 * @Description: 权限资源配置类
 * @author: gaodm
 * @time: 2018/8/2 14:21
 */
@Configuration
@EnableResourceServer
@ComponentScan({"com.diagbot.config"})
public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
    Logger log = LoggerFactory.getLogger(ResourceServerConfigurer.class);
    @Autowired
    private AuthExceptionEntryPoint authExceptionEntryPoint;
    @Autowired
    private AccessDeniedExceptionPoint accessDeniedExceptionPoint;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .exceptionHandling().authenticationEntryPoint(authExceptionEntryPoint)
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedExceptionPoint)
                .and()
                .csrf().disable()
                .authorizeRequests()
                .regexMatchers(".*swagger.*", ".*v2.*", ".*webjars.*", "/druid.*", "/actuator.*", "/hystrix.*").permitAll()
                .antMatchers("/sys/user/getJwt").permitAll()
                .antMatchers("/sys/user/getCaptcha").permitAll()
                .antMatchers("/sys/user/getHospitalMark").permitAll()
                .antMatchers("/sys/user/getJwtNoPass").permitAll()
                .antMatchers("/sys/user/refreshJwt").permitAll()
                .antMatchers("/sys/user/checkToken").permitAll()
                .antMatchers("/sys/dictionaryInfo/getDictionary").permitAll()
                .antMatchers("/oauth/token").permitAll()
                .antMatchers("/oauth/check_token").permitAll()
                .antMatchers("/cache/clear").permitAll()
                .antMatchers("/qc/behospitalInfo/execule").permitAll()
                .antMatchers("/qc/behospitalInfo/analyze_rpc").permitAll()
                .antMatchers("/qc/behospitalInfo/analyze_api").permitAll()
                .antMatchers("/qc/behospitalInfo/analyze_run").permitAll()
                .antMatchers("/qc/module/getById").permitAll()
                .antMatchers("/qc/module/getModuleMap").permitAll()
                .antMatchers("/qc/cases/getQcCases").permitAll()
                .antMatchers("/qc/behospitalInfo/page").permitAll()
                .antMatchers("/qc/casesEntryHospital/getQcCasesEntryAll").permitAll()
                .antMatchers("/qc/casesEntryHospital/getQcCasesAll").permitAll()
                .antMatchers("/qc/behospitalInfo/getByBehospitalCode").permitAll()
                .antMatchers("/bas/dept/getList").permitAll()
                .antMatchers("/bas/dept/getListUser").permitAll()
                .antMatchers("/qc/behospitalInfo/page_dept").permitAll()
                .antMatchers("/qc/behospitalInfo/page_person").permitAll()
                .antMatchers("/qc/behospitalInfo/page_group").permitAll()
                .antMatchers("/qc/casesEntryHospital/findQcCasesEntry").permitAll()
                .antMatchers("/qc/dataimport/import").permitAll()
//                .antMatchers("/qc/dataimport/test").permitAll()
                .antMatchers("/qc/behospitalInfo/exportExcel").permitAll()
                .antMatchers("/qc/behospitalInfo/exportQcresult").permitAll()
                .antMatchers("/qc/behospitalInfo/exportQcresultByDept").permitAll()
                .antMatchers("/qc/behospitalInfo/exportQcresultByGroup").permitAll()
                .antMatchers("/qc/abnormal/getQcAnnormalMode").permitAll()
//                .antMatchers("/qc/dataimport/import").permitAll()
                .antMatchers("/qc/dataimport/dataimportPrepare").permitAll()
//                .antMatchers("/qc/dataimport/test").permitAll()
                .antMatchers("/sys/user/pageset/getPageSet").permitAll()
                .antMatchers("/sys/user/pageset/savePageSet").permitAll()
                .antMatchers("/sys/user/pageset/getDefultPageSet").permitAll()
                .antMatchers("/consoleByDept/getDept").permitAll()
                .antMatchers("/console/entryRejectPercent").permitAll()
                .antMatchers("/console/qcResultLevelPercent").permitAll()
                .antMatchers("/console/averageStatistics").permitAll()
                .antMatchers("/console/entryByDept").permitAll()
                .antMatchers("/console/entryCountGroupByCase").permitAll()
                .antMatchers("/console/entryCountGroupByCasePage").permitAll()
                .antMatchers("/console/entryCountGroupByEntry").permitAll()
                .antMatchers("/console/entryCountGroupByEntryPage").permitAll()
                .antMatchers("/console/entryCountGroupXYByEntryPage").permitAll()
                .antMatchers("/console/entryGroupByEntryInnerPage").permitAll()
                .antMatchers("/console/getAverageDayNum").permitAll()
                .antMatchers("/console/getAverageDayNumPage").permitAll()
                .antMatchers("/console/getAverageFee").permitAll()
                .antMatchers("/console/getAverageFeePage").permitAll()
                .antMatchers("/console/getAverageScore").permitAll()
                .antMatchers("/console/getAverageScoreByDeptClass").permitAll()
                .antMatchers("/console/getAverageScoreByDeptPage").permitAll()
                .antMatchers("/console/getLevelResultDept").permitAll()
                .antMatchers("/console/homePageLevelLimit").permitAll()
                .antMatchers("/console/homePageLevelStatistics").permitAll()
                .antMatchers("/console/homePageLevelStatisticsXY").permitAll()
                .antMatchers("/consoleByDept/homePageLevelStatisticsXYByDept").permitAll()
                .antMatchers("/print/export/homePageLevelXYExportByDept").permitAll()
                .antMatchers("/consoleByDept/entryCountGroupXYByEntryPageDept").permitAll()
                .antMatchers("/print/export/entryCountGroupXYByExportDept").permitAll()
                .antMatchers("/consoleByDept/qcResultShortXYPageByDept").permitAll()
                .antMatchers("/print/export/qcResultShortXYPageExportDept").permitAll()
                .antMatchers("/consoleByDept/badLevelXYPageByDept").permitAll()
                .antMatchers("/print/export/badUnQualifiedLevelPageXYExportByDept").permitAll()
                .antMatchers("/print/export/badQualifiedLevelPageXYExportByDept").permitAll()
                .antMatchers("/console/leaveHosCount").permitAll()
                .antMatchers("/console/medicalRecordIndicator").permitAll()
                .antMatchers("/console/codingMonthly").permitAll()
                .antMatchers("/console/levelPercentGroupByDeptPage").permitAll()
                .antMatchers("/console/levelStatistics").permitAll()
                .antMatchers("/console/levelStatisticsByDeptClass").permitAll()
                .antMatchers("/console/mrCount").permitAll()
                .antMatchers("/console/mrStatistics").permitAll()
                .antMatchers("/console/qcResultShortPage").permitAll()
                .antMatchers("/console/qcResultShortXYPage").permitAll()
                .antMatchers("/console/resultStatistics").permitAll()
                .antMatchers("/console/resultStatisticsByDeptPage").permitAll()
                .antMatchers("/console/homePageMRCount").permitAll()
                .antMatchers("/console/qcCheckStatistics").permitAll()
                .antMatchers("/console/unModifyMRStatistics").permitAll()
                .antMatchers("/console/unModifyMRPage").permitAll()
                .antMatchers("/console/reHos31DaysPage").permitAll()
                .antMatchers("/console/beHosCount").permitAll()
                .antMatchers("/console/casesEntryStatisticsById").permitAll()
                .antMatchers("/console/hmImproveMRPage").permitAll()
                .antMatchers("/console/qcCheckMRPage").permitAll()
                .antMatchers("/consoleByDept/entryCountGroupByCaseAndDept").permitAll()
                .antMatchers("/consoleByDept/entryCountGroupByCaseAndDeptPage").permitAll()
                .antMatchers("/consoleByDept/entryCountGroupByEntryAndDept").permitAll()
                .antMatchers("/consoleByDept/entryCountGroupByEntryAndDeptPage").permitAll()
                .antMatchers("/consoleByDept/entryGroupByEntryAndDeptInnerPage").permitAll()
                .antMatchers("/consoleByDept/homePageLevelByDeptLimit").permitAll()
                .antMatchers("/consoleByDept/homePageLevelStatisticsByDept").permitAll()
                .antMatchers("/consoleByDept/leaveHosCountByDept").permitAll()
                .antMatchers("/consoleByDept/levelStatisticsByDept").permitAll()
                .antMatchers("/consoleByDept/mrCountByDept").permitAll()
                .antMatchers("/consoleByDept/qcResultShortByDeptPage").permitAll()
                .antMatchers("/consoleByDept/resultStatisticsByDeptAndDoctorPage").permitAll()
                .antMatchers("/console/entryStatistics").permitAll()
                .antMatchers("/qc/data/sendDoctorInfos").permitAll()
                .antMatchers("/qc/data/sendDeptInfos").permitAll()
                .antMatchers("/qc/data/sendRecordTypes").permitAll()
                .antMatchers("/qc/data/sendMrRecordIng").permitAll()
                .antMatchers("/qc/data/sendMrContent").permitAll()
                .antMatchers("/qc/data/sendMrRecord").permitAll()
                .antMatchers("/qc/data/sendPatientInfo").permitAll()
                .antMatchers("/qc/data/sendDoctorAdvice").permitAll()
                .antMatchers("/qc/data/sendHomePageIng").permitAll()
                .antMatchers("/qc/data/sendHomePage").permitAll()
                .antMatchers("/qc/data/sendHomeDiagnose").permitAll()
                .antMatchers("/qc/data/sendHomeOperation").permitAll()
                .antMatchers("/qc/data/sendCrisis").permitAll()
                .antMatchers("/qc/data/deleteFlag").permitAll()
                .antMatchers("/qc/data/placeFile").permitAll()
                .antMatchers("/qc/data/sendLisResults").permitAll()
                .antMatchers("/qc/data/sendPacsResults").permitAll()
                .antMatchers("/qc/data/getColumnZhAndCh").permitAll()
                .antMatchers("/qc/data/analyseRec").permitAll()
                .antMatchers("/qc/data/hisDataDeal").permitAll()
                .antMatchers("/qc/data_str/**").permitAll()
                .antMatchers("/qc/doctoradvice/getPage").permitAll()
                .antMatchers("/qc/medPacsInfo/getCheckPage").permitAll()
                .antMatchers("/qc/medLisInfo/getExaminePage").permitAll()
                .antMatchers("/qc/medLisInfo/getExamineSonPage").permitAll()
                .antMatchers("/console/medicalCheckForm").permitAll()
                .antMatchers("/qc/behospitalInfo/analyzeCds").permitAll()
                .antMatchers("/console/medicalCheckTitle").permitAll()
                .antMatchers("/console/badLevelPage").permitAll()
                .antMatchers("/console/badLevelXYPage").permitAll()
                .antMatchers("/console/export/badUnQualifiedLevelPagePageExport").permitAll()
                .antMatchers("/console/export/badQualifiedLevelPagePageExport").permitAll()
                .antMatchers("/console/export/badUnQualifiedLevelPageXYExport").permitAll()
                .antMatchers("/console/export/badQualifiedLevelPageXYExport").permitAll()
                .antMatchers("/qc/medNurse/getMedNursePage").permitAll()
                .antMatchers("/qc/medRecordOther/getMedRecordOtherPage").permitAll()
                .antMatchers("/qc/medRecordOther/getMedRecordContentOther").permitAll()
                .antMatchers("/qc/behospitalInfo/exportQcresultByPerson").permitAll()
                .antMatchers("/consoleByDept/beHosCountByDept").permitAll()
                .antMatchers("/consoleByDept/casesEntryStatisticsByDept").permitAll()
                .antMatchers("/bas/doctor/getList").permitAll()
                .antMatchers("/consoleByDept/homePageOrGoodLevelByDept").permitAll()
                .antMatchers("/print/export/homePageLevelExportByDept").permitAll()
                .antMatchers("/print/export/homeUnQualifiedPageOrLevelExportByDept").permitAll()
                .antMatchers("/print/export/homeQualifiedPageOrLevelExportByDept").permitAll()
                .antMatchers("/print/export/entryGroupExportByDeptPage").permitAll()
                .antMatchers("/print/export/entryGroupExportByDeptCase").permitAll()
                .antMatchers("/print/export/entryGroupExportByDeptEntry").permitAll()
                .antMatchers("/print/export/qcResultShortExportByDeptPage").permitAll()
                .antMatchers("/print/export/levelExportByDept").permitAll()
                .antMatchers("/consoleByDept/entryStatisticsByDept").permitAll()
                .antMatchers("/print/export/entryStatisticsExportByDept").permitAll()
                .antMatchers("/consoleByDept/leaveHosMRPageByDept").permitAll()
                .antMatchers("/print/export/leaveHosMrPageExportByDept").permitAll()
                .antMatchers("/consoleByDept/qcCheckStatisticsByDept").permitAll()
                .antMatchers("/print/export/qcCheckStaExportByDept").permitAll()
                .antMatchers("/consoleByDept/qcCheckMRPageByDept").permitAll()
                .antMatchers("/print/export/qcCheckMRPageExportByDept").permitAll()
                .antMatchers("/consoleByDept/hmImproveMRPageByDept").permitAll()
                .antMatchers("/print/export/improveMRExportByDept").permitAll()
                .antMatchers("/consoleByDept/reHos31DaysPageByDept").permitAll()
                .antMatchers("/print/export/reHos31DaysPageExportByDept").permitAll()
                .antMatchers("/consoleByDept/unModifyMRSByDept").permitAll()
                .antMatchers("/print/export/unModifyMRSExportByDept").permitAll()
                .antMatchers("/consoleByDept/unModifyMRPageByDept").permitAll()
                .antMatchers("/print/export/unModifyMRPageExportByDept").permitAll()
                .antMatchers("/consoleByDept/medicalCheckFormKs").permitAll()
                .antMatchers("/print/export/medicalCheckExportByDept").permitAll()
                .antMatchers("/consoleByDept/medicalCheckTitleKs").permitAll()
                .antMatchers("/console/qualityControl").permitAll()
                .antMatchers("/console/export/**").permitAll()
                .antMatchers("/consoleByDept/qualityControlByDept").permitAll()
                .antMatchers("/print/export/**").permitAll()
                .antMatchers("/qc/behospitalInfo/getMedQualityCoList").permitAll()
                .antMatchers("/console/saveMedicaIndicator").permitAll()
                .antMatchers("/qc/medCheckInfo/createMedBeHospitalInfoType").permitAll()
                .antMatchers("/qc/medCheckInfo/addMedCheckInfo").permitAll()
                .antMatchers("/qc/medCheckInfo/getDataEdit").permitAll()
                .antMatchers("/qc/medCheckInfo/saveDataEdit").permitAll()
                .antMatchers("/qc/analysis/addMedClickInfo").permitAll()
                .antMatchers("/qc/analysis/getQcClickDeptList").permitAll()
                .antMatchers("/qc/analysis/getQcClick").permitAll()
                .antMatchers("/qc/analysis/getQcClickByExport").permitAll()
                .antMatchers("/qc/analysis/getQcClickInnerPage").permitAll()
                .antMatchers("/qc/analysis/getQcClickInnerPageByExport").permitAll()
                .antMatchers("/qc/analysis/getEntryDefectImprove").permitAll()
                .antMatchers("/qc/analysis/getEntryDefectImproveByExport").permitAll()
                .antMatchers("/qc/analysis/getEntryDefectImproveInner").permitAll()
                .antMatchers("/qc/analysis/getDefectImproveInnerByExport").permitAll()
                .antMatchers("/qc/analysisDept/getEntryDefectImproveDept").permitAll()
                .antMatchers("/qc/analysisDept/getEntryDefectImproveByDeptExport").permitAll()
                .antMatchers("/qc/analysisDept/getEntryDefectImproveInnerDept").permitAll()
                .antMatchers("/qc/analysisDept/getDefectImproveInnerByDeptExport").permitAll()
                .antMatchers("/qc/behospitalInfo/historyAnalyze").permitAll()
                .antMatchers("/qc/behospitalInfo/operationLog").permitAll()
                .antMatchers("/qc/behospitalInfo/decodeData").permitAll()
                .antMatchers("/qc/behospitalInfo/encryptData").permitAll()
                .antMatchers("/qc/appealExamineInfo/getComplaintRecord").permitAll()
                .antMatchers("/qc/appealExamineInfo/getAppealReview").permitAll()
                .antMatchers("/qc/appealExamineInfo/approved").permitAll()
                .antMatchers("/qc/appealExamineInfo/rejected").permitAll()
                .antMatchers("/qc/appealExamineInfo/getApprovedView").permitAll()
                .antMatchers("/qc/appealExamineInfo/getAppealReviewDictionary").permitAll()
                .antMatchers("/qc/appealExamineInfo/getAuditNumber").permitAll()
                .antMatchers("/qc/appealExamineInfo/getAppealReviewExport").permitAll()
                .antMatchers("/qc/appealExamineInfo/getComplaintRecordExport").permitAll()
                .antMatchers("/qc/appealExamineInfo/getComplaintDetailMsg").permitAll()
                .antMatchers("/qc/appealInfo/addAppealInfo").permitAll()
                .antMatchers("/qc/appealInfo/addAppealInfoApi").permitAll()
                .antMatchers("/qc/appealInfo/getReviewer").permitAll()
                .antMatchers("/qc/appealInfo/getReviewerApi").permitAll()
                .antMatchers("/qc/behospitalInfo/addCase").permitAll()
                .antMatchers("/qc/appealInfo/delCase").permitAll()
                .antMatchers("/qc/appealInfo/logicDelCase").permitAll()
                .antMatchers("/qc/appealInfo/updCase").permitAll()
                .antMatchers("/qc/appealInfo/getAppealOperationType").permitAll()
                .antMatchers("/qc/appealInfo/cancelAppealInfo").permitAll()
                .antMatchers("/qc/appealInfo/cancelAppealInfoApi").permitAll()
                .antMatchers("/qc/appealInfo/getAppealInfo").permitAll()
                .antMatchers("/qc/appealInfo/getAppealDept").permitAll()
                .antMatchers("/qc/appealInfo/getAppealMode").permitAll()
                .antMatchers("/qc/appealInfo/getUserRole").permitAll()
                .antMatchers("/qc/mode/getModes").permitAll()
                .antMatchers("/consoleByDoctor/**").permitAll()
                .antMatchers("/qc/getDoctorDetail/**").permitAll()
                .antMatchers("/qcView/data/*").permitAll()
                .antMatchers("/medDefectFeedback/*").permitAll()
                .antMatchers("/consoleByDoctor/**").permitAll()
                .antMatchers("/qc/getDoctorDetail/**").permitAll()
                .antMatchers("/medNewsNotice/**").permitAll()
                .antMatchers("/h5/statistics/**").permitAll()
                .antMatchers("/logManage/**").permitAll()
                .antMatchers("/qc/qcType/add").permitAll()
                .antMatchers("/qc/qcType/update").permitAll()
                .antMatchers("/qc/qcType/copy").permitAll()
//                .antMatchers("/medNewsNotice/**").permitAll()
                .antMatchers("/str/FirstRecord/infos").permitAll()
                .antMatchers("/str/WardRecord/infos").permitAll()
                .antMatchers("/str/ConsultationApply/infos").permitAll()
                .antMatchers("/str/ConsultationResult/infos").permitAll()
                .antMatchers("/str/OperativeFirstRecord/infos").permitAll()
                .antMatchers("/str/DeathDiscussion/infos").permitAll()
                .antMatchers("/str/PreoperativeDiscussion/infos").permitAll()
                .antMatchers("/str/OperativeNote/infos").permitAll()
                .antMatchers("/str/IllCritically/infos").permitAll()
                .antMatchers("/str/DeathNote/infos").permitAll()
                .antMatchers("/str/LeaveHospital/infos").permitAll()
                .antMatchers("/str/CrisisNote/infos").permitAll()
                .antMatchers("/str/RescueNote/infos").permitAll()
                .antMatchers("/str/TransferOutNote/infos").permitAll()
                .antMatchers("/str/TransferInNote/infos").permitAll()
                .antMatchers("/str/AdmissionNote/infos").permitAll()
                .antMatchers("/str/DifficultCase/infos").permitAll()
                .antMatchers("/str/BloodTransfusion/infos").permitAll()
                .antMatchers("/str/PeriodConclusion/infos").permitAll()
                .antMatchers("/str/IllSeriousl/infos").permitAll()
                .antMatchers("/**").authenticated();
        //                .antMatchers("/**").permitAll();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        log.info("Configuring ResourceServerSecurityConfigurer");
        resources.resourceId("user-service").tokenStore(new MyJwtTokenStore(jwtTokenEnhancerClient(),redisUtils));
        resources.authenticationEntryPoint(authExceptionEntryPoint);
        resources.accessDeniedHandler(accessDeniedExceptionPoint);
    }

    @Autowired
    private CustomAccessTokenConverter customAccessTokenConverter;

    @Bean("jwtTokenEnhancerClient")
    protected JwtAccessTokenConverter jwtTokenEnhancerClient() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        Resource resource = new ClassPathResource("public.cert");
        String publicKey;
        try {
            publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        converter.setVerifierKey(publicKey);
        //不设置这个会出现 Cannot convert access token to JSON
        converter.setVerifier(new RsaVerifier(publicKey));
        converter.setAccessTokenConverter(customAccessTokenConverter);
        log.info("Created jwtTokenEnhancerClient success");
        return converter;
    }
}
