package sgc.portal.as.as0103.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;

import sgc.portal.as.as0103.dto.TcsSearchCodeVo;
import sgc.portal.as.as0103.dto.TcsSearchDeftCustsignVo;
import sgc.portal.as.as0103.dto.TcsSearchDeftElpsVo;
import sgc.portal.as.as0103.dto.TcsSearchDeftVo;
import sgc.portal.as.as0103.dto.TcsSearchSiteDongHsnoVo;
import sgc.portal.as.as0103.dto.TcsSearchSiteVo;
import sgc.portal.as.as0103.dto.TcsSearchVo;
import sgc.portal.as.as0103.model.MoPushhistVo;
import sgc.portal.as.as0103.model.SmComCovendChrgrVo;
import sgc.portal.as.as0103.model.SmComCovendVo;
import sgc.portal.as.as0103.model.TcsCodeCovendChrgrVo;
import sgc.portal.as.as0103.model.TcsCodeVo;
import sgc.portal.as.as0103.model.TcsDeftCustsignVo;
import sgc.portal.as.as0103.model.TcsDeftElpsVo;
import sgc.portal.as.as0103.model.TcsDeftStatusVo;
import sgc.portal.as.as0103.model.TcsDeftVo;
import sgc.portal.as.as0103.model.TcsSiteVo;
import sgc.portal.as.as0103.persistence.AS01030001UMapper;
import sgc.portal.com.sym.user.model.UserDetails;

/**
 * 협력업체 하자 확인 및 처리 관련 서비스
 * 
 * @author 5364
 * @since 2022-08-11
 */
@Service
public class AS01030001UService {

	/**
	 * 협력업체 하자 확인 및 처리 관련 Mapper
	 */
	private final AS01030001UMapper mapper;

	/**
	 * 
	 * @param mapper
	 */
	public AS01030001UService(AS01030001UMapper mapper) {
		this.mapper = mapper;
	}

	/**
	 * 하자) 고객서명 리스트
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftCustsignVo selectTcsDeftCustsignView(TcsSearchDeftCustsignVo vo) {
		return mapper.selectTcsDeftCustsignView(vo);
	}

	/**
	 * 하자) 고객서명 업데이트
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftCustsignVo updateTcsDeftCustsign(TcsSearchDeftCustsignVo vo) {
		TcsDeftCustsignVo oldSign = this.selectTcsDeftCustsignView(vo);
		if (oldSign == null) {
			mapper.insertTcsDeftCustsign(vo);
		} else {
			mapper.updateTcsDeftCustsign(vo);
		}
		return this.selectTcsDeftCustsignView(vo);
	}

	/**
	 * 하자) 하자처리경과 리스트
	 * 
	 * @param vo
	 * @return
	 */
	public List<TcsDeftElpsVo> selectTcsDeftElpsList(TcsSearchDeftElpsVo vo) {
		return mapper.selectTcsDeftElpsList(vo);
	}

	/**
	 * 하자) 하자처리경과 보기
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftElpsVo selectTcsDeftElpsView(TcsSearchDeftElpsVo vo) {
		return mapper.selectTcsDeftElpsView(vo);
	}

	/**
	 * 하자) 하자접수처리 리스트
	 * 
	 * @param vo
	 * @return
	 */
	public List<TcsDeftVo> selectTcsDeftList(TcsSearchDeftVo vo) {
		return mapper.selectTcsDeftList(vo);
	}

	/**
	 * 하자) 하자접수처리 보기
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftVo selectTcsDeftView(TcsSearchDeftVo vo) {
		return mapper.selectTcsDeftView(vo);
	}

	/**
	 * 하자) 하자접수처리 보기
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftStatusVo selectTcsDeftStatus(TcsSearchDeftVo vo) {
		TcsDeftStatusVo result = mapper.selectTcsDeftStatus(vo);
		if (result == null) {
			result = new TcsDeftStatusVo();
			result.setEmgGbA(0);
			result.setEmgGbB(0);
			result.setEmgGbC(0);
			result.setEmgGbD(0);
			result.setEmgGbE(0);
			result.setStatusA(0);
			result.setStatusB(0);
			result.setStatusC(0);
			result.setStatusD(0);
			result.setStatusZ(0);
			result.setStatusX(0);
		}
		result.setChartRate( Math.round((double) (result.getStatusD() + result.getStatusZ() + result.getStatusX())/ (double) Math.max(result.getStatusA() + result.getStatusB() + result.getStatusC() + result.getStatusD() + result.getStatusZ(), 1)*100));
		result.setStatusRecv(result.getStatusB());
		result.setStatusDone(result.getStatusD());
		result.setStatusClose(result.getStatusD() + result.getStatusZ() + result.getStatusX());
		result.setStatusTotal(result.getStatusA() + result.getStatusB() + result.getStatusC() + result.getStatusD() + result.getStatusZ() + result.getStatusX());
		result.setStatusUnDone(result.getStatusA() + result.getStatusB() + result.getStatusC());
		result.setStatusEnd(result.getStatusZ());
		return result;
	}

	/**
	 * 하자) 하자대상현장 리스트 팝업
	 * 
	 * @param vo
	 * @return
	 */
	public List<TcsSiteVo> selectSiteAllPop(TcsSearchSiteVo vo) {
		return mapper.selectSiteAllPop(vo);
	}

