package shop.alien.job.second;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.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.second.SecondUserCredit;
import shop.alien.entity.second.SecondUserCreditRecord;
import shop.alien.entity.store.*;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.util.type.LifeNoticeUtil;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.LifeUserViolationMapper;
import shop.alien.mapper.second.SecondUserCreditMapper;
import shop.alien.mapper.second.SecondUserCreditRecordMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class AiUserViolationJob {

    private final RestTemplate restTemplate;
    private final LifeUserViolationMapper lifeUserViolationMapper;

    private final LifeUserMapper lifeUserMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;
    private final SecondUserCreditMapper secondUserCreditMapper;
    private final SecondUserCreditRecordMapper secondUserCreditRecordMapper;

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

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

    @Value("${third-party-login.base-url}")
    private String loginUrl;

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

    @XxlJob("getAiUserViolationResult")
    public R<String> getAiUserViolationResult() {
        String accessToken = fetchAiServiceToken();
        if (!StringUtils.hasText(accessToken)) {
            return R.fail("调用AI举报用户辅助系统 登录接口失败");
        }
        return getAiUserViolationCheck(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> getAiUserViolationCheck(String accessToken) {


        HttpHeaders analyzeHeaders = new HttpHeaders();
        analyzeHeaders.setContentType(MediaType.APPLICATION_JSON);
        analyzeHeaders.set("Authorization", "Bearer " + accessToken);
        // 查询所有状态为处理中的申诉
        List<LifeUserViolation> pendingTasks = lifeUserViolationMapper.selectList(
                new QueryWrapper<LifeUserViolation>()
                        .eq("processing_status", "0")
                        .isNotNull("ai_task_id")
        );

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

            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("AI举报用户审核提交成功, 返回: {}", analyzeBody);

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

                    if (dataJsonObj == null) {
                        log.error("AI举报用户审核返回数据为空");
                        R.fail("AI举报用户审核返回数据为空");
                        continue;
                    }

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

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

                    if (dataJsonObj.getString("status").equals("completed")) {
                        if (dataJsonObj.getString("is_valid").equals("true")) {
                            aiTask.setProcessingStatus("1");
                            aiTask.setReportResult(dataJsonObj.getString("decision_reason"));
                        } else {
                            aiTask.setProcessingStatus("2");
                            aiTask.setReportResult(dataJsonObj.getString("decision_reason"));
                        }
                        aiTask.setProcessingTime(new Date());
                    }

                    // 发送通知
                    LifeNotice lifeMessage = new LifeNotice();
                    LifeUser lifeUser = lifeUserMapper.selectById(task.getReportingUserId());
                    lifeMessage.setReceiverId("user_" + lifeUser.getUserPhone());
                    String text = "您的举报用户结果为" + (aiTask.getProcessingStatus().equals("1") ? "违规" : "未违规");

//                    if ("1".equals(aiTask.getProcessingStatus())) {
//                        SecondUserCredit secondUserCredit = new SecondUserCredit();
//                        LambdaQueryWrapper<SecondUserCredit> queryWrapper = new LambdaQueryWrapper<>();
//                        queryWrapper.eq(SecondUserCredit::getUserId, lifeUser.getId());
//                        secondUserCredit.setUserId(lifeUser.getId());
//                        SecondUserCredit secondUserCredit1 = secondUserCreditMapper.selectOne(queryWrapper);
//                        secondUserCredit.setUserPoints(secondUserCredit1.getUserPoints() - 50);
//
//                        SecondUserCreditRecord record = new SecondUserCreditRecord();
//                        record.setUserId(lifeUser.getId());
//                        record.setPoints(-50);
//                        record.setPointsType(5);
//                        record.setCurrentScoreCount(secondUserCredit.getUserPoints());
//                        secondUserCreditRecordMapper.insert(record);
//                    }

                    com.alibaba.fastjson.JSONObject lifeMessagejson = new com.alibaba.fastjson.JSONObject();
                    lifeMessagejson.put("title", "平台已受理");
                    lifeMessagejson.put("message", text);
                    lifeMessage.setContext(lifeMessagejson.toJSONString());
                    lifeMessage.setTitle("举报通知");
                    lifeMessage.setBusinessId(task.getId());
                    lifeMessage.setSenderId("system");
                    lifeMessage.setIsRead(0);
                    lifeMessage.setNoticeType(1);
                    lifeNoticeUtil.fillUserTypeAndRefId(lifeMessage);
                    lifeNoticeMapper.insert(lifeMessage);

                    QueryWrapper<LifeUserViolation> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("ai_task_id", taskId);
                    LifeUserViolation lifeUserViolation = lifeUserViolationMapper.selectOne(queryWrapper);
                    if (lifeUserViolation == null) {
                        log.error("AI举报用户不存在");
                        R.fail("AI举报用户不存在");
                        continue;
                    }
                    lifeUserViolationMapper.update(aiTask, queryWrapper);

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

    private String buildCompletedUrl(String recordId) {
        String baseUrl = aiUserViolationCheckUrl;
        if (!StringUtils.hasText(baseUrl)) {
            throw new IllegalStateException("ai举报用户接口地址未配置");
        }
        if (baseUrl.endsWith("/")) {
            baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
        }
        // 构建新的URL格式: /api/v1/audit_task/getResult?task_id={recordId}
        return baseUrl + "?task_id=" + recordId;
    }
}
