package org.ta.pddserver.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.ta.pddserver.model.enums.IdentityErrorType;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WorldexUtil {

    private static final String URL = "https://api.worldex.kr";
    private static String token = "";
    private static Long timeout = 0L;

    public static JSONObject login() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("userName", "hjpddjy");
        map.put("password", "hjpddjy123");
        String resp = WorldexUtil.sendJsonPost("/api/user/signIn", map, null);
        log.info("resp = {}", resp);
        JSONObject json = JSONObject.parseObject(resp);
        if (json.getInteger("code") == 2000) {
            return json.getJSONObject("data");
        }
        return null;
    }

    public static IdentityErrorType verifyIdentity(String name, String phone, String code) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", name);
        map.put("mobile_phone_no", phone);
        map.put("customs_clearance_code", code);
        String token = WorldexUtil.getToken();
        String resp = WorldexUtil.sendJsonPost("/api/worldex/retrievePersEcm", map, token);
        log.info("resp = {}", resp);
        JSONObject json = JSONObject.parseObject(resp);
        if (json.getInteger("code") == 2000) {
            JSONObject data = json.getJSONObject("data");
            if (data.getInteger("tCnt").intValue() == 1) {
                return IdentityErrorType.Correct;
            }
            String errMsgCn = data.getJSONObject("persEcmQryRtnErrInfoVo").getString("errMsgCn");
            if (errMsgCn == null) {
                return IdentityErrorType.UnknownWrong;
            }
            if (errMsgCn.startsWith("입력하신 납세의무자명") && errMsgCn.contains("이 개인통관고유부호의 성명과 일치하지 않습니다")) {
                return IdentityErrorType.CodeNameInconsistency;
            }
            if (errMsgCn.startsWith("납세의무자 휴대전화번호가 일치하지 않습니다")) {
                return IdentityErrorType.CodeTelephoneInconsistency;
            }
            if (errMsgCn.startsWith("납세의무자 개인통관고유부호가 존재하지 않습니다")) {
                return IdentityErrorType.CodeUnused;
            }
            return IdentityErrorType.InformationInconsistency;
        }
        return null;
    }

    public static Boolean noticePddOrderOut(String orderCode) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderCode", orderCode);
        String token = WorldexUtil.getToken();
        String resp = WorldexUtil.sendJsonPost("/api/pdd/register", map, token);
        log.info("resp = {}", resp);
        JSONObject json = JSONObject.parseObject(resp);
        if (json.getInteger("code") == 2000) {
            return true;
        }
        return false;
    }

    private static String getToken() {
        long now = System.currentTimeMillis() / 1000 - 100;
        if (token.isEmpty() || timeout < now) {
            String newToken = WorldexUtil.requestToken();
            if (newToken != null) {
                token = newToken;
                timeout = now + 24 * 60 * 60;
            }
        }
        return token;
    }

    private static String requestToken() {
        JSONObject jsonObject = WorldexUtil.login();
        if (jsonObject != null) {
            String token = jsonObject.getString("token");
            log.info("token:{}", token);
            return token;
        }
        log.error("login failed");
        return "";
    }

    public static String sendJsonPost(String url, Object requestObj, String token) {
        // 自动序列化 requestObj 为 JSON，并设置 Content-Type: application/json
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Accept-Language", "zh-cn");
        httpHeaders.set("token", token);
        log.info("WORLDEX REQ:{}", JSONObject.toJSONString(requestObj));
        HttpEntity<Object> httpEntity = new HttpEntity<Object>(requestObj, httpHeaders);
        ResponseEntity<String> resp = restTemplate.exchange(URL + url, HttpMethod.POST, httpEntity, String.class);
        log.info("WORLDEX RESP:{}", resp.getBody());
//        ResponseEntity<String> resp = restTemplate.postForEntity(URL + url, requestObj, String.class, headers);
        return resp.getBody();
    }
}