	/**
	 * 하자) 현장의 동호수 리스트
	 * 
	 * @param vo
	 * @return
	 */
	public List<TcsCodeVo> getSiteDongHsno(TcsSearchVo searchVo, String siteCd, String dong) {
		TcsSearchSiteDongHsnoVo vo = new TcsSearchSiteDongHsnoVo();
		vo.setCmpnCd(searchVo.getCmpnCd());
		vo.setSiteCd(siteCd);
		vo.setDong(dong);
		if ("".equals(dong)) {
			return mapper.selectSiteDongList(vo);
		} else {
			return mapper.selectSiteHsnoList(vo);
		}
	}

	/**
	 * 하자) 협력업체 담당자 리스트
	 * 
	 * @param vo
	 * @return
	 */
	public List<TcsCodeCovendChrgrVo> getCovendLbprCodeList(TcsSearchVo searchVo, String covendId) {
		searchVo.setQuery(covendId);
		return mapper.getCovendLbprCodeList(searchVo);
	}

	/**
	 * 하자) 회사정보 코드 리스트
	 * 
	 * @return
	 */
	public List<TcsCodeVo> selectCodeCmpnList() {
		return mapper.selectCodeCmpnList();
	}

	/**
	 * 하자) 현장정보 코드 리스트
	 * 
	 * @return
	 */
	public List<TcsCodeVo> selectCodeSiteList(TcsSearchVo vo) {
		return mapper.selectCodeSiteList(vo);
	}

	/**
	 * 하자) 하자 코드 정보 리스트
	 * 
	 * @param vo
	 * @return
	 */
	public List<TcsCodeVo> selectCodeList(TcsSearchCodeVo vo) {
		return mapper.selectCodeList(vo);
	}

	/**
	 * 하자) 현장 담당 업제 정보
	 * 
	 * @param vo
	 * @return
	 */
	public List<SmComCovendVo> selectVenList(TcsSearchVo vo) {
		List<SmComCovendVo> directList = mapper.selectDirectCovendList(vo);
		List<SmComCovendVo> siteList = mapper.selectSiteCovendList(vo);
		List<SmComCovendVo> unionList = new ArrayList<>();
		if (directList != null && directList.size() > 0) {
			for (SmComCovendVo item : directList) {
				unionList.add(item);
			}
		}
		if (siteList != null && siteList.size() > 0) {
			for (SmComCovendVo item : siteList) {
				unionList.add(item);
			}
		}

		return unionList;
	}

	/**
	 * 하자) 하자 코드 정보 리스트
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftVo updateTcsDeftAttach(TcsSearchDeftVo vo) {
		mapper.updateTcsDeftAttach(vo);
		return selectTcsDeftView(vo);
	}

	/**
	 * 하자) 하자 처리 정보 생성/수정
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftElpsVo updateTcsDeftElps(TcsSearchDeftElpsVo vo) {
		if (vo.getPrcgElpsSeq() == null || vo.getPrcgElpsSeq() == "0" || "".equals(vo.getPrcgElpsSeq())) {
			mapper.insertTcsDeftElps(vo);
		} else {
			mapper.updateTcsDeftElps(vo);
		}
		mapper.updateTcsDeftSeq(vo);
		return selectTcsDeftElpsView(vo);
	}

	/**
	 * 하자) 임직원 - 하자 처리 정보 생성/수정
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftVo updateTcsDeft(TcsSearchDeftVo vo) {
		mapper.updateTcsDeft(vo);
		return selectTcsDeftView(vo);
	}

	/**
	 * 임시 저장된 메세징 서비스
	 */
	private FirebaseMessaging _firebaseMessaging = null;

