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

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.onl.company.Company;
import com.eactive.eai.rms.data.entity.onl.company.CompanyId;
import com.eactive.eai.rms.data.entity.onl.company.CompanyService;
import com.eactive.eai.transformer.dao.excel.ArraySheet;

@Service
@Transactional
public class CompanyManService extends BaseService {

	private static final int ROW_COM_CD = 1; // 업체코드
	private static final int ROW_COM_NAME = 5; // 업체명
	private static final int ROW_APP_CD = 2; // 어플리케이션코드
	private static final int ROW_BIZ_KEY = 3; // 업무구분코드
	private static final int ROW_COM_PSN_NAME = 9; // 업체전산담당자
	private static final int ROW_COM_PSN_PHONE = 10; // 업체전산담당자연락처

	@Autowired
	private CompanyDao dao;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private CompanyUIMapper companyUIMapper;

	public Page<CompanyUI> selectList(Pageable pageable, CompanyUISearch companyUISearch) {
		Page<Company> page = companyService.findPageWithSearch(pageable, companyUISearch);
		return page.map(companyUIMapper::toVo);
	}

	public CompanyUI selectDetail(CompanyUI companyUI) {
		CompanyId companyId = companyUIMapper.toId(companyUI);
		Optional<Company> company = companyService.findById(companyId);
		return company.map(companyUIMapper::toVo).orElse(null);
	}

	public void insert(CompanyUI companyUI) {
		Company company = companyUIMapper.toEntity(companyUI);
		companyService.save(company);
	}

	public void update(CompanyUI companyUI) {
		CompanyId companyId = companyUIMapper.toId(companyUI);
		Company company = companyService.getById(companyId);
		companyUIMapper.updateToEntity(companyUI, company);
		companyService.save(company);
	}

	public void delete(CompanyUI companyUI) {
		CompanyId companyId = companyUIMapper.toId(companyUI);
		companyService.deleteById(companyId);
	}

	public Map<String, Object>[] selectListToExcel() {
		@SuppressWarnings("unchecked")
		Map<String, Object>[] mapArray = companyService
				.findAll(Sort.by("id.groupCoCd", "id.appCode", "id.companyCode", "companyName")).stream().map(e -> {
					Map<String, Object> map = new HashMap<>();
					map.put("APPCODE", e.getId().getAppCode());
					map.put("COMPANYCODE", "\t" + e.getId().getCompanyCode());
					map.put("COMPANYNAME", e.getCompanyName());
					String bzwkName = "[" + e.getId().getBzwkDstCode() + "] " + e.getBzwkName();
					map.put("bzwkNameWithCode", bzwkName);
					map.put("COMPANYITCONTACTNAME", e.getCompanyItContactName());
					map.put("BZWKCONTACTPERSON", e.getBzwkContactPerson());
					map.put("ITCONTACTPOINTPERSON1", e.getItContactPointPerson1());
					return map;
				}).toArray(HashMap[]::new);

		return mapArray;
	}

	// FIXME : 필요시 추후 개발
	public HashMap<String, Object> selectPopList(int startNum, int endNum, String eaiSvcName) throws Exception {

		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("eaiSvcName", eaiSvcName);
		// 전체 목록수 얻기
		int totalCount = dao.selectPopListCount(paramMap);

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

		List<Map<String, Object>> list = dao.selectPopList(paramMap);
		HashMap<String, Object> map = new HashMap<>();

		map.put("totalCount", totalCount);
		map.put("list", list);

		return map;
	}

