package com.mca.cmmn.web;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.mca.cmmn.service.LogService;
import com.mca.cmmn.vo.BaseSearchVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mca.cmmn.service.AreaCodeService;
import com.mca.cmmn.service.LayersService;
import com.mca.cmmn.vo.LayersVO;
import com.mca.map.service.FieldDataService;
import com.mca.map.service.UseHistoryService;
import com.mca.map.service.UseRequestService;
import com.mca.map.vo.FieldDataSearchVO;
import com.mca.map.vo.FieldDataVO;
import com.mca.map.vo.UseHistorySearchVO;
import com.mca.map.vo.UseRequestSearchVO;
import com.mca.map.vo.UseRequestVO;
import com.mca.sec.UserUtil;
import com.mca.sec.vo.LoginUserVO;
import com.mca.user.service.UserService;
import com.mca.user.vo.UserSearchVO;
import com.mca.user.vo.UserVO;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

@Controller
@RequestMapping("/admin")
public class AdminController {
	
	/**
	 * properties값을 가져오는 인터페이스.
	 **/
	@Resource(name="propertiesService")
	private EgovPropertyService propertiesService;

	@Resource(name="useRequestService")
	private UseRequestService useRequestService;
	
	@Resource(name="useHistoryService")
	private UseHistoryService useHistoryService;
	
	@Resource(name="areaCodeService")
	private AreaCodeService areaCodeService;
	
