package com.eactive.eai.rms.bat.manage.rule.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.rms.bat.manage.comm.property.BatPropertyDao;
import com.eactive.eai.rms.common.acl.user.BizDao;
import com.eactive.eai.rms.common.base.BatBaseAnnotationController;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.google.gson.Gson;

@Controller
public class BatAdapterController extends BatBaseAnnotationController {

	@Autowired
	@Qualifier("batAdapterService")
	private BatAdapterService service;

	@Autowired
	@Qualifier("bizDao")
	private BizDao bizDao;

	@Autowired
	private ComboService comboService;

	@Autowired
	@Qualifier("batPropertyDao")
	private BatPropertyDao bzSysDao;
	
	@Autowired
	private BatAdapterConnectionReportService connReportService;

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.view")
	public String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false) String cmd)
			throws Exception {
		if (cmd == null || "LIST".equals(cmd.toUpperCase())) {
			cmd = "";
		} else {
			cmd = CamelCaseUtil.converCamelCase(cmd);
		}
		String path = request.getServletPath();
		return path.split("[.]")[0] + cmd;
	}

	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST")
	public ModelAndView selectList(HttpServletRequest request, JsonPageVo pageVo,
			@RequestParam HashMap<String, Object> paramap) throws Exception {

		String userid = SessionManager.getUserId(request);
		paramap.put("loginEmpno", userid);

		HashMap<String, Object> map = service.selectList(pageVo.getStartNum(), pageVo.getEndNum(), paramap);

		pageVo.setTotalCount((Integer) map.get("totalCount"));

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("total", pageVo.getTotal()); // 전체 페이지수
		resultMap.put("page", pageVo.getPage()); // 현재 페이지수
		resultMap.put("records", pageVo.getTotalCount());// 전체 레코드건수
		resultMap.put("rows", map.get("list"));

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String userId = SessionManager.getUserId(request);
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		paramMap.put("prptyGroupId", "BzSystem");

		List<Map<String, Object>> listBiz = bzSysDao.propertyDetail(paramMap);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("bizList", listBiz);

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_SUBFILE_INIT_COMBO")
	public ModelAndView subFileInitCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {

		List<ComboVo> listChkFileExt = comboService.getFromCode("CHK_FILE_EXT");
		List<ComboVo> listFtpType = comboService.getFromCode("FTP_TYPE");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("listChkFileExt", listChkFileExt);
		resultMap.put("listFtpType", listFtpType);

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_SUBDB_INIT_COMBO")
	public ModelAndView subDbInitCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {

		List<ComboVo> listDbmsType = comboService.getFromCode("DBMS_TYPE");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("listDbmsType", listDbmsType);

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=DETAIL")
	public ModelAndView selectDetail(HttpServletRequest request, HttpServletResponse response, String envRdvs)
			throws Exception {
		HashMap<String, Object> map = service.selectDetail(envRdvs);
		ModelAndView modelAndView = new ModelAndView("jsonView", map);
		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=INSERT")
	public ModelAndView insert(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String gridData) throws Exception {

		String userid = SessionManager.getUserId(request);
		map.put("userid", userid);
		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
		service.insert(map, list);

		ModelAndView modelAndView = new ModelAndView("jsonView", map);

		return modelAndView;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=UPDATE")
	public String update(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String gridData) throws Exception {

		String userid = SessionManager.getUserId(request);
		map.put("userid", userid);
		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);

		service.update(map, list);

		return null;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=DELETE")
	public String delete(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		service.delete(map);

		return null;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_DELETE")
	public String deleteList(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		String[] adptrCdList = map.get("adptrCdList").toString().split(",");

		for (int i = 0; i < adptrCdList.length; i++) {
			String adptrCd = adptrCdList[i];
			HashMap<String, Object> adptrCdMap = new HashMap<String, Object>();
			adptrCdMap.put("adptrCd", adptrCd);
			service.delete(adptrCdMap);
		}

		return null;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=DETAILDB")
	public ModelAndView selectDetailDB(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> paraMap) throws Exception {

		HashMap<String, Object> map = service.selectDetailDB(paraMap);

		ModelAndView modelAndView = new ModelAndView("jsonView", map);

		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=INSERTDB")
	public ModelAndView insertDB(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		service.insertDB(map);

		return null;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=UPDATEDB")
	public ModelAndView updateDB(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String gridData) throws Exception {

		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);

		service.updateDB(map, list);

		return null;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=UPDATEDBSEQ")
	public ModelAndView updateDBAdptrSeq(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		service.updateDBAdptrSeq(map);

		return null;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=DELETEDB")
	public ModelAndView deleteDB(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		service.deleteDB(map);

		return null;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=CLONE")
	public ModelAndView clone(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		map.replace("adptrCdSeq", Integer.valueOf(map.get("adptrCdSeq").toString()) + 1);
		map.replace("intfId", "");

		service.insertDB(map);

		return null;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=UPDATE_ALL_DB")
	public ModelAndView updateAllDB(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		service.updateAllDB(map);

		return null;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=DETAILFILE")
	public ModelAndView selectDetailFile(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> paraMap) throws Exception {

		HashMap<String, Object> map = service.selectDetailFile(paraMap);
		ModelAndView modelAndView = new ModelAndView("jsonView", map);

		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=INSERTFILE")
	public ModelAndView insertFile(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		map.put("rmtSevrFTPUID", " "); // FTP ID 공백처리
		map.put("rmtSevrFTPUserPwdName", " "); // FTP PW 공백처리

		service.insertFile(map);

		return null;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=UPDATEFILE")
	public ModelAndView updateFile(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String gridData) throws Exception {

		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);

		service.updateFile(map, list);

		return null;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=UPDATEFILESEQ")
	public ModelAndView updateFileAdptrSeq(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		service.updateFileAdptrSeq(map);

		return null;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=DELETEFILE")
	public ModelAndView deleteFile(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		service.deleteFile(map);

		return null;

	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=UPDATE_ALL_FILE")
	public ModelAndView updateAllFile(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		service.updateAllFile(map);

		return null;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/bat/admin/adapter/adapterMan.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response, String gridData,
			String header, String headerTitle, String fileName, String merge) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		Gson gson = new Gson();
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
		String[] headers = gson.fromJson(header, String[].class);
		String[] headerTitles = gson.fromJson(headerTitle, String[].class);

		HashMap<String, Object>[] lmerge = null;
		if (merge != null) {
			lmerge = gson.fromJson(merge, HashMap[].class);
		}

		resultMap.put("headers", headers);
		resultMap.put("headerTitles", headerTitles);
		resultMap.put("datas", list);
		resultMap.put("fileName", fileName);
		resultMap.put("merge", lmerge);
		ModelAndView modelAndView = new ModelAndView("excelView", resultMap);

		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_DB_CONNECT")
	public ModelAndView connectDB(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		HashMap<String, Object> result = service.connectionDB(map);

		ModelAndView modelAndView = new ModelAndView("jsonView", result);

		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_FTP_CONNECT")
	public ModelAndView connectFTP(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		HashMap<String, Object> result = service.connectionFTP(map);

		ModelAndView modelAndView = new ModelAndView("jsonView", result);

		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_DOWNLOAD_SQL")
	public ModelAndView downloadSql(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		ModelAndView modelAndView = new ModelAndView("jsonView", service.mkInserSqlForAdptr(map));

		return modelAndView;
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.view", params = "cmd=LIST_FILE_DOWNLOAD")
	public String fileDownload(HttpServletRequest request) throws Exception {

		return "/bat/admin/common/filedownload";
	}

	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=GEN_ADAPTER_CODE")
	public ModelAndView generateAdapterCode(String paramAdapterCode) throws Exception {

		String adapterCode = service.generateAdapterCode(paramAdapterCode);

		Map<String, Object> mapToJson = new HashMap<>();
		mapToJson.put("adapterCode", adapterCode);

		ModelAndView modelAndView = new ModelAndView("jsonView", mapToJson);
		return modelAndView;
	}
	
	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_BAT_CONN_ALL")
	public ResponseEntity<GridResponse<AdapterConnectionInfo>> batConnectionReportAll() throws Exception {
		
		List<AdapterConnectionInfo> connInfoList = connReportService.getAdapterConnectionReportAll();
		
		GridResponse<AdapterConnectionInfo> gridResponse = new GridResponse<>();
		gridResponse.setRows(connInfoList);
		
		return ResponseEntity.ok()
				.body(gridResponse);
	}
	
	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_BAT_CONN")
	public ResponseEntity<GridResponse<AdapterConnectionInfo>> batConnectionReport(String adapterCode) throws Exception {
		
		List<AdapterConnectionInfo> connInfoList = connReportService.getAdapterConnectionReport(adapterCode);
		
		GridResponse<AdapterConnectionInfo> gridResponse = new GridResponse<>();
		gridResponse.setRows(connInfoList);
		
		return ResponseEntity.ok()
				.body(gridResponse);
	}
	
	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_BAT_CONN_EXCEL")
	public ResponseEntity<Resource> batConnectionReportExcel() throws Exception {
	
		List<AdapterConnectionInfo> connInfoList = connReportService.getAdapterConnectionReportAll();
		ByteArrayResource xlsxWorkBookResource = connReportService.generateExcelFromConnectionInfoList(connInfoList);
		
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"batConntionInfo.xlsx\"")
				.contentLength(xlsxWorkBookResource.contentLength())
				.body(xlsxWorkBookResource);
		
	}
	
	@RequestMapping(value = "/bat/admin/adapter/adapterMan.json", params = "cmd=LIST_REMOTE_FILES")
	public ResponseEntity<String> batRemoteFilesList(String modalAdapterCode, String modalDirectory) throws Exception {
		
		String response = connReportService.getRemoteFilesList(modalAdapterCode, modalDirectory);
		
		return ResponseEntity.ok()
				.body(response);
	}

}