	/**
	 * 메세징 서비스 가져오기
	 * 
	 * @return
	 * @throws IOException
	 */
	private FirebaseMessaging getFirebaseMessaging() throws IOException {
		if (this._firebaseMessaging == null) {
			List<FirebaseApp> firebaseApps = FirebaseApp.getApps();
			if (firebaseApps != null && !firebaseApps.isEmpty()) {
				for (FirebaseApp app : firebaseApps) {
					if (app.getName().equals(FirebaseApp.DEFAULT_APP_NAME)) {
						this._firebaseMessaging = FirebaseMessaging.getInstance(app);
					}
				}
			}
			if (this._firebaseMessaging == null) {
				InputStream serviceAccount = new ClassPathResource("sgc-portal-firebase-adminsdk-75r2g-c9a2ba20fd.json")
						.getInputStream();
				@SuppressWarnings("deprecation")
				FirebaseOptions options = new FirebaseOptions.Builder()
						.setCredentials(GoogleCredentials.fromStream(serviceAccount)).build();
				FirebaseApp app = FirebaseApp.initializeApp(options);
				this._firebaseMessaging = FirebaseMessaging.getInstance(app);
			}
		}
		return this._firebaseMessaging;
	}

	/**
	 * 푸시 메세지 전송
	 * 
	 * @param note
	 * @param token
	 * @return
	 * @throws FirebaseMessagingException
	 * @throws IOException
	 */
	public String sendNotification(MoPushhistVo note) throws FirebaseMessagingException, IOException {
		Notification notification = Notification.builder().setTitle(note.getPushTitle()).setBody(note.getPushContents())
				.setImage(note.getPushImage()).build();
		Message message = Message.builder().setToken(note.getPushToken()).setNotification(notification)
				.putAllData(note.getPushData() != null ? note.getPushData() : new HashMap<String, String>()).build();
		return this.getFirebaseMessaging().send(message);
	}

	/**
	 * 하자) 임직원 - 하자작업지시 PUSH 전송
	 * 
	 * @param vo
	 * @return
	 * @throws IOException
	 * @throws FirebaseMessagingException
	 */
	public MoPushhistVo sendTcsDeftPush(MoPushhistVo vo) {
		if (vo.getPushSeq() != null && !"".equals(vo.getPushSeq())) {
			mapper.insertTcsDeftPush(vo);
			if (vo.getPushToken() != null && !"".equals(vo.getPushToken())) {
				String pushErrmsg = "";
				try {
					pushErrmsg = this.sendNotification(vo);
				} catch (FirebaseMessagingException | IOException e) {
					pushErrmsg = e.getMessage();
				}
				if (!"".equals(pushErrmsg)) {
					vo.setPushErrmsg(pushErrmsg);
					if (pushErrmsg.startsWith("projects")) {
						vo.setPushStatus("Y");
					} else {
						vo.setPushStatus("N");
					}
					mapper.updateTcsDeftPush(vo);
				}
			}
		}
		return vo;
	}

