package shop.alien.job.second;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
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.second.SecondGoods;
import shop.alien.entity.store.SecondAiTask;
import shop.alien.entity.store.StoreComment;
import shop.alien.entity.store.StoreCommentAppeal;
import shop.alien.job.feign.SecondGoodsFeign;
import shop.alien.mapper.SecondAiTaskMapper;
import shop.alien.mapper.second.SecondGoodsMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class goodsCheckJob {

    private final RestTemplate restTemplate;

    private final SecondAiTaskMapper secondAiTaskMapper;
    private final SecondGoodsMapper secondGoodsMapper;

    private final SecondGoodsFeign secondGoodsFeign;

    private String loginUrl = "http://192.168.2.250:9000/ai/user-auth-core/api/v1/auth/login";

    private String goodsCheckUrl = "http://192.168.2.250:9000/ai/auto-review/api/v1/audit_task/getResult";

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

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

    @XxlJob("getAiGoodsCheckResult")
    public R<String> getAiGoodsCheckResult() {
        String accessToken = fetchAiServiceToken();
        if (!StringUtils.hasText(accessToken)) {
            return R.fail("调用差评申诉辅助系统 登录接口失败");
        }
        return getGoodsCheck(accessToken);
    }


    private String fetchAiServiceToken() {
        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);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(loginUrl, requestEntity, String.class);
            if (response != null && response.getStatusCodeValue() == 200 && response.getBody() != null) {
                JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                JSONObject dataJson = jsonObject.getJSONObject("data");
                return dataJson != null ? dataJson.getString("access_token") : null;
            }
            log.error("请求差评申诉辅助系统 登录接口失败 http状态：{}", response != null ? response.getStatusCode() : null);
        } catch (Exception e) {
            log.error("调用差评申诉辅助系统登录接口异常", e);
        }
        return null;
    }


    private R<String> getGoodsCheck(String accessToken) {


        HttpHeaders analyzeHeaders = new HttpHeaders();
        analyzeHeaders.setContentType(MediaType.APPLICATION_JSON);
        analyzeHeaders.set("Authorization", "Bearer " + accessToken);
        // 查询所有状态为处理中的申诉
        List<SecondAiTask> pendingTasks = secondAiTaskMapper.selectList(
                new QueryWrapper<SecondAiTask>()
                        .eq("status", "PROCESSING")
        );

        // 循环调用查询结果接口
        for (SecondAiTask task : pendingTasks) {
            String completedUrl = buildCompletedUrl(task.getTaskId());

            ResponseEntity<String> analyzeResp;

            RestTemplate restTemplateWithAuth = new RestTemplate();
            List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
            interceptors.add((request, body, execution) -> {
                request.getHeaders().set("Authorization", "Bearer " + accessToken);
                return execution.execute(request, body);
            });
            restTemplateWithAuth.setInterceptors(interceptors);

            ResponseEntity<String> response = null;

            try {
                analyzeResp = restTemplateWithAuth.getForEntity(completedUrl, String.class);

                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("商品审核返回数据为空");
                        continue;
                    }

                    // 获取task_id用于后续查询
                    String taskId = dataJsonObj.getString("task_id");
                    if (taskId == null) {
                        log.error("商品审核返回task_id为空");
                        R.fail("商品审核返回task_id为空");
                        continue;
                    }

                    SecondAiTask aiTask = new SecondAiTask();
                    aiTask.setTaskId(taskId);
                    if (dataJsonObj.getString("status").equals("pending")) {
                        R.fail("审核未结束");
                        continue;
                    }

                    if (dataJsonObj.getString("status").equals("done")) {
                        aiTask.setStatus("SUCCESS");
                    }

                    aiTask.setResult(dataJsonObj.toJSONString());

                    QueryWrapper<SecondGoods> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ai_task_id", taskId);
                    SecondGoods goods = secondGoodsMapper.selectOne(queryWrapper);
                    if (goods == null) {
                        log.error("商品不存在");
                        R.fail("商品不存在");
                        continue;
                    }
                    secondGoodsFeign.approveAndListGoods(goods);

                } else {
                    if (analyzeResp != null) {
                        log.error("调用商品审核接口失败, http状态: {}", analyzeResp.getStatusCode());
                        R.fail("调用商品审核接口失败, http状态: " + analyzeResp.getStatusCode());
                    }
                }
            } catch (Exception e) {
                log.error("调用差评申述查询结果接口异常", e);
            }
        }
        return R.success("调用商品审核结果接口完成");
    }


    private String buildCompletedUrl(String recordId) {
        String baseUrl = goodsCheckUrl;
        if (!StringUtils.hasText(baseUrl)) {
            throw new IllegalStateException("差评申述分析接口地址未配置");
        }
        if (baseUrl.endsWith("/")) {
            baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
        }
        // 构建新的URL格式: /api/v1/audit_task/getResult?task_id={recordId}
        return baseUrl + "?task_id=" + recordId;
    }
}
