package com.eactive.eai.rms.bap.manage.message.messageMeta;

import java.util.ArrayList;
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.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.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.BapBaseAnnotationController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.google.gson.Gson;

@Controller
public class BapMessageMetaController extends BapBaseAnnotationController  {

	@Autowired
	@Qualifier("bapMessageMetaService")
	private BapMessageMetaService service;
	
	@RequestMapping(value= "/bap/admin/message/messageMetaMan.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= "/bap/admin/message/messageMetaMan.json", params = "cmd=LIST")
	public ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo , @RequestParam HashMap<String, Object> paramMap) throws Exception {
		
		HashMap<String, Object> map = service.selectList( pageVo.getStartNum(), pageVo.getEndNum(), paramMap);
		
		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= "/bap/admin/message/messageMetaMan.json",params = "cmd=DETAIL")
	public ModelAndView selectDetail(HttpServletRequest request,
			HttpServletResponse response, String msgMetaDstcd) throws Exception {

		HashMap<String, Object> map = service.selectDetail(msgMetaDstcd);
		
		ModelAndView modelAndView = new ModelAndView("jsonView", map);	
		
		return modelAndView;
	}
	@RequestMapping(value= "/bap/admin/message/messageMetaMan.json",params = "cmd=INSERT")
	public String insert(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map,String gridData ) throws Exception {

		
		String userid = com.eactive.eai.rms.common.login.SessionManager.getUserId(request);
		map.put("userid", userid );
    	
		Gson gson = new Gson();
    	@SuppressWarnings("unchecked")
		HashMap<String, Object>[] list = (HashMap<String, Object>[])gson.fromJson(gridData, HashMap[].class);
    	service.insert(map,list);
    	
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.telegram.UpdateTelegramCommand",map.get("msgMetaDstcd"));
		agentUtilService.broadcast(command);

    	return null;
		
	}	
	@RequestMapping(value= "/bap/admin/message/messageMetaMan.json",params = "cmd=UPDATE")
	public String update(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String, Object> map, String gridData ) throws Exception {
		
		String userid = com.eactive.eai.rms.common.login.SessionManager.getUserId(request);
		map.put("userid", userid );

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

    	service.update(map,list);  

		CommonCommand command = new CommonCommand("com.eactive.eai.agent.telegram.UpdateTelegramCommand",map.get("msgMetaDstcd"));
		agentUtilService.broadcast(command);

		return null;
		
	}
	@RequestMapping(value= "/bap/admin/message/messageMetaMan.json",params = "cmd=DELETE")
	public String delete(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String, Object> map ) throws Exception {
		
		service.delete(map);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.telegram.RemoveTelegramCommand",map.get("msgMetaDstcd"));
		agentUtilService.broadcast(command);

		return null;
	
	}
	@RequestMapping(value= "/bap/admin/message/messageMetaMan.json",params = "cmd=LIST_DELETE")
	public String deleteList(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String, Object> paramMap ) throws Exception {
		for (String msgMetaDstcd : paramMap.get("msgMetaDstcdList").toString().split(",")) {
			HashMap<String, Object> paramDetail = new HashMap<String,Object>();
			paramDetail.put("msgMetaDstcd", msgMetaDstcd);			
			service.delete(paramDetail);
		}
		return null;
		
	}	
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "/bap/admin/message/messageMetaMan.json",params = "cmd=CLONE")
	public ModelAndView clone(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> map) throws Exception {
		
		String msgMetaDstcd = map.get("msgMetaDstcd").toString();
		HashMap<String, Object> detailMap 	= service.selectDetail(msgMetaDstcd);
		HashMap<String, Object> detail 		= (HashMap<String, Object>)detailMap.get("detail");
		List<Map<String, Object>> list		= (List<Map<String, Object>>)detailMap.get("list");
		
		// detail insert 데이터키 치환 (insert_bm03)
		String newMsgMetaDstcd = map.get("newMsgMetaDstcd").toString();
		detail.put("msgMetaDstcd", newMsgMetaDstcd);
		detail.put("msgDesc" 	 , map.get("newMsgDesc") != null ? map.get("newMsgDesc") : detail.get("MSGDESC"));
		detail.put("thisMsgUseYn", detail.get("THISMSGUSEYN"));
		
		String searchMsgMetaDstcd = map.get("searchMsgMetaDstcd").toString();
		String cloneMsgMetaDstcd = map.get("cloneMsgMetaDstcd").toString();
		
		// gridList insert 데이터키 치환 (insert_bm02)
		HashMap<String, Object>[] gridList = list.toArray(new HashMap[list.size()]);
		for (int i=0; i<list.size(); i++) {
			Map<String, Object> listMap = (Map<String, Object>)list.get(i);
			gridList[i].put("msgMetaDstcd"			, ((String)listMap.get("MSGMETADSTCD")).replace(searchMsgMetaDstcd,cloneMsgMetaDstcd));
			gridList[i].put("thisMsgUseYn"			, listMap.get("THISMSGCLMNUSEYN"));
			// 메시지항목명을 치환하면 메시지항목 테이블(BM01)에 항목이 없으므로 메타 Item 리스트에 보이지 않음 --> 치환 안함으로 변경 
//			gridList[i].replace("MSGITEMDSTICNAME"	, ((String)listMap.get("MSGITEMDSTICNAME")).replace(searchMsgMetaDstcd,cloneMsgMetaDstcd));
			gridList[i].replace("MSGITEMDSTICNAME"	, listMap.get("MSGITEMDSTICNAME"));
			gridList[i].replace("MSGCLMNSEQ"		, listMap.get("MSGCLMNSEQ"));
		}

		String userid = com.eactive.eai.rms.common.login.SessionManager.getUserId(request);
		detail.put("userid", userid );
    	
    	service.insert(detail,gridList);
    	
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.telegram.UpdateTelegramCommand",map.get("newMsgMetaDstcd"));
		agentUtilService.broadcast(command);
		
		HashMap<String, Object> result = new HashMap<String, Object>();
		result.put("detail",detail);
		result.put("list",gridList);
		ModelAndView modelAndView = new ModelAndView("jsonView", result);	
		
		return modelAndView;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "/bap/admin/message/messageMetaMan.json",params = "cmd=LIST_DOWNLOAD_SQL")
	public ModelAndView downloadSql(HttpServletRequest request,
		HttpServletResponse response,@RequestParam HashMap<String,Object> map) throws Exception {		

		List<Map<String, Object>> msgMetaList = new ArrayList<Map<String, Object>>();
		for (String searchMsgMetaDstcd : map.get("searchMsgMetaDstcdList").toString().split(",")) {
			HashMap<String, Object> msgMeta = service.selectDetail(searchMsgMetaDstcd);
			msgMetaList.add((Map<String, Object>)msgMeta.get("detail"));
		}
		
		HashMap<String,Object> messageMeta = new HashMap<String,Object>();
		messageMeta.put("list", msgMetaList);
		messageMeta.put("userid",com.eactive.eai.rms.common.login.SessionManager.getUserId(request));
		messageMeta.put("fileName", map.get("fileName"));
		messageMeta.put("svrType", map.get("svrType"));

    	ModelAndView modelAndView = new ModelAndView("jsonView",service.mkInserSqlForMsgMeta(messageMeta));	
		
		return modelAndView;
	}
	@RequestMapping(value= "/bap/admin/message/messageMetaMan.view",params = "cmd=LIST_FILE_DOWNLOAD")
	public String fileDownload(HttpServletRequest request) throws Exception {
		
		return "/bap/admin/common/filedownload";
	}
}