package com.eactive.eai.rms.bap.manage.work.inf;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.bap.loader.intf.deploy.InterfaceDeploy;
import com.eactive.eai.rms.common.base.BapBaseAnnotationController;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class BapInterfaceProcController extends BapBaseAnnotationController  {

   @Autowired
   @Qualifier("bapInterfaceProcService")
   private BapInterfaceProcService service;

    // 자원 import 병목을 막기 위한 key
    private static Object key = new Object();
   
   @RequestMapping(value= "/bap/admin/work/interfaceManBatchFep.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;
   }
      
    @RequestMapping(value = "/bap/admin/work/interfaceManBatchFep.json", params = "cmd=LIST_BATCH")
    public ModelAndView selectListBatch(JsonPageVo pageVo, @RequestParam Map<String, Object> paramMap) {
        Map<String, Object> map = service.selectListBatch(pageVo.getStartNum(), pageVo.getEndNum(), paramMap);

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

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

        return new ModelAndView("jsonView", resultMap);
    }
    
    @RequestMapping(value = "/bap/admin/work/interfaceManBatchFep.json", params = "cmd=LIST_COMBO")
    public ModelAndView selectListProps(HttpServletRequest request) throws Exception{
        
       Map<String, Object> resultMap = new HashMap<>();
       
       // appcode
        Map<String, Object> map = service.selectListProp("BzSystem");
        resultMap.put("BzSystem", map);
        // 대외일괄업무코드
        map = service.selectListProp("BzSystem_BAP");
        resultMap.put("BzSystem_BAP", map);
        // 대외기관코드
        String userid = SessionManager.getUserId(request);
        map = service.selectAuthAppCode(userid);
        resultMap.put("authList", map);

        return new ModelAndView("jsonView", resultMap);
    }
    
    @RequestMapping(value = "/bap/admin/work/interfaceManBatchFep.json", params = "cmd=DETAIL")
    public ModelAndView selectDetailBatchFep(HttpServletRequest request,
         HttpServletResponse response, @RequestParam HashMap<String,Object> param) {
        Map<String, Object> map = service.selectDetailBatch(param);
        return new ModelAndView("jsonView", map);
    }
    
    @RequestMapping(value = "/bap/admin/work/interfaceManBatchFep.json", params = "cmd=INSERT_BATCH")
    public ModelAndView insertBatch(@RequestParam Map<String, Object> map, HttpServletRequest request) throws Exception{
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        // prefix 설정
        String priFix   = "X";
        String snDst    = map.get("snDst").toString();
        String tgtSysCd = "FEP";
        String strSys    = map.get("appCd").toString();
        String srcSysCd = "FEP";
        
        // snDst S : 송신 / T : 송,수신 / R : 수신
        if("S".equals(snDst)) {
           srcSysCd = strSys;
        }else if("T".equals(snDst)) {
            tgtSysCd = strSys;
        }else {
            tgtSysCd = srcSysCd;
            srcSysCd = strSys;
        }
        
        String tmpInfId = srcSysCd + tgtSysCd;
        
        map.put("beforeInfId", srcSysCd + "_" + tgtSysCd);
        map.put("tmpInfId", tmpInfId);
        
        resultMap = service.mergeBJ01(map);
        
        if("0".equals(resultMap.get("result").toString())) {
            resultMap = service.selectDetailBatch((HashMap<String,Object>)resultMap);
            resultMap.put("result", "0");
        }
        
        return new ModelAndView("jsonView", resultMap);
    }
    
    @RequestMapping(value = "/bap/admin/work/interfaceManBatchFep.json", params = "cmd=UPDATE_BATCH")
    public ModelAndView updateBatch(@RequestParam Map<String, Object> map, HttpServletRequest request) throws Exception{
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        resultMap = service.mergeBJ01(map);
        
        if("0".equals(resultMap.get("result").toString())) {
            resultMap = service.selectDetailBatch((HashMap<String,Object>)resultMap);
            resultMap.put("result", "0");
        }
        
        return new ModelAndView("jsonView", resultMap);
    }
    
    @RequestMapping(value = "/bap/admin/work/interfaceManBatchFep.json", params = "cmd=DELETE_BATCH")
    public ModelAndView deleteBatch(@RequestParam Map<String, Object> map, HttpServletRequest request) throws Exception{
        service.deleteBJ01(map);
        return new ModelAndView("jsonView");
    }

    @PostMapping(value = "/bap/admin/work/interfaceManBatchFep.file", params = "cmd=LIST_IMPORT_FILE")
    public ResponseEntity<?> listImportFromFile(@RequestParam("file") MultipartFile file) {

        try {
            if (file != null) {
                String extension = FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
                if ("json".equals(extension)) {

                    synchronized (key) {
                        InterfaceDeploy interfaceDeploy = service.insertInterfaceFromJson(file);

                        HashMap<String, Object> broadcastResult = agentUtilService.broadcast(new CommonCommand("com.eactive.eai.agent.rule.dirInfo.RefreshAllJobCommand", interfaceDeploy.getBjobmsgdstcd()));
                        if (!broadcastResult.entrySet().stream().allMatch(entry -> entry.getValue().equals("success"))) {
                            String mapString = CommonUtil.getMapString(broadcastResult, false);
                            throw new Exception("데이터 수정 완료하였으나 인스턴스 동기화에 실패하였습니다. " + mapString);
                        }

                        return ResponseEntity.ok("Insert&Reload success");
                    }

                }
            }

        } catch (Exception e) {
            logger.error(e);
            return ResponseEntity.internalServerError().body("Error processing file");
        }
        return ResponseEntity.internalServerError().body("empty file or unmatched extension");
    }
   
}
