package shop.alien.second.util;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreCommentAppeal;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
@RefreshScope
public class AiTaskUtils {

    private final RestTemplate restTemplate;

//    @Value("${third-party-login.base-url:http://192.168.2.250:9000/ai/user-auth-core/api/v1/auth/login}")
//    private String loginUrl = "http://192.168.2.250:9000/ai/user-auth-core/api/v1/auth/login";

    @Value("${third-party-user-name-admin.base-url:UdUser}")
    private String userName;

    @Value("${third-party-pass-word.base-url:123456}")
    private String passWord;


    @Value("${third-party-login.base-url:http://192.168.2.250:9100/ai/user-auth-core/api/v1/auth/login}")
    private String loginUrl;

    @Value("${audit.auditTaskUrl:http://192.168.2.250:9100/ai/auto-review/api/v1/audit_task/product}")
    private String auditTaskUrl;
//    private String auditTaskUrl = "http://192.168.2.250:9000/ai/auto-review/api/v1/audit_task/product";


    private String auditTaskResultUrl = "http://192.168.2.250:9000/ai/task-core/api/v1/audit_task/getResult";

    /**
     * 登录 AI 服务，获取 token
     *
     * @return accessToken
     */
    public String getAccessToken() {
        log.info("登录Ai服务获取token...{}", loginUrl);
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("username", userName);
        formData.add("password", passWord);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

        ResponseEntity<String> response;
        try {
            log.info("请求Ai服务登录接口===================>");
            response = restTemplate.postForEntity(loginUrl, requestEntity, String.class);
        } catch (Exception e) {
            log.error("请求AI服务登录接口失败", e);
            return null;
        }

        if (response != null && response.getStatusCode() == HttpStatus.OK) {
            String body = response.getBody();
            log.info("请求Ai服务登录成功 postForEntity.getBody()\t{}", body);
            if (StringUtils.hasText(body)) {
                JSONObject jsonObject = JSONObject.parseObject(body);
                if (jsonObject != null) {
                    JSONObject dataJson = jsonObject.getJSONObject("data");
                    if (dataJson != null) {
                        return dataJson.getString("access_token");
                    }
                }
            }
            log.warn("AI服务登录响应解析失败 body: {}", body);
            return null;
        }

        log.error("请求AI服务 登录接口失败 http状态：{}", response != null ? response.getStatusCode() : null);
        return null;
    }


    /**
     * 调用AI服务创建任务
     *
     * @return accessToken
     */
    public String createTask(String accessToken, String text, List<String> img_urls) {
        log.info("创建Ai服务任务...{}", auditTaskUrl);

        HttpHeaders analyzeHeaders = new HttpHeaders();
        analyzeHeaders.setContentType(MediaType.APPLICATION_JSON);
        analyzeHeaders.set("Authorization", "Bearer " + accessToken);

        Map<String, Object> analyzeRequest = new HashedMap<>();
        analyzeRequest.put("text", StringUtils.hasText(text) ? text : "");
        analyzeRequest.put("img_urls", img_urls);

        HttpEntity<Map<String, Object>> analyzeEntity = new HttpEntity<>(analyzeRequest, analyzeHeaders);

        ResponseEntity<String> analyzeResp = null;
        try {
            analyzeResp = restTemplate.postForEntity(auditTaskUrl, analyzeEntity, String.class);
        } catch (org.springframework.web.client.HttpServerErrorException.ServiceUnavailable e) {
            log.error("调用提交商品审核任务接口返回503 Service Unavailable错误: {}", e.getResponseBodyAsString());
            return  null;
        } catch (Exception e) {
            log.error("调用提交商品审核任务接口异常", e);
            return  null;
        }

        if (analyzeResp != null && analyzeResp.getStatusCodeValue() == 200) {
            String analyzeBody = analyzeResp.getBody();
            log.info("提交商品审核任务提交成功, 返回: {}", analyzeBody);

            JSONObject analyzeJson = JSONObject.parseObject(analyzeBody);
            JSONObject dataJsonObj = analyzeJson.getJSONObject("data");

            if (dataJsonObj == null) {
                log.error("提交商品审核任务返回数据为空");
                R.fail("提交商品审核任务返回数据为空");
                return  null;
            }

            // 获取record_id用于后续查询
            String taskId = dataJsonObj.getString("task_id");
            if (taskId == null) {
                log.error("提交商品审核任务返回record_id为空");
                R.fail("提交商品审核任务返回record_id为空");
                return  null;
            }
            return taskId;
        } else {
            if (analyzeResp != null) {
                log.error("调用提交商品审核任务接口失败, http状态: {}", analyzeResp.getStatusCode());
                R.fail("调用提交商品审核任务接口失败, http状态: " + analyzeResp.getStatusCode());
                return  null;
            }
        }
        return  null;
    }
}
