package egovframework.service.impl;

import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import egovframework.service.AdminService;
import egovframework.service.mapper.AdminMapper;
import egovframework.util.CommonPath;
import egovframework.util.PageCriteria;
import egovframework.util.SHA256;
import egovframework.vo.AdminVO;
import egovframework.vo.PopupVO;
import egovframework.vo.StatsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RequiredArgsConstructor
@Service
public class AdminServiceImpl extends EgovAbstractServiceImpl implements AdminService {
    private final NoticeServiceImpl adminNoticeService;
    private final AdminMapper adminMapper;
    private final String ATTATCH_FILE_PATH = CommonPath.getFilePath();
    private final String IMAGE_FILE_PATH   = CommonPath.getImageUploadPath();
    private PageCriteria criteria;
    private final String[] fileExtArray = {"xls", "xlsx", "doc", "docx",
            "ppt", "pptx", "csv", "txt", "hwp", "pdf", "ai", "psd", "zip"};

    @Override
    public AdminVO getUser(String id) {
        return this.adminMapper.getUser(id);
    }

    @Override
    public List<PopupVO> getPopupList(Map<String, Object> paramMap) {
        return this.adminMapper.getPopupList(paramMap);
    }

    @Override
    public void insertPopup(Map<String, Object> paramMap) {
        this.adminMapper.insertPopup(paramMap);
    }

    @Override
    public void updatePopupUseYN(Map<String, Object> paramMap) {
        this.adminMapper.updatePopupUseYN(paramMap);
    }

    @Override
    public void deletePopup(Map<String, Object> paramMap) {
        this.adminMapper.deletePopup(paramMap);
    }

    @Override
    public void updatePopup(Map<String, Object> paramMap) {
        this.adminMapper.updatePopup(paramMap);
    }

    @Override
    public Map<String, Object> checkPrePw(Map<String, Object> paramMap) {
        return this.adminMapper.checkPrePw(paramMap);
    }

    @Override
    public void updatePw(Map<String, Object> paramMap) {
        this.adminMapper.updatePw(paramMap);
    }

    @Override
    public List<StatsVO> getDDStatus(Map<String, Object> paramMap) {
        List<StatsVO> statsArr = this.adminMapper.getDDStatus(paramMap);
        return getStatus(statsArr, 31, false);
    }

    @Override
    public List<StatsVO> getHHStatus(Map<String, Object> paramMap) {
        List<StatsVO> statsArr = this.adminMapper.getHHStatus(paramMap);
        return getStatus(statsArr, 24, true);
    }

    @Override
    public List<StatsVO> getMMStatus(Map<String, Object> paramMap) {
        List<StatsVO> statsArr = this.adminMapper.getMMStatus(paramMap);
        return getStatus(statsArr, 12, false);
    }

    public List<StatsVO> getStatus(List<StatsVO> statsArr, int arrayLength, boolean isHour) {
        for (StatsVO vo : statsArr) {

            int[] formatArray = new int[arrayLength];
            Arrays.fill(formatArray, 0);
            if (vo.getConnCnt() != null) {
                String[] statsData = vo.getDt().split(",");
                String[] connCnt   = vo.getConnCnt().split(",");
                if (vo.getConnCnt() != null) {
                    for (int ii = 0; ii < statsData.length; ii++) {
                        int dyNum = Integer.parseInt(statsData[ii]);
                        if (isHour == false) {
                            --dyNum;
                        }
                        formatArray[dyNum] = Integer.parseInt(connCnt[ii]);
                    }
                }
            }
            vo.setStatsInArr(formatArray);
        }
        return statsArr;
    }

    @Override
    public void adminLoginMake(Map<String, Object> paramMap) {
        this.adminMapper.adminLoginMake(paramMap);
    }

    @Override
    public void adminLogoutMake(Map<String, Object> paramMap) {
        this.adminMapper.adminLogoutMake(paramMap);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Map<String, Object> loginCheck(Map<String, Object> paramMap, HttpSession session) {
        Map<String,Object> resultMap = new HashMap<>();
        AdminVO userInfo = adminMapper.getUser(paramMap.get("email").toString());
        if (userInfo != null) {
            String pw = SHA256.encrypt(paramMap.get("password").toString()); // 원본
            if (userInfo.getIs_account_lock().equals("Y") ) {
                resultMap.put("msg", "3회 이상 로그인 실패로 계정 이용 불가\n관리자에게 문의하세요.");
            }
            else if (userInfo.getPassword().equals(pw)) {
                //로그인성공
                String id = userInfo.getEmail();
                session.setAttribute("userId", id);
                adminMapper.adminLoginMake(null);
                resultMap.put("code", "S");
                paramMap.put("count", 0);
                adminMapper.setFailCount(paramMap);
            }
            else {
                Map<String,Object> failCountMap = adminMapper.getFailCount(paramMap);
                int count;
                if (failCountMap == null) {
                    count = 0;
                }
                else {
                    count =  Integer.parseInt(String.valueOf(failCountMap.get("LOGIN_FAIL_COUNT")));
                }
                paramMap.put("count", ++count);
                adminMapper.setFailCount(paramMap);
                if (count > 2) {
                    adminMapper.setAcountLock(paramMap);
                    resultMap.put("msg", "3회 이상 로그인 실패로 계정 이용 불가\n관리자에게 문의하세요");
                }
                else {
                    //로그인 실패
                    resultMap.put("msg", "정보입력 " + count + " 회 오류");
                }
                resultMap.put("code", "F");
            }
        }
        else {
            resultMap.put("code", "F");
            resultMap.put("msg", "입력하신 정보를 다시 확인해주세요.");
        }
        return resultMap;
    }

}
