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

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

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.acl.user.BizDao;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.excel.ExcelSheet;
import com.eactive.eai.rms.common.excel.ExcelUtil;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.util.StringUtils;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.common.service.AgentUtilService;
import com.eactive.eai.transformer.dao.excel.ArraySheet;
import com.eactive.eai.transformer.dao.excel.Layout2ExcelDao;
import com.eactive.eai.transformer.dao.excel.Layout2ExcelLoadDao;
import com.eactive.eai.transformer.dao.excel.LayoutExcelDao;
import com.eactive.eai.transformer.layout.Layout;

@Service("layoutExcelService")
public class LayoutExcelService extends BaseService {
	
	@Autowired
	@Qualifier("layoutDao")
	private LayoutDao dao;
	
   @Autowired
   @Qualifier("layout2ExcelDao")
   private Layout2ExcelDao excelDao;	
	
	@Autowired
	@Qualifier("dataSource")
	private DataSource dataSource;

	@Autowired
	private LayoutExcelDao layoutExcelDao;
	
	@Autowired
    @Qualifier("onlAgentUtilService")
    public AgentUtilService agentUtilService;
	
	@Autowired
    @Qualifier("bizDao")
    public BizDao bizDao;
	public List<HashMap<String,Object>> uploadFull(String data[][], HttpServletRequest request,String saveType,String sheetName, String eaisevrDstcd) throws Throwable {
		int row = data.length;
		int col = 0;

		if (row > 0) {
			col = data[0].length;
		}

		if (row < 4 || col <= 0) {
			String msg = "[Layout excel upload] Invalid array size : row=" + row + " ,col=" + col;
			logger.error(msg);
			throw new Exception(msg);
		}

		ArraySheet sheet = new ArraySheet(row, col);
		for (int r = 0; r < row; r++) {
			for (int c = 0; c < col; c++) {
				sheet.setString(r, c, data[r][c]);
			}
		}
		
		String service = SessionManager.getServiceTypeKey(request);
//		String service = "EAI";
		//엑셀의 서비스 명 과 현재 서비스명 체크
		int checkCount = checkServiceName(data, row, col, service);
		if (checkCount == 0) {
			logger.error("service name check ? current service " + service);
			throw new Exception("service name check ? current service " + service);
		}
		
		//Layout목록 추출  (한개의 sheet에 여러개가 들어 있을수 있음)
		List<HashMap<String, Object>> listName = extractLayoutName(data, row, col);

		if (listName.size() == 0) {
			logger.error("Can't generate layout name!");
			throw new Exception("Can't generate layout name!");
		}
		for (HashMap<String,Object> r : listName ) {
			r.put("SHEETNAME",sheetName);
			r.put("LAYOUTNAME",r.get("loutName"));
			r.put("LAYOUTITEM","");
			r.put("RESULT", "O");
			r.put("MESSAGE", "");
			r.put("DELETEMARK","N");
			r.put("DUPLICATED","N");
			String bizCode = (String)r.get("bizCode");
			// 여러개의 업무중 한개라도 권한이 없으면 => fail 처리한다.
			if (!isValidEaiBzwkDstcd(bizCode, request)) {
				throw new Exception("[" + bizCode + "] 업무에 대한 권한이 없습니다.");
			}

			HashMap<String,Object> check = dao.selectDetail(r);
			if (check != null) {
				if ("1".equals(saveType)) {
					r.put("DELETEMARK","Y");
				} else {
					r.put("DUPLICATED","Y");
					r.put("RESULT", "X");
					r.put("MESSAGE", "중복된 레이아웃 입니다.");

				}
			} 
		}
		Map<String, Layout> map = new Layout2ExcelLoadDao().load(sheet);
		
		for (HashMap<String,Object> r : listName ) {
			if ("Y".equals(r.get("DUPLICATED"))){
				continue;
			}
			if ("Y".equals(r.get("DELETEMARK"))){
				deleteUploadLayout(r, r);
			}
			try{
				Layout layout = map.get(r.get("LAYOUTNAME"));
				layout.setEaiSvrDstcd(eaisevrDstcd);
				layoutExcelDao.saveLayout(layout);
			} catch (Exception e) {
				r.put("RESULT", "X");
				r.put("MESSAGE", e.getMessage());
			}
			CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadLayoutCommand",r.get("LAYOUTNAME"));
			HashMap returnMap = agentUtilService.broadcast(command);

			r.put("MESSAGE", CommonUtil.getMapString(returnMap, true)); 
		}
		return listName;
	}
	