	/**
	 * 하자) 임직원 - 하자작업지시 SMS/PUSH 전송
	 * 
	 * @param vo
	 * @return
	 */
	public TcsDeftVo sendTcsDeftSmsPush(TcsSearchDeftVo vo) {
		TcsDeftVo pushSmsInfo = mapper.selectTcsDeftSmsPushView(vo);
		if (pushSmsInfo != null) {
			vo.setCmpnCd(pushSmsInfo.getCmpnCd());
			String vendrLbprCrryTel = pushSmsInfo.getVendrLbprCrryTel();
			if (vendrLbprCrryTel != null && !"".equals(vendrLbprCrryTel) && vendrLbprCrryTel.startsWith("01")) {
				vo.setVendrLbprCrryTel(vendrLbprCrryTel);
				mapper.insertElpsSms(vo);
			}
			String vendrLbprPushSeq = pushSmsInfo.getVendrLbprPushSeq();
			if (vendrLbprPushSeq != null && !"".equals(vendrLbprPushSeq)) {
				MoPushhistVo pushhistVo = new MoPushhistVo();
				pushhistVo.setPushContents(vo.getSmsContents());
				pushhistVo.setPushTitle(vo.getSmsTitle());
				pushhistVo.setPushSeq(vendrLbprPushSeq);
				pushhistVo.setPushType("DEFT");
				sendTcsDeftPush(pushhistVo);
				if ("Y".equals(pushhistVo.getPushStatus())) {
					vo.setWorkWkiPushYn("Y");
				}
			}
			if (vo.getWorkWkiSmsYn() == null ) {
				vo.setWorkWkiSmsYn("N");
			}
			if (vo.getWorkWkiPushYn() == null ) {
				vo.setWorkWkiPushYn("N");
			}
			mapper.updateElpsSmsPush(vo);
			
			TcsSearchDeftElpsVo deftElpsVo = new TcsSearchDeftElpsVo();
			deftElpsVo.setCmpnCd(vo.getCmpnCd());
			deftElpsVo.setLginId(vo.getLginId());
			deftElpsVo.setPgprNm(vo.getPgprNm());
			deftElpsVo.setPrcgPrEndTm(null);
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.KOREA);
			Date nowDate = new Date();
			Calendar calTmp = Calendar.getInstance();
			calTmp.setTime(nowDate);
			String prcgPrStrtDt = dateFormat.format(nowDate);
			StringBuffer prcgPrStrtTm = new StringBuffer();
			int hour = calTmp.get(Calendar.HOUR_OF_DAY);
			int minute = calTmp.get(Calendar.MINUTE);
			if (hour >= 20) {
				prcgPrStrtTm.append("2000");
			} else if (hour < 7) {
				prcgPrStrtTm.append("0700");
			} else {
				if (hour < 10) {
					prcgPrStrtTm.append("0" + hour);
				} else {
					prcgPrStrtTm.append("" + hour);
				}
				if (minute >= 30) {
					prcgPrStrtTm.append("30");
				} else {
					prcgPrStrtTm.append("00");
				}
			}
			deftElpsVo.setPrcgPrStrtDt(prcgPrStrtDt);
			deftElpsVo.setPrcgPrStrtTm(prcgPrStrtTm.toString());
			deftElpsVo.setRmkCn(vo.getSmsContents());
			deftElpsVo.setDeftNo(vo.getDeftNo());
			deftElpsVo.setCovendId(vo.getCovendId());
			deftElpsVo.setSiteCd(vo.getSiteCd());
			mapper.insertTcsDeftElpsSms(deftElpsVo);
			
			return selectTcsDeftView(vo);
		} else {
			return pushSmsInfo;
		}
	}

	/**
	 * 하자) 협력업체 대표 현장 가져오기
	 * 
	 * @param vo
	 * @return
	 */
	public UserDetails getUserDetails(UserDetails vo) {
		SmComCovendChrgrVo result = null;
		if (vo.getCovendId() != null && !"".equals(vo.getCovendId())) {
			result = mapper.selectConvendChrgrView(vo);
		} else {
			result = mapper.selectProtalView(vo);
		}
		if (result != null) {
			vo.setConnSiteCd(result.getFnlConnSiteCd());
			vo.setPushUseYn(result.getPushUseYn());
			vo.setPushKey(result.getPushKey());
		} else {
			vo.setConnSiteCd("");
			vo.setPushUseYn("N");
			vo.setPushKey("");
		}
		return vo;
	}

	/**
	 * 하자) 협력업체 대표 현장 업데이트
	 * 
	 * @param vo
	 * @return
	 */
	public UserDetails setUserDetails(UserDetails vo) {
		SmComCovendChrgrVo result = null;
		if (vo.getCovendId() != null && !"".equals(vo.getCovendId())) {
			result = mapper.selectConvendChrgrView(vo);
		} else {
			result = mapper.selectProtalView(vo);
		}
		if (vo.getCovendId() != null && !"".equals(vo.getCovendId())) {
			if ((vo.getConnSiteCd() != null && !"".equals(vo.getConnSiteCd())
					&& !vo.getConnSiteCd().equals(result.getFnlConnSiteCd()))
					|| (vo.getPushUseYn() != null && !"".equals(vo.getPushUseYn())
							&& !vo.getPushUseYn().equals(result.getPushUseYn()))) {
				mapper.updateConvendChrgr(vo);
			}
		}
		if (vo.getPushKey() != null && !"".equals(vo.getPushKey()) && !vo.getPushKey().equals(result.getPushKey())) {
			mapper.insertPushKey(vo);
			mapper.updatePushKey(vo);
		}
		return vo;
	}

}