package kr.co.uplus.ez.api.sysMgt;

import kr.co.uplus.ez.api.calculate.dto.CalcListResDto;
import kr.co.uplus.ez.api.comm.FileService;
import kr.co.uplus.ez.api.homeMgt.dto.NoticeListReqDto;
import kr.co.uplus.ez.api.sysMgt.dto.*;
import kr.co.uplus.ez.common.data.ApiResponseCode;
import kr.co.uplus.ez.common.data.Paging;
import kr.co.uplus.ez.common.utils.EncryptionUtil;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

@Service
@Slf4j
public class SysMgtService {

	private static final Logger logger = LoggerFactory.getLogger(SysMgtService.class);

	@Autowired
	@Qualifier("sqlSessionTemplateDb1")
	private SqlSessionTemplate sqlSessionMaster;

	@Autowired
	@Qualifier("sqlSessionTemplateDb2")
	private SqlSessionTemplate sqlSessionSlave;
	
	@Autowired
	FileService fileService;
	
	// 파일위치
	@Value("${hubeasy_file_info.work-location}") private String dirWorkState;
	
	// @Value("${spring.servlet.multipart.location}")
	private String uploadPath = "/efs/admin";

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 관리자 목록 조회
	 * @param adminListReqDto
	 * @return AdminListResDto
	 */
	public AdminListResDto adminList(AdminListReqDto adminListReqDto) {

		SysMgtMapper sysMgtMapper = sqlSessionSlave.getMapper(SysMgtMapper.class);

		String nowPage = String.valueOf(adminListReqDto.getPage());
		int totalCnt = sysMgtMapper.selectAdmUserTotalCnt(adminListReqDto);


		if(totalCnt == 0) {
			Paging paging = new Paging();
			paging.setPage(nowPage);
			paging.setTotalCnt(String.valueOf(totalCnt));
			AdminListRes adminListRes = new AdminListRes();
			adminListRes.setList(new ArrayList<>());
			adminListRes.setPaging(paging);
			return new AdminListResDto(ApiResponseCode.CM_NOT_FOUND, adminListRes);
		}

		int page = adminListReqDto.getPage();
		int pagePerRows = adminListReqDto.getPagePerRows();
		page = (page -1) * pagePerRows;
		adminListReqDto.setPage(page);

		List<AdminInfo> adminInfos =  sysMgtMapper.selectAdminList(adminListReqDto);

		Paging paging = new Paging();
		paging.setPage(nowPage);
		paging.setTotalCnt(String.valueOf(totalCnt));

		AdminListRes adminListRes = new AdminListRes();
		adminListRes.setList(adminInfos);
		adminListRes.setPaging(paging);

		return new AdminListResDto(ApiResponseCode.SUCCESS, adminListRes);
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 마당ID 조회
	 * @return SearchMadangIdResDto
	 */
	public SearchMadangIdResDto searchMadangId(SearchMadangIdReqDto searchMadangIdReqDto) {

		SysMgtMapper sysMgtMapper = sqlSessionSlave.getMapper(SysMgtMapper.class);
		SearchMadangId MadangId = new SearchMadangId();
		try {
			MadangId = sysMgtMapper.selectSearchMadangId(searchMadangIdReqDto);

			if(MadangId == null) {
				return new SearchMadangIdResDto(ApiResponseCode.CM_NOT_FOUND);
			}

		} catch (Exception e) {
			return new SearchMadangIdResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new SearchMadangIdResDto(ApiResponseCode.SUCCESS, MadangId);
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 관리자 등록
	 * @param insertAdminReqDto
	 * @return InsertAdminResDto
	 */
	public InsertAdminResDto insertAdmin(InsertAdminReqDto insertAdminReqDto) {

		SysMgtMapper sysMgtMapper = sqlSessionMaster.getMapper(SysMgtMapper.class);

		// 관리자 ID 중복체크.
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("searchType", "01");
		paramMap.put("adminId", insertAdminReqDto.getMadangId());
		int checkId = sysMgtMapper.checkAdmin(paramMap);
		if(checkId > 0){
			return new InsertAdminResDto(ApiResponseCode.CE_DUPLICATE_ID);
		}

		String encPw =  EncryptionUtil.getCustomSHA512(insertAdminReqDto.getMadangId(),  insertAdminReqDto.getAdminPw());
		insertAdminReqDto.setAdminPw(encPw);

		try {
			sysMgtMapper.insertAdmUser(insertAdminReqDto);
		} catch (Exception e) {
			return new InsertAdminResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new InsertAdminResDto(ApiResponseCode.SUCCESS);
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 관리자 수정
	 * @param updateAdminReqDto
	 * @return UpdateAdminResDto
	 */
	public UpdateAdminResDto updateAdmin(UpdateAdminReqDto updateAdminReqDto) {
		SysMgtMapper sysMgtMapper = sqlSessionMaster.getMapper(SysMgtMapper.class);

		if(StringUtils.isNotBlank(updateAdminReqDto.getAdminPw())) {
			String encPw =  EncryptionUtil.getCustomSHA512(updateAdminReqDto.getAdminId(),  updateAdminReqDto.getAdminPw());
			updateAdminReqDto.setAdminPw(encPw);
		}

		try {
			sysMgtMapper.updateAdmUser(updateAdminReqDto);
		} catch (Exception e) {
			return new UpdateAdminResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new UpdateAdminResDto(ApiResponseCode.SUCCESS);
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 관리자 삭제
	 * @param deleteAdminReqDto
	 * @return DeleteAdminResDto
	 */
	public DeleteAdminResDto deleteAdmin(DeleteAdminReqDto deleteAdminReqDto) {

		SysMgtMapper sysMgtMapper = sqlSessionMaster.getMapper(SysMgtMapper.class);

		try {
			int result = sysMgtMapper.deleteAdminList(deleteAdminReqDto.getList());

			if(result < 1 ) {
				return new DeleteAdminResDto(ApiResponseCode.CM_NOT_FOUND);
			}

		} catch (Exception e) {
			return new DeleteAdminResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		DeleteAdminResDto result = new DeleteAdminResDto(ApiResponseCode.SUCCESS);
		return result;
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 관리자 정보 상세 조회
	 * @param adminDetailReqDto
	 * @return
	 */
	public AdminDetailResDto adminDetail(AdminDetailReqDto adminDetailReqDto) {

		SysMgtMapper sysMgtMapper = sqlSessionSlave.getMapper(SysMgtMapper.class);

		AdminDetail adminDetail = new AdminDetail();
		try {
			adminDetail = sysMgtMapper.selectAdminDetail(adminDetailReqDto);

			if(adminDetail == null) {
				return new AdminDetailResDto(ApiResponseCode.CM_NOT_FOUND);
			}
		} catch (Exception e) {
			return new AdminDetailResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new AdminDetailResDto(ApiResponseCode.SUCCESS, adminDetail);
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 권한 목록 조회
	 * @param paramMap
	 * @return
	 */
	public AuthListResDto authList(Map<String, Object> paramMap) {
		List<AuthInfo> rsAuthInfoList = new ArrayList<AuthInfo>();
		AuthListRes result = new AuthListRes();

		SysMgtMapper sysMgtMapper = sqlSessionSlave.getMapper(SysMgtMapper.class);

		try {
			rsAuthInfoList = sysMgtMapper.selectAuthList();
			if(rsAuthInfoList.size() < 1) {
				return new AuthListResDto(ApiResponseCode.CM_NOT_FOUND);
			}
			result.setList(rsAuthInfoList);

		} catch (Exception e) {
			return new AuthListResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new AuthListResDto(ApiResponseCode.SUCCESS, result);
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 권한 삭제
	 * @param deleteAuthReqDto
	 * @return
	 */
	public DeleteAuthResDto deleteAuth(DeleteAuthReqDto deleteAuthReqDto) {

		SysMgtMapper sysMgtMapper = sqlSessionMaster.getMapper(SysMgtMapper.class);

		Map<String, Object> authParamMap = new HashMap<String, Object>();
		authParamMap.put("searchType", "02");
		authParamMap.put("authCd", deleteAuthReqDto.getAuthCd());
		int checkAdmin = sysMgtMapper.checkAdmin(authParamMap);
		if(checkAdmin > 0){
			return new DeleteAuthResDto(ApiResponseCode.CE_SYSMGT_AUTHCODE_EXISTS_USER);
		}

		try {
			// 1.권한메뉴 삭제
			sysMgtMapper.deleteAuthMenu(authParamMap);

			// 2.권한 삭제
			int result = sysMgtMapper.deleteAuth(authParamMap);

			if(result < 1) {
				return new DeleteAuthResDto(ApiResponseCode.CM_NOT_FOUND);
			}

		} catch (Exception e) {
			return new DeleteAuthResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		DeleteAuthResDto result = new DeleteAuthResDto(ApiResponseCode.SUCCESS);
		return result;
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 권한 상세 조회
	 * @param authDetailReqDto
	 * @return
	 */
	public AuthDetailResDto authDetail(AuthDetailReqDto authDetailReqDto) {

		SysMgtMapper sysMgtMapper = sqlSessionSlave.getMapper(SysMgtMapper.class);

		AuthDetail authDetail = new AuthDetail();
		List<AuthMenu> authMenuList = new ArrayList<AuthMenu>();

		try {
			authDetail =  sysMgtMapper.selectAuthDetail(authDetailReqDto);

			if(authDetail == null) {
				return new AuthDetailResDto(ApiResponseCode.CM_NOT_FOUND);
			}
			authMenuList = sysMgtMapper.selectAuthMemuList(authDetailReqDto);

			if(authMenuList.size() < 1) {
				return new AuthDetailResDto(ApiResponseCode.CM_NOT_FOUND);
			}

			authDetail.setList(authMenuList);


		} catch (Exception e) {
			return new AuthDetailResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new AuthDetailResDto(ApiResponseCode.SUCCESS, authDetail);

	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 권한 추가
	 * @param insertAuthReqDto
	 * @return
	 */
	public InsertAuthResDto insertAuth(InsertAuthReqDto insertAuthReqDto, String regId) {

		SysMgtMapper sysMgtMapper = sqlSessionMaster.getMapper(SysMgtMapper.class);

		AuthDetailReqDto authDetailReqDto = new AuthDetailReqDto();
		AuthDetail authDetail = new AuthDetail();
		Map<String, Object> authParamMap = new HashMap<String, Object>();
		Map<String, Object> authMenuParamMap = new HashMap<String, Object>();
		List<AuthMenu> reqAuthMenuList = new ArrayList<AuthMenu>();

		authDetailReqDto.setAuthCd(insertAuthReqDto.getAuthCd());

		// 권한코드 조회(권한코드 중복체크)
		authDetail =  sysMgtMapper.selectAuthDetail(authDetailReqDto);
		if(authDetail != null) {
			return new InsertAuthResDto(ApiResponseCode.CE_SYSMGT_AUTHCODE_INVALID);
		}

		try {
			// 권한 등록
			authParamMap.put("authCd", insertAuthReqDto.getAuthCd());
			authParamMap.put("authNm", insertAuthReqDto.getAuthNm());
			authParamMap.put("authDesc", insertAuthReqDto.getAuthDesc());
			authParamMap.put("stat", insertAuthReqDto.getStat());
			authParamMap.put("regId", regId);
			sysMgtMapper.insertAuth(authParamMap);

			// 권한메뉴 등록
			reqAuthMenuList = insertAuthReqDto.getList();

			for(int i =0; i<reqAuthMenuList.size(); i++) {
				authMenuParamMap = new HashMap<String, Object>();
				authMenuParamMap.put("authCd", authParamMap.get("authCd"));
				authMenuParamMap.put("regId", regId);
				authMenuParamMap.put("menuNo", reqAuthMenuList.get(i).getMenuNo());

				sysMgtMapper.insertAuthMenu(authMenuParamMap);
			}

		} catch (Exception e) {
			return new InsertAuthResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}
		return new InsertAuthResDto(ApiResponseCode.SUCCESS);
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 권한 수정
	 * @param updateAuthReqDto
	 * @return
	 */
	public UpdateAuthResDto updateAuth(UpdateAuthReqDto updateAuthReqDto, String regId) {
		SysMgtMapper sysMgtMapper = sqlSessionMaster.getMapper(SysMgtMapper.class);
		Map<String, Object> authParamMap = new HashMap<String, Object>();
		Map<String, Object> authMenuParamMap = new HashMap<String, Object>();
		List<AuthMenu> reqAuthMenuList = new ArrayList<AuthMenu>();

		try {
			// 권한 데이터 수정
			authParamMap.put("authCd", updateAuthReqDto.getAuthCd());
			authParamMap.put("authNm", updateAuthReqDto.getAuthNm());
			authParamMap.put("authDesc", updateAuthReqDto.getAuthDesc());
			authParamMap.put("stat", updateAuthReqDto.getStat());
			authParamMap.put("regId", regId);

			sysMgtMapper.updateAuth(authParamMap);

			// 권한메뉴 수정 (기존 권한메뉴 등록데이터 삭제 후 등록)
			// 1. 기존 권한메뉴 데이터 삭제
			sysMgtMapper.deleteAuthMenu(authParamMap);

			// 2. 권한메뉴 데이터 등록
			reqAuthMenuList = updateAuthReqDto.getList();

			for(int i =0; i<reqAuthMenuList.size(); i++) {
				authMenuParamMap = new HashMap<String, Object>();
				authMenuParamMap.put("authCd", authParamMap.get("authCd"));
				authMenuParamMap.put("regId", regId);
				authMenuParamMap.put("menuNo", reqAuthMenuList.get(i).getMenuNo());

				sysMgtMapper.insertAuthMenu(authMenuParamMap);
			}

		} catch (Exception e) {
			return new UpdateAuthResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new UpdateAuthResDto(ApiResponseCode.SUCCESS);
	}

	/**
	 * data : 2022. 10. 25.
	 * auth : Lee minha
	 * desc : 배치 리스트 조회
	 * @return
	 */
	public BatchListResDto batchList() {
		
		SysMgtMapper sysmgtmapper = sqlSessionSlave.getMapper(SysMgtMapper.class);
		
		List<BatchList> batchLists = sysmgtmapper.batchListSelect();
		
		for(int i=0; i<batchLists.size(); i++) {
		
			String batchDesc = batchLists.get(i).getBatchDesc();
			
			String[] batchArr = batchDesc.split("@");
			
			batchLists.get(i).setBatchType(batchArr[0]);
			batchLists.get(i).setBatchCycle(batchArr[1]);
			batchLists.get(i).setBatchTime(batchArr[2]);
			
		}
		
		BatchListRes batchListRes = new BatchListRes();
		batchListRes.setList(batchLists);

		return new BatchListResDto(ApiResponseCode.SUCCESS, batchListRes);
				
	}
	
	/**
	 * data : 2022. 10. 26.
	 * auth : Lee minha
	 * desc : 배치 상세내용 조회
	 * @param batchDetailReqDto
	 * @return
	 */
	public BatchDetailResDto batchDetail(BatchDetailReqDto batchDetailReqDto) {
		
		SysMgtMapper sysMgtMapper = sqlSessionSlave.getMapper(SysMgtMapper.class);
		BatchDetailRes batchDetailRes = new BatchDetailRes();
		
		String nowPage = String.valueOf(batchDetailReqDto.getPage());
		int totalCnt = sysMgtMapper.batchDetailCnt(batchDetailReqDto);

		if (totalCnt == 0) {
			batchDetailRes.setList(new ArrayList<>());
			Paging paging = new Paging();
			paging.setPage(nowPage);
			paging.setTotalCnt(String.valueOf(totalCnt));
			batchDetailRes.setPaging(paging);

			return new BatchDetailResDto(ApiResponseCode.CM_NOT_FOUND, batchDetailRes);
		}

		int page = batchDetailReqDto.getPage();
		int pagePerRows = batchDetailReqDto.getPagePerRows();
		page = (page - 1) * pagePerRows;
		batchDetailReqDto.setPage(page);
		
		List<BatchDetail> batchDetail = sysMgtMapper.batchDetailSelect(batchDetailReqDto);
		batchDetailRes.setList(batchDetail);
		Paging paging = new Paging();
		paging.setPage(nowPage);
		paging.setTotalCnt(String.valueOf(totalCnt));
		batchDetailRes.setPaging(paging);
		
		
		return new BatchDetailResDto(ApiResponseCode.SUCCESS, batchDetailRes);
	}
	
	/**
	 * data : 2022. 11. 23.
	 * auth : Lee minha
	 * desc : 알림 이력 조회
	 * @param noticeListReqDto
	 * @return
	 */
	public NotiListResDto notiList(NotiListReqDto notiListReqDto) {
		
		log.info("Start notiList Service");
		
		
		SysMgtMapper sysmgtmapper = sqlSessionSlave.getMapper(SysMgtMapper.class);
		NotiListRes notiListRes = new NotiListRes();
		
		String nowPage = String.valueOf(notiListReqDto.getPage());
		int totalCnt = sysmgtmapper.notiListSelectCnt(notiListReqDto);

		if (totalCnt == 0) {
			notiListRes.setList(new ArrayList<>());
			Paging paging = new Paging();
			paging.setPage(nowPage);
			paging.setTotalCnt(String.valueOf(totalCnt));
			notiListRes.setPaging(paging);

			return new NotiListResDto(ApiResponseCode.CM_NOT_FOUND, notiListRes);
		}

		int page = notiListReqDto.getPage();
		int pagePerRows = notiListReqDto.getPagePerRows();
		page = (page - 1) * pagePerRows;
		notiListReqDto.setPage(page);
		
		List<NotiList> notiList = sysmgtmapper.notiListSelect(notiListReqDto);
		notiListRes.setList(notiList);
		Paging paging = new Paging();
		paging.setPage(nowPage);
		paging.setTotalCnt(String.valueOf(totalCnt));
		notiListRes.setPaging(paging);
		
		log.info("End notiList Service");
		
		return new NotiListResDto(ApiResponseCode.SUCCESS, notiListRes);
	}
	
	
	public SetWorkStateResDto setWorkState(SetWorkStateReqDto setWorkParam) {
	
		File file = new File("C:\\efs\\home\\workState\\workStatefile.txt");
		File fileList = new File("C:\\efs\\admin\\workState\\workStatefile.txt");
		
		String[] workParamArr = setWorkParam.getStartDate().split("-");
		
		String year = "";
		String month = "";
		String day = "";
		
		//1.파일 값 셋팅
		String setWorkState = "";
		
		setWorkState += setWorkParam.getState() + "@";
		setWorkState += workParamArr[0] + "@";
		setWorkState += workParamArr[1] + "@";
		setWorkState += workParamArr[2] + "@";
		setWorkState += setWorkParam.getStartTimeT() + "@";
		setWorkState += setWorkParam.getStartTimeM() + "@";
		setWorkState += setWorkParam.getEndTimeT() + "@";
		setWorkState += setWorkParam.getEndTimeM();
		
		
		try {
			//1. workState 파일이 없다면? 만들어라
			if(!file.exists()) {
				file.createNewFile();
			}else if(!fileList.exists()) {
				fileList.createNewFile();
			}
			
			//2. Buffer를 사용해서 File에 write할 수 있는 BufferedWriter 생성
			FileWriter fw = new FileWriter(file);
			BufferedWriter writer = new BufferedWriter(fw);
			
			logger.debug("setWorkString={}",setWorkState);
			
			//3. 파일에 쓰기
			writer.write(setWorkState);
			
			//4. Buffer
			writer.close();
			
			//5. admin파일에 저장
			
			String workStateData = "";
			
			Resource filethree = fileService.loadAsResource(dirWorkState);
            BufferedReader reader = new BufferedReader(new FileReader(filethree.getFile()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            
            FileWriter fwList = new FileWriter(fileList);
			BufferedWriter writerList = new BufferedWriter(fwList);
			
            workStateData = sb.toString();
        	String[] Data = workStateData.split(",");
        	
        	List<String> newList = new ArrayList<>();
        	
        	if((Data[0].equals(""))==false) {
        		for (String data : Data) {
        			newList.add(data);
        		}	
        	}
        	newList.add(setWorkState);
        	
        	for (String data : newList) {
        		writerList.write(data+",\r\n");
            }
        	
        	writerList.close();
			
		} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		}
		logger.debug("setWorkParam={}",setWorkParam);
		
		
		
		return new SetWorkStateResDto(ApiResponseCode.SUCCESS);
	}
	
	 /**
	  * data: 2023. 05.09.
	  * auth: won
	  * desc: 서비스 점검 이력 조회
	  * @return
	  */
	 public SvcCheckListResDto svcCheckLists(@Valid SvcCheckListReqDto svcCheckListReqDto) {
		 
		 String workStateData = "";
	    	String [] workStateDataArr = new String[7];
	    	log.info("getWorkStateCheck START ==========================================");
	    	
	    	SvcCheckListRes svcCheckListRes = new SvcCheckListRes();
	    	List<SvcCheckList> CheckList = new ArrayList<SvcCheckList>(); 
	    	SvcCheckList svcCheckList = new SvcCheckList();
	    	
	    	String nowPage = String.valueOf(svcCheckListReqDto.getPage());
    		int totalCnt = 0;
    		File fileList = new File("C:\\efs\\admin\\workState\\workStatefile.txt");
    		
	    	try {
	    		//파일 읽기
	    		Resource file = fileService.loadAsResource(dirWorkState);
	            BufferedReader reader = new BufferedReader(new FileReader(file.getFile()));
	            StringBuilder sb = new StringBuilder();
	            String line;
	            while ((line = reader.readLine()) != null) {
	                sb.append(line);
	            }
	            reader.close();
	            
	            if(null != sb.toString() && !"".equals(sb.toString())) {
	            	workStateData = sb.toString();
	            	String[] Data = workStateData.split(",");
	            	
	            	//항목 객체에 값 셋팅
	            	for (int i = 0; i < Data.length; i++) {
	            		svcCheckList = new SvcCheckList();
	            		workStateDataArr = Data[i].split("@");
	            		svcCheckList.setWorkState(workStateDataArr[0]);
	            		svcCheckList.setYear(workStateDataArr[1]);
		            	svcCheckList.setMonth(workStateDataArr[2]);
		            	svcCheckList.setDay(workStateDataArr[3]);
		            	svcCheckList.setStrtHour(workStateDataArr[4]);
		            	svcCheckList.setStrtMin(workStateDataArr[5]);
		            	svcCheckList.setEndHour(workStateDataArr[6]);
		            	svcCheckList.setEndMin(workStateDataArr[7]);
		            	
		            	String Ymd = svcCheckList.getYear()+"-"+ svcCheckList.getMonth()+"-"+ svcCheckList.getDay();
		            	svcCheckList.setYmd(Ymd);
		            	String StrHd = svcCheckList.getStrtHour()+" : "+ svcCheckList.getStrtMin();
		            	svcCheckList.setStrHd(StrHd);
		            	String EndHd = svcCheckList.getEndHour()+" : "+ svcCheckList.getEndMin();
		            	svcCheckList.setEndHd(EndHd);
		            	// 리스트에 항목 추가
		            	CheckList.add(svcCheckList);
	            	}

	            	svcCheckListRes.setList(CheckList);
	            	totalCnt = CheckList.size();
	            	int page = svcCheckListReqDto.getPage();
	        		int pagePerRows = svcCheckListReqDto.getPagePerRows();
	        		page = (page - 1) * pagePerRows;
	        		svcCheckListReqDto.setPage(page); 
	            }
			} catch (Exception e) {
				if(!fileList.exists()) {
					log.debug("파일이 존재하지 않습니다.");
				}else {
				// 파일 읽기 실패 시 "USE"로 설정하고 결과 반환
				log.error("WORK STATE READ FAIL : {}",e.getMessage(), e);
				svcCheckList.setWorkState("USE");
				
				String[] Data = workStateData.split(",");
				totalCnt = CheckList.size();
            	int page = svcCheckListReqDto.getPage();
        		int pagePerRows = svcCheckListReqDto.getPagePerRows();
        		page = (page - 1) * pagePerRows;
        		svcCheckListReqDto.setPage(page); 
				return new SvcCheckListResDto(ApiResponseCode.SUCCESS);
				}
			}
	    	
	    	if (totalCnt == 0) {
        		svcCheckListRes.setList(new ArrayList<>());
    			Paging paging = new Paging();
    			paging.setPage(nowPage);
    			paging.setTotalCnt(String.valueOf(totalCnt));
    			svcCheckListRes.setPaging(paging);

    			return new SvcCheckListResDto(ApiResponseCode.CM_NOT_FOUND, svcCheckListRes);
    		}
        	
        	
        	svcCheckListRes.setList(CheckList);
    		Paging paging = new Paging();
    		paging.setPage(nowPage);
    		paging.setTotalCnt(String.valueOf(totalCnt));
    		svcCheckListRes.setPaging(paging);
		 
		 return new SvcCheckListResDto(ApiResponseCode.SUCCESS,svcCheckListRes);
	 }
}
