package com.eactive.eai.rms.onl.manage.serviceinfo.b2bservice;

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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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.common.util.StringUtil;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.util.ControllerValidationHelper;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.google.gson.Gson;

@Controller
public class B2bServiceController extends OnlBaseAnnotationController {

	@Autowired
	private B2bServiceManService service;

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.view")
	public void viewList() {
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.view", params = "cmd=DETAIL")
	public String detailView() {
		return "/onl/admin/service/b2bServiceManDetail";
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<B2bServiceUI>> selectList(HttpServletRequest request, Pageable pageable,
			B2bServiceUISearch uiSearch) {
		Page<B2bServiceUI> page = service.selectList(pageable, uiSearch);
		return ResponseEntity.ok(new GridResponse<B2bServiceUI>(page));
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=DETAIL")
	public ResponseEntity<B2bServiceUI> selectDetail(HttpServletRequest request, HttpServletResponse response,
			String extnlInstiIdnfiName, String svcPrcssNo) {
		B2bServiceUI map = service.selectDetail(extnlInstiIdnfiName, svcPrcssNo);
		return ResponseEntity.ok(map);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=INSERT")
	public ResponseEntity<?> insert(HttpServletRequest request, HttpServletResponse response, @Valid B2bServiceUI ui,
			BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return ControllerValidationHelper.checkValidation(bindingResult);
		}
		service.insert(ui);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.b2bservice.ReloadB2BServiceCommand",
				ui.getExtnlInstiIdnfiName());
		HashMap<String, Object> commandResult = agentUtilService.broadcast(command);
		return ResponseEntity.ok(commandResult);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=UPDATE")
	public ResponseEntity<?> update(HttpServletRequest request, HttpServletResponse response, @Valid B2bServiceUI ui,
			BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return ControllerValidationHelper.checkValidation(bindingResult);
		}
		service.update(ui);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.b2bservice.ReloadB2BServiceCommand",
				ui.getExtnlInstiIdnfiName());
		HashMap<String, Object> commandResult = agentUtilService.broadcast(command);
		return ResponseEntity.ok(commandResult);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=DELETE")
	public ResponseEntity<?> delete(HttpServletRequest request, HttpServletResponse response,
			String extnlInstiIdnfiName, String svcPrcssNo) throws Exception {
		service.delete(extnlInstiIdnfiName, svcPrcssNo);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.b2bservice.RemoveB2BServiceCommand",
				extnlInstiIdnfiName + svcPrcssNo);
		HashMap<String, Object> commandResult = agentUtilService.broadcast(command);
		return ResponseEntity.ok(commandResult);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView selectListInitCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userId = SessionManager.getUserId(request);
		Map<String, Object> map = service.selectListInitCombo(userId);
		return new ModelAndView("jsonView", map);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=LIST_DETAIL_COMBO")
	public ModelAndView selectListDetailCombo(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String userId = SessionManager.getUserId(request);
		Map<String, Object> map = service.selectListDetailCombo(userId);
		return new ModelAndView("jsonView", map);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=INITIALIZES")
	public ModelAndView initializes(HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.b2bservice.ReloadB2BServiceCommand", "ALL");
		HashMap<String, Object> returnMap = agentUtilService.broadcast(command);
		HashMap<String, Object> map = new HashMap<>();
		map.put("message", CommonUtil.getMapString(returnMap, true));

		return new ModelAndView("jsonView", map);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=INITIALIZE")
	public ModelAndView initialize(HttpServletRequest request, HttpServletResponse response, String extnlInstiIdnfiName)
			throws Exception {
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.b2bservice.ReloadB2BServiceCommand",
				extnlInstiIdnfiName);
		HashMap<String, Object> returnMap = agentUtilService.broadcast(command);
		HashMap<String, Object> map = new HashMap<>();
		map.put("message", CommonUtil.getMapString(returnMap, true));

		return new ModelAndView("jsonView", map);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=CLONE")
	private ResponseEntity<?> clone(HttpServletRequest request, HttpServletResponse response,
			@Valid B2bServiceUI ui, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return ControllerValidationHelper.checkValidation(bindingResult);
		}
		service.clone(ui);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.b2bservice.ReloadB2BServiceCommand",
				ui.getNewExtnlInstiIdnfiName());
		HashMap<String, Object> commandResult = agentUtilService.broadcast(command);
		return ResponseEntity.ok(commandResult);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response,
			B2bServiceUISearch uiSearch, @RequestParam HashMap<String, Object> paramMap) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<>();
		String headersStr = (String) paramMap.get("headersStr");
		headersStr = headersStr.substring(0, headersStr.length() - 1);
		paramMap.put("headersStr", headersStr);

		Map<String, List<?>> list = service.selectListToExcel(uiSearch);
		Gson gson = new Gson();
		String jsonStr = gson.toJson(list.get("list"));
		HashMap<String, Object>[] list2 = gson.fromJson(jsonStr, HashMap[].class);

		String[] headers = gson.fromJson((String) paramMap.get("header"), String[].class);
		String[] headerTitles = gson.fromJson((String) paramMap.get("headerTitle"), String[].class);

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

		resultMap.put("headers", headers);
		resultMap.put("headerTitles", headerTitles);
		resultMap.put("datas", list2);
		resultMap.put("fileName", paramMap.get("fileName"));
		resultMap.put("merge", lmerge);
		return new ModelAndView("excelView", resultMap);
	}

	@RequestMapping(value = "/onl/admin/service/b2bServiceMan.json", params = "cmd=CLONETOPROD")
	public ModelAndView cloneToProd(HttpServletRequest request, @RequestParam HashMap<String, Object> paramMap)
			throws Exception {
		if (!SystemUtil.isDevServer()) {
			throw new Exception("only support dev server ");
		}
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String userId = SessionManager.getUserId(request);
		String cmDate = StringUtil.getNullStr(paramMap.get("CmDate"));
		String cmTime = StringUtil.getNullStr(paramMap.get("CmTime"));
		String sysCode = StringUtil.getNullStr(paramMap.get("SysCode"));
		String listSvcName = StringUtil.getNullStr(paramMap.get("selectedList"));
		String serviceType = StringUtil.getNullStr(paramMap.get("serviceType"));

		try {
			boolean ret = service.extractB2B(userId, listSvcName, cmDate, cmTime, sysCode, serviceType);
			if (!ret) {
				throw new Exception("CM대상 자원의 운영적용에 있어 에러가 발생했습니다.");
			}
			resultMap.put("message", "적용이 완료되었습니다.");
		} catch (BizException be) {
			throw new Exception(be.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		}

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

}