package shop.alien.store.util.ai;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import shop.alien.entity.store.LifeUserViolation;
import shop.alien.mapper.CommonCommentMapper;
import shop.alien.mapper.LifeUserDynamicsMapper;
import shop.alien.mapper.LifeUserViolationMapper;

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

/**
 * AI 举报审核（举报评论，举报动态）工具类
 *
 * @author system
 * @since 2025-01-XX
 */

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

    private final AiAuthTokenUtil aiAuthTokenUtil;
    private final RestTemplate restTemplate;

    @Value("${third-party-ai.report-review.base-url:http://124.93.18.180:9000/ai/auto-review/api/v1/merchant_dynamic_violation_audit_task/submit}")
    private String aiReportReviewUrl;

    private final LifeUserViolationMapper lifeUserViolationMapper;
    private final CommonCommentMapper commonCommentMapper;
    private final LifeUserDynamicsMapper  lifeUserDynamicsMapper;

    @Async("taskExecutor")
    public void reviewReport(Integer reportId, String reportType) {

        if(!StringUtils.hasText(reportId.toString())){
            throw new IllegalArgumentException("reportId 不能为空");
        }

        if(!StringUtils.hasText(reportType)){
            throw new IllegalArgumentException("reportType 不能为空");
        }


        // 1. 登录 AI 服务，获取 token
        String accessToken = aiAuthTokenUtil.getAccessToken();
        if(!StringUtils.hasText(accessToken)){
            throw new IllegalArgumentException("accessToken 不能为空");
        }

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("id", reportId);
        requestBody.put("type", reportType);
        // 构建请求头，添加Authorization
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + accessToken);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
        log.info("调用ai举报接口URL：{}，requestBody: {}", aiReportReviewUrl, requestBody);
        ResponseEntity<String> response = restTemplate.postForEntity(aiReportReviewUrl, request, String.class);

        if(response.getStatusCode().isError()){
            log.error("调用ai举报接口失败，URL：{}，requestBody: {}，response: {}", aiReportReviewUrl, requestBody, response);
        } else {
            // 如果举报成功删除对应数据，动态/评论
            boolean success = JSONObject.parseObject(response.getBody()).getJSONObject("data").getJSONObject("result").getString("processing_status").equals("1");
            if(success){
                LifeUserViolation lifeUserViolation = lifeUserViolationMapper.selectById(reportId);
                int i = 0;
                if(reportType.equals("2")){
                    // 删除动态
                    i = lifeUserDynamicsMapper.deleteById(lifeUserViolation.getDynamicsId());
                }
                if(reportType.equals("3")){
                    // 删除评论
                    i = commonCommentMapper.deleteById(lifeUserViolation.getBusinessId());
                }
                if( i == 0 ){
                    log.info("删除动态/评论失败，type:{},举报id:{}", reportType, reportId);
                }
            }
        }
    }
}
