package com.eactive.eai.rms.onl.manage.rule.transform2;

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

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.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.rms.common.base.BaseAnnotationController;
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.spring.LocaleMessage;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.onl.manage.rule.transform.TransformVo;
import com.eactive.eai.rms.onl.transaction.extnl.InterfaceManService;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Transform2RefController extends BaseAnnotationController {
	
	@Autowired
    @Qualifier("localeMessage")
    private LocaleMessage localeMessage;

    @Autowired
    @Qualifier("transformService")
    private Transform2Service service;

    @Autowired
    private ComboService comboService;

    @Autowired
    private InterfaceManService interfaceManService;

//    @Autowired
//    private TransformMapper transformMapper;
//
//    @Autowired
//    private TransformItemMapper transformItemMapper;

    @RequestMapping(value = "/onl/admin/rule/transform2Man.view")
    public String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false) String cmd) {
    	if (cmd == null || "LIST".equalsIgnoreCase(cmd)) {
            cmd = "";
        } else {
            cmd = CamelCaseUtil.converCamelCase(cmd);
        }
        String path = request.getServletPath();
        return path.split("[.]")[0] + cmd;
    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=LIST_COMBO")
    public ModelAndView listCombo(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
    	
        String userId = SessionManager.getUserId(request);
        
        //model.addAttribute("BzSystem", comboService.selectBzwkOptions(userId)); TODO

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

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response, 
    		String infId) throws Exception {

        // admin 권한
        String roleId = SessionManager.getRoleIdString(request);
        String isAdmin = "N";
        if (roleId.indexOf("admin") > -1) { // admin 일경우
            isAdmin = "Y";
        }
        Map resultMap = new HashMap();

        // List<Map<String, String>> listFunction = comboService.selectTransformFunctionCombo(); TODO

        List<ComboVo> listCnvsnType = comboService.getFromCode("CNVSN_TYPE");

        List<ComboVo> listSvrDstcd = comboService.getFromCode("INOUT_TYPE");
        List<ComboVo> listUseYn = comboService.getFromCode("USE_YN");// 사용여부

        // Map<String, Object> interfaceMap = interfaceService.selectDetail(infId, "N"); TODO

        // resultMap.put("functionRows", listFunction); TODO
        resultMap.put("isAdmin", isAdmin);
        resultMap.put("useYnRows", listUseYn);
        resultMap.put("cnvsnType", listCnvsnType);
        // resultMap.put("interfaceMap", interfaceMap); TODO
        ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
        return modelAndView;
    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=LIST_EAISVCNAME_COMBO")
    public ModelAndView eaiSvcNameCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<ComboVo> listCnvsnType = comboService.getFromCode("CNVSN_TYPE");

        List<ComboVo> listInoutTypeCd = comboService.getFromCode("INOUT_TYPE");// EAI서버구분코드
        List<ComboVo> listUseYn = comboService.getFromCode("USE_YN");

        Map resultMap = new HashMap();
        resultMap.put("cnvsnTypeRows", listCnvsnType);
        resultMap.put("inoutTypeRows", listInoutTypeCd);
        resultMap.put("useYnRows", listUseYn);

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

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=LIST_LAYOUT_ITEM")
    public ModelAndView listLayoutItem(HttpServletRequest request, HttpServletResponse response, 
    		String loutIoId, String loutType) throws Exception {
    	
//        Map<String, Object> map = service.selectLayoutItems(loutIoId, loutType); TODO
//        ModelAndView modelAndView = new ModelAndView("jsonView", map);
//        return modelAndView;
    	return null;
    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=INSERT_CNVSN_TYPE")
    @ResponseBody
    public ResponseEntity<TransformVo> insertCnvsnType(TransformVo transformVo) {
//        Transform transform = transformMapper.toEntity(transformVo); TODO
//        transform.setUseYn("Y");
//        transform = service.insert(transform);
//        return ResponseEntity.ok(transformMapper.toVo(transform));
    	return null;
    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=DELETE")
    private String delete(HttpServletRequest request, HttpServletResponse response, 
    		String cnvsnName, String infId, String cnvsnType) throws Exception {

        // service.deleteById(cnvsnName);TODO
        return null;

    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=DELETE_LIST")
    private ModelAndView deleteMulti(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> map) throws Exception {
        String message = "";

        String[] cnvsnNameArr = ((String) map.get("cnvsnNames")).split(",");
        String[] eaiSvcNameArr = ((String) map.get("eaiSvcNames")).split(",");
        String[] cnvsnTypeArr = ((String) map.get("cnvsnTypes")).split(",");

        int idx = 0;
        for (String cnvsnName : cnvsnNameArr) {
            // service.deleteById(cnvsnName); TODO
            idx++;
        }

        message = "총" + idx + "건을 삭제하였습니다";

        Map resultMap = new HashMap();
        resultMap.put("message", message);
        ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
        return modelAndView;

    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=LIST_TRANSFORM_SOURCE_RESULT")
    public ModelAndView transformSourceResult(HttpServletRequest request, HttpServletResponse response, String cnvsnName) throws Exception {

        List list = service.selectTransformSourceResult(cnvsnName);

        HashMap map = new HashMap();
        map.put("rows", list);

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

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=LIST_TRANSFORM_ITEM")
    public ModelAndView transformItem(HttpServletRequest request, HttpServletResponse response, 
    		String loutIoId, String loutType, String cnvsnName) throws Exception {
//        Map<String, Object> map = service.selectTransformItems(cnvsnName, loutIoId, loutType);
//        ModelAndView modelAndView = new ModelAndView("jsonView", map);
//        return modelAndView; TODO
    	return null; 
    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=UPDATE")
    public ResponseEntity<TransformVo> update(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> paramMap, 
    		TransformVo transformVo, String srcLayoutName, String tgtLayoutName) throws Exception {

        String gridData = (String) paramMap.get("gridData");
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

//        List<TransformItemVo> transformLayoutVos = objectMapper.readValue(gridData, new TypeReference<List<TransformItemVo>>() {  });
//
//        transformLayoutVos.forEach(t -> t.setCnvsnName(transformVo.getId()));
//
//        List<TransformItem> transformItems = transformLayoutVos.stream().map(transformItemMapper::toEntity)
//                .collect(Collectors.toList());
//
//        List<TransformLayout> transformLayouts = new ArrayList<>();
//
//        mapTransformLayout(srcLayoutName, tgtLayoutName, transformVo.getId(), transformLayouts);
//        Transform transform = service.update(transformVo.getId(), transformLayouts, transformItems);
//
//        return ResponseEntity.ok(transformMapper.toVo(transform)); TODO
        
        return null; 
    }

//    private void mapTransformLayout(String srcLayoutName, String tgtLayoutName, String cnvsnName, List<TransformLayout> transformLayouts) {
//        TransformLayout srcTransformLayout = TransformLayout.builder().loutName(srcLayoutName).id(TransformLayoutId
//                .builder().cnvsnName(cnvsnName).sourcRsultDstcd(Transform.TRANSFORM_DIRECTION_SOURCE).build()).build();
//        TransformLayout tgtTransformLayout = TransformLayout.builder().loutName(tgtLayoutName).id(TransformLayoutId
//                .builder().cnvsnName(cnvsnName).sourcRsultDstcd(Transform.TRANSFORM_DIRECTION_TARGET).build()).build();
//
//        transformLayouts.add(srcTransformLayout);
//        transformLayouts.add(tgtTransformLayout);
//    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=INITIALIZES")
    public ModelAndView initializes(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HashMap map = new HashMap();

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

    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=INITIALIZE")
    public ModelAndView initialize(HttpServletRequest request, HttpServletResponse response, String cnvsnName)
            throws Exception {
        HashMap map = new HashMap();
        ModelAndView modelAndView = new ModelAndView("jsonView", map);
        return modelAndView;
    }

    @RequestMapping(value = "/onl/admin/rule/transform2Man.json", params = "cmd=LIST_INITIALIZE")
    public ModelAndView listInitialize(HttpServletRequest request, HttpServletResponse response,
            @RequestParam HashMap<String, Object> paramMap) throws Exception {

        String[] chkItemsArr = ((String) paramMap.get("chkItems")).split(",");
        Vector vec = new Vector<>();
        for (String chkItem : chkItemsArr) {
            vec.add(chkItem);
        }

        HashMap map = new HashMap();

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

}