	@Resource(name="layersService")
	private LayersService layersService;
	
	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="fieldDataService")
	private FieldDataService fieldDataService;

  @Resource(name = "logService")
  private LogService logService;

  /**
   * 대시보드 페이지 이동
   *
   * @param useRequestSearchVO
   * @param model 모델 객체
   * @return
   * @throws
   */
  @RequestMapping("/dashBoard")
  public String dashBoard(@ModelAttribute("UseRequestSearchVO") UseRequestSearchVO useRequestSearchVO, Model model) throws Exception {
    try {
      // 지도사용 요청 승인대기 수
      int statusCnt = useRequestService.selectUseRequeststatusCnt();
      model.addAttribute("statusCnt", statusCnt);

      // 회원가입 승인대기 수
      int standByCount = userService.selectUserStandByCount();
      model.addAttribute("standByCount", standByCount);

      // 확인요청 데이터
		FieldDataSearchVO fieldDataSearchVO = new FieldDataSearchVO();
		fieldDataSearchVO.setStatus0(1);
		fieldDataSearchVO.setStatus1(1);
		fieldDataSearchVO.setStatus2(1);
		fieldDataSearchVO.setStatus3(1);
		int standFieldData = fieldDataService.selectFieldDataCnt(fieldDataSearchVO);
		model.addAttribute("standFieldData", standFieldData);

      // 일, 월 방문자 수
      BaseSearchVO searchVO = new BaseSearchVO();
      LocalDate searchStartDate = LocalDate.now();
      searchVO.setSearchStartDate(searchStartDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
      searchVO.setSearchEndDate(searchStartDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
      model.addAttribute("dayLoginCount", logService.selectLoginCnt(searchVO));
      searchVO.setSearchStartDate(searchStartDate.minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
      model.addAttribute("monthLoginCount", logService.selectLoginCnt(searchVO));

      return "admin/dashBoard";

    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
      return "error/EgovServerError";
    }
  }

	/**
	 * 지도 사용요청 목록을 반환한다.
	 * 
	 * @param useRequestSearchVO 지도사용요청 검색, 페이지 정보 객체
	 * @param model 모델 객체
	 * @return 지도사용요청 목록 화면
	 * @throws 
	 */
	@RequestMapping("/request")
	public String reqList(@ModelAttribute("UseRequestSearchVO") UseRequestSearchVO useRequestSearchVO, Model model) throws Exception {
		try {
			useRequestSearchVO.setPageUnit(propertiesService.getInt("pageUnit"));
			useRequestSearchVO.setPageSize(propertiesService.getInt("pageSize"));
			
			PaginationInfo paginationInfo = new PaginationInfo();
			paginationInfo.setCurrentPageNo(useRequestSearchVO.getPageIndex());
			paginationInfo.setRecordCountPerPage(useRequestSearchVO.getPageUnit());
			paginationInfo.setPageSize(useRequestSearchVO.getPageSize());
			
			useRequestSearchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
			useRequestSearchVO.setLastIndex(paginationInfo.getLastRecordIndex());
			useRequestSearchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
			
			List<?> userList = useRequestService.selectUseRequestList(useRequestSearchVO);
			int count = useRequestService.selectUseRequestCnt(useRequestSearchVO);
			int statusCnt = useRequestService.selectUseRequeststatusCnt();
			
			paginationInfo.setTotalRecordCount(count);
			
			model.addAttribute("paginationInfo", paginationInfo);
			model.addAttribute("useRequestList", userList);
			model.addAttribute("useRequestSearchVO", useRequestSearchVO);
			model.addAttribute("count", count);
			model.addAttribute("statusCnt", statusCnt);
			
			return "admin/request";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 지도 사용요청 상세화면을 반환한다.
	 * 
	 * @param idx 지도사용요청 Primary Key
	 * @param model 모델 객체
	 * @return 지도사용요청 상세 화면
	 * @throws Exception 기본 예외 처리
	 */
	@RequestMapping("/request/{idx}")
	public String reqDetail(@PathVariable int idx, Model model) throws Exception{
		try {
			LoginUserVO loginUserVO = UserUtil.getMemberInfo();
			
			UseRequestVO useRequestVO = useRequestService.selectUseRequest(idx);
			useRequestVO = useRequestService.selectUseRequest(idx);
			UserVO userVO = userService.selectUserInfo(useRequestVO.getUserid());
			
			String layers[] = useRequestVO.getLayers().split(",");
			String places[] = useRequestVO.getPlaces().split(",");
			
			ArrayList<String> selectArea = new ArrayList<String>();
			for(int i=0;i<places.length;i++) {
				selectArea.add(areaCodeService.selectAreaName(places[i]));
			}
			
			List <LayersVO> layersVO = layersService.selectLayers();
			model.addAttribute("loginUserVO", loginUserVO);
			model.addAttribute("userVO", userVO);
			model.addAttribute("useRequestVO", useRequestVO);
			model.addAttribute("selectArea", selectArea);
			model.addAttribute("layers", layers);
			model.addAttribute("layersVO", layersVO);
			return "admin/requestView";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 지도사용이력 목록을 반환한다.
	 * 
	 * @param useHistorySearchVO 지도사용이력 검색, 페이지 정보 객체
	 * @param model 모델 객체
	 * @return 지도사용요청 목록 화면
	 * @throws 
	 */
	@RequestMapping("/history")
	public String history(@ModelAttribute("UseHistorySearchVO") UseHistorySearchVO useHistorySearchVO, Model model) throws Exception {
		try {
			useHistorySearchVO.setPageUnit(propertiesService.getInt("pageUnit"));
			useHistorySearchVO.setPageSize(propertiesService.getInt("pageSize"));
			
			PaginationInfo paginationInfo = new PaginationInfo();
			paginationInfo.setCurrentPageNo(useHistorySearchVO.getPageIndex());
			paginationInfo.setRecordCountPerPage(useHistorySearchVO.getPageUnit());
			paginationInfo.setPageSize(useHistorySearchVO.getPageSize());
			
			useHistorySearchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
			useHistorySearchVO.setLastIndex(paginationInfo.getLastRecordIndex());
			useHistorySearchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
			
			List<?> useHistoryList = useHistoryService.selectUseHistoryList(useHistorySearchVO);
			int count = useHistoryService.selectUseHistoryCnt(useHistorySearchVO);
			
			paginationInfo.setTotalRecordCount(count);
			
			model.addAttribute("paginationInfo", paginationInfo);
			model.addAttribute("useHistoryList", useHistoryList);
			model.addAttribute("useHistorySearchVO", useHistorySearchVO);
			model.addAttribute("count", count);
			
			return "admin/history";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 지도사용요청 승인/거절 처리한다.
	 * 
	 * @param useRequestVO 지도사용요청 VO
	 * @param model 모델 객체
	 * @return 지도사용요청 목록 화면
	 * @throws 
	 */
	@RequestMapping("/updateReqConfirm")
	public String updateReqConfirm(@ModelAttribute("useRequestVO") UseRequestVO useRequestVO, Model model) throws Exception {
		try {
			useRequestService.updateReqConfirm(useRequestVO);
			String resultMsg;
			if(useRequestVO.getStatus().equals("0")) {
				resultMsg = "지도사용요청 승인 처리가 되었습니다.";
			}else {
				resultMsg = "지도사용요청 거절 처리가 되었습니다.";
			}
			
			model.addAttribute("url", "/admin/request");
			model.addAttribute("resultMsg", resultMsg);
			return "/redirect";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 사용자관리 목록을 반환한다.
	 * 
	 * @param userSearchVO 사용자정보 검색 VO
	 * @param model 모델 객체
	 * @return 사용자관리 목록 화면
	 * @throws 
	 */
	@RequestMapping("/userInfo")
	public String userInfo(@ModelAttribute("UserSearchVO") UserSearchVO userSearchVO, Model model) throws Exception {
		try {
			userSearchVO.setPageUnit(propertiesService.getInt("pageUnit"));
			userSearchVO.setPageSize(propertiesService.getInt("pageSize"));
			
			PaginationInfo paginationInfo = new PaginationInfo();
			paginationInfo.setCurrentPageNo(userSearchVO.getPageIndex());
			paginationInfo.setRecordCountPerPage(userSearchVO.getPageUnit());
			paginationInfo.setPageSize(userSearchVO.getPageSize());
			
			userSearchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
			userSearchVO.setLastIndex(paginationInfo.getLastRecordIndex());
			userSearchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
			
			List<?> userList = userService.selectUserList(userSearchVO);
			int count = userService.selectUserCount(userSearchVO);
			int standByCount = userService.selectUserStandByCount();
			
			paginationInfo.setTotalRecordCount(count);
			
			model.addAttribute("paginationInfo", paginationInfo);
			model.addAttribute("userList", userList);
			model.addAttribute("userSearchVO", userSearchVO);
			model.addAttribute("count", count);
			model.addAttribute("standByCount", standByCount);
			
			return "admin/userInfo";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 사용자관리 상세화면을 반환한다.
	 * 
	 * @param userid 사용자정보 ID
	 * @param model 모델 객체
	 * @return 사용자관리 상세 화면
	 * @throws 
	 */
	@RequestMapping("/userInfo/{userid}")
	public String userInfoView(@PathVariable String userid, Model model) throws Exception {
		try {
			UserVO userVO = userService.selectUserInfo(userid);
			model.addAttribute("userVO", userVO);
			
			return "admin/userInfoView";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 사용자정보를 수정한다.
	 * 
	 * @param req Request 객체
	 * @param model 모델 객체
	 * @param userVO 사용자정보 VO
	 * @return 사용자관리 목록 화면
	 * @throws 
	 */
	@RequestMapping("/userUpdate")
	public String userUpdate(HttpServletRequest req, Model model, UserVO userVO) throws Exception {
		try {
			userService.updateUser(userVO);
			model.addAttribute("url", "/admin/userInfo");
			model.addAttribute("resultMsg", "수정되었습니다.");
			return "/redirect";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 사용자를 승인/거절 처리한다.
	 * 
	 * @param userVO 사용자정보 VO
	 * @param model 모델 객체
	 * @return 사용자관리 목록 화면
	 * @throws 
	 */
	@RequestMapping("/userSign")
	public String userSign(@ModelAttribute("userVO") UserVO userVO, Model model) throws Exception {
		try {
			String resultMsg = null;
			if(userVO.getAuth() == 2) {
				userService.updateUserSign(userVO.getUserid());
				resultMsg = "승인 처리 되었습니다.";
			}else {
				userService.updateUserDelete(userVO.getUserid());
				resultMsg = "삭제 처리 되었습니다.";
			}
			
			model.addAttribute("url", "/admin/userInfo?auth=99");
			model.addAttribute("resultMsg", resultMsg);
			return "/redirect";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 현장수집데이터 목록을 반환한다.
	 * 
	 * @param fieldDataSearchVO 현장수집데이터 검색 VO
	 * @param model 모델 객체
	 * @return 현장수집데이터 목록 화면
	 * @throws 
	 */
	@RequestMapping("/fieldData")
	public String fieldData(@ModelAttribute("FieldDataSearchVO") FieldDataSearchVO fieldDataSearchVO, Model model) throws Exception {
		try {
			fieldDataSearchVO.setPageUnit(propertiesService.getInt("pageUnit"));
			fieldDataSearchVO.setPageSize(propertiesService.getInt("pageSize"));
			
			PaginationInfo paginationInfo = new PaginationInfo();
			paginationInfo.setCurrentPageNo(fieldDataSearchVO.getPageIndex());
			paginationInfo.setRecordCountPerPage(fieldDataSearchVO.getPageUnit());
			paginationInfo.setPageSize(fieldDataSearchVO.getPageSize());
			
			fieldDataSearchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
			fieldDataSearchVO.setLastIndex(paginationInfo.getLastRecordIndex());
			fieldDataSearchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
			
			List<?> fieldDataList = fieldDataService.selectFieldDataList(fieldDataSearchVO);
			int count = fieldDataService.selectFieldDataCnt(fieldDataSearchVO);
			
			
			paginationInfo.setTotalRecordCount(count);
			
			model.addAttribute("fieldDataList", fieldDataList);
			model.addAttribute("paginationInfo", paginationInfo);
			model.addAttribute("fieldDataSearchVO", fieldDataSearchVO);
			model.addAttribute("count", count);
			
			return "admin/fieldData";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
	
	/**
	 * 현장수집데이터 상세화면을 반환한다.
	 * 
	 * @param id 현장수집데이터 id
	 * @param model 모델 객체
	 * @return 현장수집데이터 상세 화면
	 * @throws
	 */
	@RequestMapping("/fieldData/{id}")
	public String fieldData(@PathVariable String id, Model model) throws Exception {
		try {
			FieldDataVO fieldDataVO = fieldDataService.selectFieldData(id);
			UserVO userVO = userService.selectUserInfo(fieldDataVO.getUserid());
			
			model.addAttribute("fieldDataVO", fieldDataVO);
			model.addAttribute("userVO", userVO);
			return "admin/fieldView";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "error/EgovServerError";
		}
	}
}