	public List<HashMap<String, Object>> uploadFull(String data[][], HttpServletRequest request, String sheetName)
			throws Throwable {
		int row = data.length;
		int col = 0;

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

		if (row < 4 || col <= 0) {
			String msg = "[Company upload] Invalid array size : row=" + row + " ,col=" + col;
			logger.error(msg);
			throw new Exception(msg);
		}
		ArraySheet sheet = new ArraySheet(row, col);
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

		String result = "O";
		for (int r = 0; r < row; r++) {
			for (int c = 0; c < col; c++) {
				sheet.setString(r, c, data[r][c]);
			}
			if (r != 0) {
				HashMap resMap = new HashMap();
				if (data[r][0] != null && "".equals(data[r][0])) {
					String message = "Success";
					if (data[r][ROW_COM_CD].equals("")) {
						message = (r + 1) + "행 > 업체코드는 필수항목입니다";
						logger.error(message);
						resMap.put("MESSAGE", message);
						resMap.put("RESULT", "X");
						list.add(resMap);
						continue;
					} else if (data[r][ROW_COM_NAME].equals("")) {
						message = (r + 1) + "행 > 업체명은 필수항목입니다";
						logger.error(message);
						resMap.put("MESSAGE", message);
						resMap.put("RESULT", "X");
						list.add(resMap);
						continue;
					} else if (data[r][ROW_APP_CD].equals("")) {
						message = (r + 1) + "행 > 어플리케이션코드는 필수항목입니다";
						logger.error(message);
						resMap.put("MESSAGE", message);
						resMap.put("RESULT", "X");
						list.add(resMap);
						continue;
					} else if (data[r][ROW_BIZ_KEY].equals("")) {
						message = (r + 1) + "행 > 업무구분코드는  필수항목입니다";
						logger.error(message);
						resMap.put("MESSAGE", message);
						resMap.put("RESULT", "X");
						list.add(resMap);
						continue;
					} else if (data[r][ROW_COM_PSN_NAME].equals("")) {
						message = (r + 1) + "행 > 업체전산담당자는 필수항목입니다";
						logger.error(message);
						resMap.put("MESSAGE", message);
						resMap.put("RESULT", "X");
						list.add(resMap);
						continue;
					} else if (data[r][ROW_COM_PSN_PHONE].equals("")) {
						message = (r + 1) + "행 > 업체전산담당자 연락처는 필수항목입니다";
						logger.error(message);
						resMap.put("MESSAGE", message);
						resMap.put("RESULT", "X");
						list.add(resMap);
						continue;
					}
					HashMap<String, Object> dataMap = new HashMap<>();
					dataMap.put("groupCoCd", data[r][0]);
					dataMap.put("companyCode", data[r][1]);
					dataMap.put("appCode", data[r][2]);
					dataMap.put("bzwkDstcode", data[r][3]);

					HashMap paramMap = new HashMap();

					paramMap.put("searchCompanyCode", data[r][1]);
					paramMap.put("searchAppCode", data[r][2]);
					paramMap.put("searchBzwkDstcode", data[r][3]);
					int chkNum = dao.selectListCount(paramMap);
					if (chkNum > 0) {
						dao.delete(dataMap);
						message = "업체코드 : " + data[r][1] + " 중복 (덮어쓰기됨)";
					}

					dataMap.put("bzwkName", data[r][4]);
					dataMap.put("companyName", data[r][5]);
					dataMap.put("conNetInstiCode", data[r][6]);
					dataMap.put("conNetInstiCodeName", data[r][7]);
					dataMap.put("onlineYn", data[r][8]);
					dataMap.put("companyItContactName", data[r][9]);
					dataMap.put("companyItContactTelNo", data[r][10]);
					dataMap.put("bzwkContactName", data[r][11]);
					dataMap.put("bzwkContactPerson", data[r][12]);
					dataMap.put("itContactPointName", data[r][13]);
					dataMap.put("itContactPointPerson1", data[r][14]);
					dataMap.put("itContactPointPerson2", data[r][15]);
					dao.insert(dataMap);

					resMap.put("MESSAGE", message);
					resMap.put("COMPANYCODE", data[r][1]);
					resMap.put("APPCODE", data[r][2]);
					resMap.put("BZWKDSTCODE", data[r][3]);
					resMap.put("BZWKNAME", data[r][4]);
					resMap.put("COMPANYNAME", data[r][5]);
					resMap.put("CONNETINSTICODENAME", data[r][6]);
					resMap.put("RESULT", result);

					list.add(resMap);
				}
			}
		}
		return list;
	}

}
