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

import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.rms.bap.common.base.BapBaseService;
import com.eactive.eai.rms.bap.loader.intf.InterfaceDeployService;
import com.eactive.eai.rms.bap.manage.comm.property.BapPropertyDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.eactive.eai.rms.bap.loader.intf.deploy.InterfaceDeploy;
import org.springframework.web.multipart.MultipartFile;

@Service("bapInterfaceProcService")
public class BapInterfaceProcService extends BapBaseService {

   @Autowired
   @Qualifier("bapInterfaceProcDao")
   private BapInterfaceProcDao dao;
   
   @Autowired
   @Qualifier("bapPropertyDao")
   private BapPropertyDao propDao;

    @Autowired
    @Qualifier("BapInterfaceDeployService")
    private InterfaceDeployService interfaceDeployService;

    private final ObjectMapper objectMapper = new ObjectMapper();
   
    /**   
     * 대외 일괄 배치 인터페이스 목록조회
     * @param startNum
     * @param endNum
     * @param paramMap
     * @return
     */
    public Map<String, Object> selectListBatch(int startNum, int endNum, Map<String, Object> paramMap) {

        List<String> searchStatusList = new ArrayList<String>();
        String [] status = StringUtil.getNullStr(paramMap.get("status")).split(",");
        for (int i = 0; i < status.length; i++) {
            if (status[i] != null && !"".equals(status[i])) {
                searchStatusList.add(status[i]);
            }
        }
        
        paramMap.put("searchStatus", searchStatusList);

        // 전체 목록수 얻기
        int totalCount = dao.selectListCountBatch(paramMap);

        paramMap.put("startNum", startNum);// 시작 record
        paramMap.put("endNum", endNum);// 끝 record

        List<Map<String, Object>> list = dao.selectListBatch(paramMap);

        HashMap<String, Object> map = new HashMap<>();

        map.put("totalCount", totalCount);

        map.put("list", list);

        return map;
    }
    
    /**   
     * 대외 일괄 배치 프로퍼티 목록조회
     * @param startNum
     * @param endNum
     * @param paramMap
     * @return
     */
    public Map<String, Object> selectListProp(String prptyGroupName) throws Exception{

       HashMap<String, Object> map = new HashMap<>();
       
       
       // 코드성 데이터 조회 
       // app code
      HashMap<String, Object> paramMap = new HashMap<String, Object>();
      paramMap.put("prptyGroupName", prptyGroupName);
      
      List<Map<String, Object>> list = propDao.propertyDetail(paramMap);
      List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
      
      for( Map<String, Object> tmp : list ) {
         tmp.put("CODENAME", tmp.get("PRPTYNAME") + "[" + tmp.get("PRPTY2VAL") + "]");
         newList.add(tmp);
      }

      map.put("rows", newList);
      
        return map;
    }
    
    /**   
     * 대외 일괄 배치 사용자별 app code 조회
     * @param startNum
     * @param endNum
     * @param paramMap
     * @return
     */
    public Map<String, Object> selectAuthAppCode(String userId) throws Exception{

       HashMap<String, Object> map = new HashMap<>();
       
       // 코드성 데이터 조회 
       // app code
      HashMap<String, Object> paramMap = new HashMap<String, Object>();
      paramMap.put("userId", userId);
      
      List<Map<String, Object>> list = dao.selectAuthAppCode(paramMap);

      map.put("rows", list);
      
        return map;
    }
    
    /**
     * 대내 일괄 배치 인터페이스 상세조회
     * @param infId
     * @return
     */
    public Map<String, Object> selectDetailBatch(HashMap<String,Object> param) {
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        paramMap.put("infId", param.get("infId"));
        resultMap = dao.selectDetailBatch(paramMap);

        return resultMap;
    }
    
   //일괄전송 BJ01 및 본 테이블 반영
   public Map<String, Object> mergeBJ01(Map<String, Object> inputData) throws Exception {
      
      Map<String, Object> resultMap = new HashMap<String, Object>();
      
      String bj01pkgen = ""; 
      logger.info( "BF BJ01 I/U" + inputData);            
      // TSEAIBJ01 데이터 처리
      int selCountBJ01 = dao.selectCountBJ01(inputData);
      
      //일괄전송 고유 업무 코드 구하기.
      String bzwkDstCd = "";
      try {
         bzwkDstCd = dao.selectBzwkDstCd(inputData);
      } catch(Exception e) {
         e.printStackTrace();
      }
      logger.info("bzwkDstCd : "+ bzwkDstCd);
      inputData.put("bzwkDstCd", bzwkDstCd);
      
      String fileSize = inputData.get("recSize").toString();
      
      if( "".equals(fileSize) ) {
         inputData.put("recSize", "0");
      }
      
      logger.info(">>>>>>>>>>>bapDeploy : "+ inputData.toString());
      if (selCountBJ01 == 0) {
         String sndst = (String)inputData.get("snDst");
         String fileSendUseYN = "0";
         String fileRecvUseYN = "0";
         if(sndst.equals("S")) { //송신
            fileSendUseYN = "1";
         } else if(sndst.equals("R")) { // 수신
            fileRecvUseYN = "1";
         }  else if(sndst.equals("A")) { // 송수신
            fileSendUseYN = "1";
            fileRecvUseYN = "1";
         } else {  // 잘못된 코드
            throw new Exception("잘못된 코드입니다");
         }
         
         inputData.put("fileSendUseYN", fileSendUseYN);
         inputData.put("fileRecvUseYN", fileRecvUseYN);
         
         logger.info("bapDeploy : "+ inputData.toString());
         
         // 키 값을 기준으로 seq 채번
         dao.generateSequence(inputData);
         bj01pkgen = dao.selectSequence(inputData); 
         logger.info("bj01pkgen : "+ bj01pkgen);
         
         inputData.put("infId", bj01pkgen);
         
         dao.insertBJ01(inputData);
         logger.info("insert BAP interface into TSEAIBJ01 : "+ inputData);
      } else {
         logger.info("else bj01pkgen : "+ bj01pkgen);
         inputData.put("bjobMsgDstcd", inputData.get("infId"));
         dao.updateBJ01(inputData);
         logger.info("update BAP interface of TSEAIBJ01 : "+ inputData);
      }
      
        resultMap.put("result", "0");
        resultMap.put("infId", inputData.get("infId"));
        
        return resultMap;
   }
   
   // BJ01 테이블 데이터 삭제
   public void deleteBJ01(Map<String, Object> inputData) throws Exception {
      dao.deleteBJ01(inputData);
   }
   public InterfaceDeploy insertInterfaceFromJson(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new IOException("File is empty");
        }

        try (InputStream inputStream = file.getInputStream()) {
            InterfaceDeploy deploy = objectMapper.readValue(inputStream, InterfaceDeploy.class);
            interfaceDeployService.saveDeploy(deploy);

            return deploy;
        }
    }
}
