package com.nokia.sms.service;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nokia.sms.vo.QueryBlackDTO;
import com.nokia.sms.vo.QueryDTO;
import com.nokia.sms.vo.QueryResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class QueryService {
    public static final String URL = "http://10.17.182.24:8082/task/queryBlack";

    public QueryResp query(QueryDTO params) {
        RestTemplate restTemplate = new RestTemplate();
        QueryResp r = new QueryResp();
        r.setQuerySuccess(false);
        r.setQueryMessage("查询失败");
        try {
            // 查询黑名单
            String responseString = restTemplate.postForObject(URL, new QueryBlackDTO(params.getPhone()), String.class);
            log.info("查询黑名单响应: {}", responseString);
            if (responseString == null) {
                log.error("查询黑名单接口响应为空");
                return r;
            }

            JsonObject responseJsonObject = JsonParser.parseString(responseString).getAsJsonObject();
            JsonElement retStatusJsonElement = responseJsonObject.get("retStatus");
            JsonElement retDataJsonElement = responseJsonObject.get("retData");
            if (retStatusJsonElement == null
                    || retDataJsonElement == null
                    || !"success".equals(retStatusJsonElement.getAsString())) {
                log.error("查询黑名单接口响应异常: {}", responseString);
                return r;
            }

            // 不在黑
            if (!retDataJsonElement.isJsonArray()) {
                r.setQueryMessage("当前不在黑");
                return r;
            }

            JsonArray retDataJsonArray = retDataJsonElement.getAsJsonArray();
            if (retDataJsonArray.isEmpty()) {
                r.setQueryMessage("当前不在黑");
                return r;
            }

            // 在黑
            JsonObject data = retDataJsonArray.get(0).getAsJsonObject();
            QueryResp.QueryResultDTO dto = new QueryResp.QueryResultDTO();
            boolean allowToDel = "1".equals(data.get("advice").getAsString());
            dto.setReason(data.get("reason").getAsString());
            dto.setStartTime(data.get("startTime").getAsString());
            dto.setEndTime(data.get("endTime").getAsString());
            dto.setDescribe(data.get("reasonInfo").getAsString());
            dto.setAllowToDel(allowToDel);
            r.setQuerySuccess(true);
            r.setQueryMessage(allowToDel ? "当前在黑可解黑" : "当前在黑不可解黑");
            r.setQueryResult(dto);
        } catch (Exception e) {
            log.error("查询黑名单接口异常: {}", e.getMessage(), e);
        }

        return r;
    }
}
