package egovframework.com.its.web.server.service;


import egovframework.com.its.web.server.mapper.AdminMapper;
import egovframework.com.its.web.server.util.PageCriteria;
import egovframework.com.its.web.server.util.SHA256;
import egovframework.com.its.web.server.vo.*;
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 AdminService {
    private final NoticeService adminNoticeService;
    private final AdminMapper adminMapper;
//    @Autowired
//    CommonPath commonPath;
//    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"};

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

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

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

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

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

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

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

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

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

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

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

    public List<PeriodStatVO> getYearStatsList(Map<String, Object> paramMap) {
        return this.adminMapper.getYearStatsList(paramMap);
    }
    public List<PeriodStatVO> getMonthStatsList(Map<String, Object> paramMap) {
        return this.adminMapper.getMonthStatsList(paramMap);
    }
    public List<PeriodStatVO> getHourStatsList(Map<String, Object> paramMap) {
        return this.adminMapper.getHourStatsList(paramMap);
    }

    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;
    }

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

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

    @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);
                Integer failCount = adminMapper.getFailCount(paramMap);
                int count;
                if (failCount == null) {
                    count = 0;
                }
                else {
                    count = failCount;
//                    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;
    }

}
