package com.madeu.service.mobile.mobilephoneauth.impl;

import com.madeu.constants.Constants;
import com.madeu.dao.mobile.mobilephoneauth.MobilePhoneAuthSqlMapDAO;
import com.madeu.dao.mobile.mobilesms.MobileSmsSqlMapDAO;
import com.madeu.service.mobile.mobilephoneauth.MobilePhoneAuthService;
import com.madeu.util.ValidationCheckUtil;
import com.popbill.api.MessageService;
import com.popbill.api.PopbillException;
import com.popbill.api.message.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service("MobilePhoneAuthService")
public class MobilePhoneAuthServiceImpl implements MobilePhoneAuthService {
    @Autowired
    private MobilePhoneAuthSqlMapDAO mobilePhoneAuthSqlMapDAO;

    @Autowired
    private MobileSmsSqlMapDAO mobileSmsSqlMapDAO;

    /*Popbill*/
    @Autowired
    private MessageService messageService;

    @Value("${popbill.corp-num}")
    String corpNum;

    @Value("${popbill.user-id}")
    String userId;

    @Value("${popbill.sender-nm}")
    String senderName;

    @Value("${popbill.sender-phone-num}")
    String senderPhoneNumber;


    /**
     * 휴대폰 인증 확인
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectPhoneAuthCheck(HashMap<String, Object> paramMap) throws Exception {
        log.debug("MobilePhoneAuthServiceImpl selectPhoneAuthCheck START");

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

        log.debug("phoneNumber			: " + paramMap.get("phoneNumber"));
        log.debug("authNumber			: " + paramMap.get("authNumber"));

        try {
            boolean check = true;

            String phoneNumber = String.valueOf(paramMap.get("phoneNumber"));
            String authNumber = String.valueOf(paramMap.get("authNumber"));

            if (true != ValidationCheckUtil.emptyCheck(phoneNumber)) {
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc", "핸드폰 번호 정보가 없습니다.");
            }

            if (true != ValidationCheckUtil.emptyCheck(authNumber)) {
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc", "인증번호정보가 없습니다.");
            }

            if (check == true) {

                List<Map<String, Object>> listMap = mobilePhoneAuthSqlMapDAO.selectPhoneAuthCheck(paramMap);
                int cnt = Integer.parseInt(String.valueOf(listMap.get(0).get("successCount")));

                if(cnt>0) {
                    map.put("msgCode", Constants.OK);
                    map.put("msgDesc", "인증되었습니다.");
                }else {
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "인증번호가 다릅니다. 다시 입력해주세요.");
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

        log.debug("MobilePhoneAuthServiceImpl selectPhoneAuthCheck END");
        return map;
    }

    /**
     * 인증번호 등록(SMS 발송)
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = { Exception.class }, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> insertPhoneAuth(HashMap<String, Object> paramMap) throws Exception {

        log.debug("MobilePhoneAuthServiceImpl insertPhoneAuth START");

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

        log.debug("phoneNumber		: " + paramMap.get("phoneNumber"));
        log.debug("authType			: " + paramMap.get("authType"));

        try {
            boolean check = true;

            String phoneNumber = String.valueOf(paramMap.get("phoneNumber"));

            if (true != ValidationCheckUtil.emptyCheck(phoneNumber)) {
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc", "연락처 정보가 없습니다.");
            }

            // 최대 5회 발송확인.
//            if (check == true) {
//                List<Map<String, Object>> selectListPhoneAuthCountToday = mobilePhoneAuthSqlMapDAO.selectListPhoneAuthCountToday(paramMap);
//
//                int authSendCount = Integer.parseInt(String.valueOf(selectListPhoneAuthCountToday.get(0).get("totalCount")));
//
//                if (authSendCount >= 5) {
//                    check = false;
//                    map.put("msgCode", Constants.FAIL);
//                    map.put("msgDesc", "일일 인증횟수가 초과되었습니다.");
//                }
//            }

            if (check == true) {
                //SMS 환경설정 정보 호 출  :  팝빌회원 사업자번호, 팝빌회원 아이디, 발신자명, 발신번호, TEST(수신번호), 인증번호
                String receiverNumber = String.valueOf(paramMap.get("phoneNumber")); //테스트 후 paramMap.get("phoneNumber")로 변경;
                String tId = String.valueOf(System.currentTimeMillis());
                int authNumber		  = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;
                String message		  = "[인증번호:"+authNumber+"] 메이드유 인증번호입니다.";

                log.debug("corpNum      		:"+corpNum);
                log.debug("userId       		:"+userId);
                log.debug("senderName   		:"+senderName);
                log.debug("senderPhoneNumber   	:"+senderPhoneNumber);
                log.debug("receiverNumber   	:"+receiverNumber);
                log.debug("authNumber   		:"+authNumber);

                //SMS 등록
                HashMap<String, Object> insertSmsParamMap = new HashMap<String, Object>();
                insertSmsParamMap.put("id", ("S").concat(String.valueOf(System.currentTimeMillis())));
                insertSmsParamMap.put("senderPhoneNumber",senderPhoneNumber);
                insertSmsParamMap.put("receiverNumber",receiverNumber);
                insertSmsParamMap.put("content",message);
                insertSmsParamMap.put("state","R");
                insertSmsParamMap.put("popbillState","0");
                insertSmsParamMap.put("popbillResult","");
                insertSmsParamMap.put("regId",  paramMap.get("regId"));
                insertSmsParamMap.put("modId",  paramMap.get("modId"));
                insertSmsParamMap.put("tId",  tId);
                mobileSmsSqlMapDAO.insertSms(insertSmsParamMap);

                //PHONE AUTH 등록
                HashMap<String, Object> insertPhoneAuthParamMap = new HashMap<String, Object>();
                insertPhoneAuthParamMap.put("id", ("PA").concat(String.valueOf(System.currentTimeMillis())));
                insertPhoneAuthParamMap.put("muSmsId", insertSmsParamMap.get("id"));
                insertPhoneAuthParamMap.put("phoneNumber", paramMap.get("phoneNumber"));
                insertPhoneAuthParamMap.put("authType", paramMap.get("authType"));	//JN : 회원가입 ID: 아이디찾기, PW: 비밀번호 찾기, EM: 이메일 변경
                insertPhoneAuthParamMap.put("authNumber", authNumber);
                insertSmsParamMap.put("tId",  tId);
                mobilePhoneAuthSqlMapDAO.insertPhoneAuth(insertPhoneAuthParamMap);

                // sms 상태 수정
                HashMap<String, Object> smsStateParamMap = new HashMap<String, Object>();
                smsStateParamMap.put("muSmsId", insertSmsParamMap.get("id"));
                smsStateParamMap.put("state", "G");
                mobileSmsSqlMapDAO.updateSmsState(smsStateParamMap);


                Message[] messages = new Message[1];

                Message msg = new Message();
                msg.setSender(senderPhoneNumber);          //발신번호
                msg.setSenderName(senderName);        //발신자명
                msg.setReceiver(receiverNumber);      //수신번호
                msg.setReceiverName("");     		  //수신자명
                msg.setContent(message);              //메시지내용

                messages[0] = msg;

                String receiptNum = "";

                // 예약전송일시, null 처리시 즉시전송
                Date reserveDT = null;
                // 광고문자 전송여부
                Boolean adsYN = false;

                // 전송요청번호
                // 파트너가 전송 건에 대해 관리번호를 구성하여 관리하는 경우 사용.
                // 1~36자리로 구성. 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 팝빌 회원별로 중복되지 않도록 할당.
                String requestNum = "";

                try {
                    receiptNum = messageService.sendSMS(corpNum, senderPhoneNumber, message, messages, reserveDT, adsYN, userId, requestNum);

                    log.debug("receiptNum",receiptNum);

                } catch (PopbillException e) {
                    log.debug("오류 코드   :" + e.getCode());
                    log.debug("오류 메시지 :" + e.getMessage());
                }

                // sms 상태 수정
                smsStateParamMap = new HashMap<String, Object>();
                smsStateParamMap.put("muSmsId", insertSmsParamMap.get("id"));
                smsStateParamMap.put("state", "Y");
                mobileSmsSqlMapDAO.updateSmsState(smsStateParamMap);

                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "발송되었습니다.");
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

        log.debug("MobilePhoneAuthServiceImpl insertPhoneAuth END");
        return map;
    }

}