	private int checkServiceName(String data[][], int row, int col,	String service) {
		int i = 0;

		if (row > 3 && col > 0) {
			for (int c = 0; c < col; c++) {
				if (data[0][c].startsWith(service)) {
					i++;
				}
			}
		}

		return i;
	}

	private List<HashMap<String, Object>> extractLayoutName(String data[][], int row, int col) {
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

		if (row > 3 && col > 0) {
			for (int c = 0; c < col; c++) {
				
//				if (data[0][c].startsWith(DataSourceTypeManager.EAI)
//						|| data[0][c].startsWith(DataSourceTypeManager.FEP)) {
					String str0 = data[0][c].trim();
					String str1 = data[1][c].trim();
					String str3 = data[3][c].trim();
					if (str1.length() > 0 && str3.length() > 0) {
						StringBuffer sb = new StringBuffer();
						sb.append(str1 + "_");
						sb.append(str3 + "_");
						sb.append(str0.substring(str0.indexOf('(') + 1, str0.indexOf(')')));

						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("loutName", sb.toString());
						map.put("bizCode", str1);
						list.add(map);
					}
//				}
			}
		}

		return list;
	}

	private boolean isValidEaiBzwkDstcd(String eaiBzwkDstcd,HttpServletRequest request) throws Exception {
		String userId = SessionManager.getUserId(request);

		if (StringUtils.isEmpty(userId)) {
			throw new Exception("로그인 되지 않았습니다.");
		}
		HashMap paramMap = new HashMap();
		paramMap.put("userId", userId);
		List<HashMap> list = bizDao.selectUserBizCodes(paramMap);
		if (list.size() > 0) {
			for(HashMap tmpList : list){
				if(eaiBzwkDstcd.equals((String)tmpList.get("BIZCODE").toString().trim())){
					return true;
				}
			}
		}

		return false;
	}
	
	private void deleteUploadLayout(HashMap<String,Object> vo, HashMap<String,Object> nVo) throws Exception {
		dao.deleteItemAll(vo);
		dao.delete(nVo);
	}
	
	public List<Map<String,Object>> excelParsing(String decFile, String fileExtension) throws BizException, Exception {
		List<Map<String,Object>> ret = new ArrayList<Map<String,Object>>();
		
		String [] sheetNames = { "시스템인터페이스송수신항목설계서" };
		ExcelSheet[] sheets = null;
		try {
			sheets = (ExcelSheet[])ExcelUtil.loadExcelFile(decFile);
			for (int i=0; i<sheets.length; i++) {
				String data[][] = null;
				for (String sheetName : sheetNames) {
					if (StringUtils.equals(sheets[i].getName(), sheetName)) {
						int index = 0;
						if (StringUtils.equals(fileExtension, "xlsx")) {
							int maxcolumn = 32;
							while (sheets[i].existsRowForXlsx(index)) {
								index++;
							}
							data = new String[index][maxcolumn];
							for (int row=0; row<index; row++) {
								for (int col=0; col<maxcolumn; col++) {
									data[row][col]=sheets[i].getCellStringForXlsx(row, col);
								}
							}
						} else {
							int maxcolumn = 28;
	        				while (sheets[i].existsRow(index)) {
								index++;
							}
							data = new String[index][maxcolumn];
							for(int row=0;row<index;row++){
								for(int col=0;col<maxcolumn;col++){
									data[row][col]=sheets[i].getCellString(row, col);
								}
							}
						}
						Map<String,Object> map = new HashMap<String,Object>();
						map.put("sheetName", sheets[i].getName());
						map.put("data", data);
						ret.add(map);
					} else {
						// sheet 명명 규칙 오류
					}
				}
			}
			if (ret.size() == 0) {
				throw new BizException("유효한 시트명이 존재하지 않습니다.");
			}
			
		} catch (BizException be) {
			throw be;
		} catch (Exception e) {
			throw e;
		}
		
		return ret;
	}
   public String getSheetName() {
      return excelDao.getSheetName();
   }
}
