package org.ta.pddserver.utils;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.ta.pddserver.model.enums.IdentityErrorType;

import java.nio.charset.StandardCharsets;

@Slf4j
public class UniPassUtil {

    /**
     * 向韩国UNIPASS查询通关信息有效性
     *
     * @param persEcm   通关符号
     * @param pltxNm    姓名
     * @param cralTelNo 电话号码
     * @param custPsno  邮编
     * @return 结果信息
     */

    private static RestTemplate restTemplate = null;

    public static UniPassPersonalClearanceCheckResult queryUniPassPersonalClearanceInfo(String persEcm, String pltxNm, String cralTelNo, String custPsno) {
        String url = String.format("https://unipass.customs.go.kr:38010/ext/rest/persEcmQry/retrievePersEcm?crkyCn=g240g274x016o063l080g030v2&persEcm=%s&pltxNm=%s&cralTelno=%s&custPsno=%s", persEcm, pltxNm, cralTelNo, custPsno);
        log.info("url:" + url);
        UniPassPersonalClearanceCheckResult result = new UniPassPersonalClearanceCheckResult();
        result.setSuccess(false);
        try {
            ResponseEntity<String> resp = new RestTemplate().getForEntity(url, String.class);
            result.setMsg("查询验证失败！");
            if (resp.getStatusCode().is2xxSuccessful()) {
                XmlMapper xmlMapper = new XmlMapper();

                String body = resp.getBody();
                String newBody = new String(body.getBytes(StandardCharsets.ISO_8859_1), "UTF-8");
//                log.info("body:{}", newBody);
                PersEcmQryRtnVo respObject = xmlMapper.readValue(newBody, PersEcmQryRtnVo.class);
                if (respObject != null) {
                    if (respObject.getTCnt() == 1) {
                        result.setSuccess(true);
                        result.setMsg("有效期：" + respObject.getValtPridStrtDt() + "-" + respObject.getValtPridStrtDt());
                    } else {
                        String msg = "";
                        for (PersEcmQryRtnErrInfoVo vo : respObject.getPersEcmQryRtnErrInfoVoList()) {
                            if (!msg.isEmpty()) {
                                msg += "\n";
                            }
                            msg += vo.analyzeErrorMessage();
                        }
                        result.setSuccess(false);
                        result.setMsg(msg);
                    }
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 向韩国UNIPASS查询通关信息有效性
     *
     * @param persEcm   通关符号
     * @param pltxNm    姓名
     * @param cralTelNo 电话号码
     * @return 结果信息
     */
    public static IdentityErrorType queryUniPassPersonalClearanceInfo(String persEcm, String pltxNm, String cralTelNo) {
        if (restTemplate == null) {
//            HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
//            httpRequestFactory.setConnectionRequestTimeout(2*1000);
//            httpRequestFactory.setConnectTimeout(2*1000);
//            httpRequestFactory.setReadTimeout(2*1000);
            restTemplate = new RestTemplate();
        }
        String url = String.format("https://unipass.customs.go.kr:38010/ext/rest/persEcmQry/retrievePersEcm?crkyCn=g240g274x016o063l080g030v2&persEcm=%s&pltxNm=%s&cralTelno=%s", persEcm, pltxNm, cralTelNo);
        log.info("url:" + url);
//        UniPassPersonalClearanceCheckResult result = new UniPassPersonalClearanceCheckResult();
//        result.setSuccess(false);
        try {
            ResponseEntity<String> resp = restTemplate.getForEntity(url, String.class);
            int retry = 0;
//            while (!resp.getStatusCode().is2xxSuccessful() & retry < 5) {
//                retry++;
//                resp = new RestTemplate().getForEntity(url, String.class);
//            }
//            result.setMsg("查询验证失败！");
            if (resp.getStatusCode().is2xxSuccessful()) {
                XmlMapper xmlMapper = new XmlMapper();

                String body = resp.getBody();
                String newBody = new String(body.getBytes(StandardCharsets.ISO_8859_1), "UTF-8");
                log.info("body:{}", newBody);
                PersEcmQryRtnVo respObject = xmlMapper.readValue(newBody, PersEcmQryRtnVo.class);
                if (respObject != null) {
                    if (respObject.getTCnt() == 1) {
                        return IdentityErrorType.Correct;
//                        result.setSuccess(true);
//                        result.setMsg("有效期：" + respObject.getValtPridStrtDt() + "-" + respObject.getValtPridStrtDt());
                    } else {
                        String msg = respObject.getNtceInfo();
//                        String msg = "";
                        for (PersEcmQryRtnErrInfoVo vo : respObject.getPersEcmQryRtnErrInfoVoList()) {
                            if (!msg.isEmpty()) {
                                msg += "\n";
                            }
                            msg += vo.analyzeErrorMessage();
                        }
//                        result.setSuccess(false);
//                        result.setMsg(msg);
                        if (msg.indexOf("납세의무자 개인통관고유부호가 존재하지 않습니다") >= 0 || msg.indexOf("현재 사용중이 아닌 개인통관고유부호 입니다") >= 0) {
                            return IdentityErrorType.CodeUnused;
                        }
                        if (msg.indexOf("납세의무자 전화번호가 일치하지 않습니다") >= 0 || msg.indexOf("개인통관고유부호 정보변경(휴대전화번호 인증)후 신고하시기 바랍니다") >= 0) {
                            return IdentityErrorType.CodeTelephoneInconsistency;
                        }
                        if (msg.indexOf("입력하신 납세의무자명") >= 0 || msg.indexOf("개인통관고유부호의 성명과 일치하지 않습니다") >= 0) {
                            return IdentityErrorType.CodeNameInconsistency;
                        }
                    }
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return IdentityErrorType.UnknownWrong;
    }

    @Data
    public static class UniPassPersonalClearanceCheckResult {
        boolean success;
        String msg;
    }

}
