package com.dbnt.kcscbackend.admin.logs.service;

import com.dbnt.kcscbackend.admin.logs.entity.ThAttachFileLog;
import com.dbnt.kcscbackend.admin.logs.entity.ThLoginLog;
import com.dbnt.kcscbackend.admin.logs.entity.ThPrivacyLog;
import com.dbnt.kcscbackend.admin.logs.entity.TnDailyUserLog;
import com.dbnt.kcscbackend.admin.logs.repository.FileLogsRepository;
import com.dbnt.kcscbackend.admin.logs.repository.PrivacyLogsRepository;
import com.dbnt.kcscbackend.admin.logs.repository.ThLoginLogRepository;
import com.dbnt.kcscbackend.admin.logs.repository.UserLogsRepository;
import com.dbnt.kcscbackend.file.entity.TnAttachFile;
import com.dbnt.kcscbackend.standardCode.entity.TnDocumentInfo;
import com.dbnt.kcscbackend.standardCode.repository.TnDocumentInfoRepository;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AdminLogsService extends EgovAbstractServiceImpl {

    private final PrivacyLogsRepository privacyLogsRepository;
    private final ThLoginLogRepository loginLogRepository;
    private final UserLogsRepository userLogsRepository;
    private final FileLogsRepository fileLogsRepository;
    private final TnDocumentInfoRepository documentInfoRepository;

    public Map<String, Object> selectPrivacyList() {
        Map<String, Object> resultMap = new HashMap<>();

        // 전체 레코드 수 가져오기
        long totalRecordCount = privacyLogsRepository.count();

        // 개수를 resultMap에 추가
        resultMap.put("resultCnt", String.valueOf(totalRecordCount));

        // 개인 정보 로그 리스트 가져오기
        List<ThPrivacyLog> privacyLogList = privacyLogsRepository.findAllByOrderByUplSeqDesc();

        // 결과를 resultMap에 추가
        resultMap.put("resultList", privacyLogList);

        return resultMap;
    }

    @Transactional
    public void insertPrivacyLog(String userId, String ipAddress, String accessType, String targetUserId){
        ThPrivacyLog log = new ThPrivacyLog();
        log.setUserId(userId);
        log.setAccessDt(LocalDateTime.now());
        log.setIpAddress(ipAddress);
        log.setAccessType(accessType);
        log.setTargetUserId(targetUserId);
        privacyLogsRepository.save(log);
    }

    @Transactional
    public void insertLoginLog(String userId, String ipAddress, String accessToken, String accessType, String webType){
        ThLoginLog loginLog = new ThLoginLog();
        loginLog.setUserId(userId);
        loginLog.setIpAddress(ipAddress);
        loginLog.setSessionId(accessToken);
        loginLog.setAccessType(accessType);
        loginLog.setAccessDt(LocalDateTime.now());
        loginLogRepository.save(loginLog);

        // 로그인 기록이면 tn_daily_yser_log 카운트 조정
        if(accessType.equals("Y")){
            //오늘 일자 로그 조회
            TnDailyUserLog userConnLog = userLogsRepository.findByLogDt(LocalDate.now()).orElse(null);
            if(userConnLog==null){
                userConnLog = new TnDailyUserLog();
                userConnLog.setLogDt(LocalDate.now());
                userConnLog.setLogCnt(0L);
                userConnLog.setMobileCnt(0L);
                userConnLog.setPcCnt(0L);
            }
            if(webType.equals("PC")){
                userConnLog.setPcCnt(userConnLog.getPcCnt()+1);
            }else{
                userConnLog.setMobileCnt(userConnLog.getMobileCnt()+1);
            }
            //같은 일자 로그인 기록 확인
            LocalDateTime now = LocalDateTime.now();
            now = now.minusHours(now.getHour());
            now = now.minusMinutes(now.getMinute());
            now = now.minusSeconds(now.getSecond());
            List<ThLoginLog> todayLoginLog = loginLogRepository.findByUserIdAndAccessDtAfter(userId, now);
            if(todayLoginLog.size()==1){
                userConnLog.setLogCnt(userConnLog.getLogCnt()+1);
            }
            userLogsRepository.save(userConnLog);

        }
    }

    @Transactional
    public void insertFileLog(TnAttachFile tnAttachFile, String accessId, String ipAddress){
        TnDocumentInfo documentInfo = documentInfoRepository.findByDocFileGrpId(tnAttachFile.getFileSeq().toString()).orElse(null);
        ThAttachFileLog fileLog = new ThAttachFileLog();
        fileLog.setFileSeq((long)tnAttachFile.getFileSeq());
        fileLog.setAccessType("FILE_DOWN");
        fileLog.setAccessId(accessId);
        fileLog.setAccessDt(LocalDateTime.now());
        fileLog.setIpAddress(ipAddress);
        switch (documentInfo.getKcscCd().split(" ")[0]){
            case "KDS": fileLog.setGroupCurCd("10"); break;
            case "KCS": fileLog.setGroupCurCd("20"); break;
            case "SMCS": fileLog.setGroupCurCd("40"); break;
            case "EXCS": fileLog.setGroupCurCd("50"); break;
            case "KRCCS": fileLog.setGroupCurCd("60"); break;
            case "KRACS": fileLog.setGroupCurCd("70"); break;
            case "LHCS": fileLog.setGroupCurCd("80"); break;
            case "KWCS": fileLog.setGroupCurCd("90"); break;
        }
        fileLogsRepository.save(fileLog);
    }
}
