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.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xxl.job.core.context.XxlJobHelper;
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.client.ClientHttpRequestInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import shop.alien.entity.result.R;
import shop.alien.entity.second.SecondGoodsRecord;
import shop.alien.entity.second.SecondRiskControlRecord;
import shop.alien.entity.store.*;
import shop.alien.mapper.*;
import shop.alien.mapper.second.SecondGoodsRecordMapper;
import shop.alien.mapper.second.SecondRiskControlRecordMapper;
import shop.alien.util.common.Constants;
import shop.alien.util.type.LifeNoticeUtil;

import java.net.SocketException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Lhaibo
 * @date 2025/11/28
 * @desc: xxl-job
 * AI调用审核任务
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
//@RestController
//@RequestMapping("/job")
//@RequiredArgsConstructor
public class AiCheckXxlJob {

    // 添加RestTemplate用于HTTP调用
    private final RestTemplate restTemplate;

    private final LifeUserViolationMapper lifeUserViolationMapper;

    private final StoreDictionaryMapper storeDictionaryMapper;

    private final LifeUserMapper lifeUserMapper;

    private final SecondGoodsRecordMapper secondGoodsRecordMapper;

    private final SecondRiskControlRecordMapper secondRiskControlRecordMapper;

    @Autowired
    private final StoreImgMapper storeImgMapper;

    // 第三方接口地址 登录接口URL
    @Value("${third-party-login.base-url}")
    private String loginUrl;

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

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

    // 第三方接口地址 登录接口URL
    @Value("${third-party-goods.base-url}")
    private String goodsUrl;

    // 第三方接口地址 登录接口URL
    @Value("${third-party-goodsresult.base-url}")
    private String goodsResultUrl;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    /**
     * AI自动审核任务处理器
     * <p>
     * 定时任务方法，用于批量处理用户违规举报记录，通过AI接口进行自动审核。
     * 主要流程：
     * 1. 查询所有待处理的用户违规记录
     * 2. 遍历每条记录，组装审核请求数据
     * 3. 调用AI审核接口进行自动审核（当前代码中已准备请求体，待实现接口调用）
     * </p>
     *
     * @author Lhaibo
     * @date 2025/11/28
     * @since 1.0.0
     */
    @XxlJob("aiCheckJobHandler")
//    @PostMapping("/aiCheckJobHandler")
    public void aiCheckJobHandler() {
        log.info("开始执行AI自动审核任务");

        try {
            log.info("登录Ai服务获取token..." + loginUrl);
            //构建请求参数
            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("username", userName);    // 表单字段 1：用户名
            formData.add("password", passWord);    // 表单字段 2：密码

            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
            ResponseEntity<String> postForEntity = null;
            try {
                postForEntity = restTemplate.postForEntity(loginUrl, requestEntity, String.class);
            } catch (Exception e) {
                log.error("类:PostMethod 方法:post", e);
            }

            if (postForEntity != null) {
                if (postForEntity.getStatusCodeValue() == 200) {
                    log.info("请求Ai服务登录成功 postForEntity.getBody()\t" + postForEntity.getBody());
                    String responseBody = postForEntity.getBody();
                    JSONObject jsonObject = JSONObject.parseObject(responseBody);
                    JSONObject dataJson = jsonObject.getJSONObject("data");
                    String accessToken = dataJson.getString("access_token");
                    // 查询所有待处理的用户违规记录
                    List<LifeUserViolation> lifeUserViolations = lifeUserViolationMapper.selectList(new LambdaQueryWrapper<LifeUserViolation>()
                            .eq(LifeUserViolation::getReportContextType, "4")
                            .eq(LifeUserViolation::getProcessingStatus, "0"));

                    // 遍历每条违规记录，组装AI审核请求数据
                    for (LifeUserViolation violation : lifeUserViolations) {
                        // 初始化请求体Map
                        Map<String, Object> requestBody = new HashMap<>();

                        // 设置投诉记录ID
                        requestBody.put("complaint_id", violation.getId().toString());

                        // 查询投诉类型字典信息
                        StoreDictionary storeDictionary = storeDictionaryMapper.selectOne(new LambdaQueryWrapper<StoreDictionary>()
                                .eq(StoreDictionary::getDictId, violation.getDictId()).eq(StoreDictionary::getTypeName, violation.getDictType()));
                        String complaint_type = "";
                        if (storeDictionary != null) {
                            // 设置投诉类型
                            complaint_type = storeDictionary.getDictDetail();
                        }
                        requestBody.put("complaint_type", complaint_type);
                        // 设置举报人信息
                        requestBody.put("reporter_user_id", violation.getReportingUserId());
                        requestBody.put("reporter_user_type", violation.getReportingUserType());
                        requestBody.put("reporter_info", lifeUserMapper.selectById(violation.getReportingUserId()));

                        // 查询被举报的商品记录
                        SecondGoodsRecord secondGoodsRecord = secondGoodsRecordMapper.selectById(violation.getBusinessId());
                        if (secondGoodsRecord != null) {
                            // 设置被举报人信息
                            requestBody.put("reported_user_id", secondGoodsRecord.getUserId().toString());
                            requestBody.put("reported_user_type", "");
                            requestBody.put("reported_info", lifeUserMapper.selectById(secondGoodsRecord.getUserId()));
                            requestBody.put("product_name", secondGoodsRecord.getTitle());
                        }
                        // 设置商品相关信息
                        requestBody.put("product_info", secondGoodsRecord);
                        requestBody.put("product_id", violation.getGoodsId().toString());

                        // 设置投诉文本内容
                        requestBody.put("complaint_text", violation.getOtherReasonContent());

                        LambdaQueryWrapper<StoreImg> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(StoreImg::getStoreId, violation.getId());
                        wrapper.eq(StoreImg::getImgType, Constants.ImageType.SECOND_HAND_REPORT);
                        List<StoreImg> imgList = storeImgMapper.selectList(wrapper);

                        // 将 imgList 中的 ImgUrl 提取为 String[] 数组
                        String[] imgUrls = imgList.stream()
                                .map(StoreImg::getImgUrl)
                                .toArray(String[]::new);

                        // 设置证据图片数组
                        requestBody.put("evidence_images", imgUrls);

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

                        System.out.println(requestBody);
                        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);
                        ResponseEntity<String> response = null;
                        try {
                            response = restTemplate.postForEntity(goodsUrl, request, String.class);
                            log.info("AI自动审核结果：{}", response.getBody());
                            if (response.getStatusCodeValue() != 200) {
                                throw new RuntimeException("AI门店审核接口调用失败 http状态：" + response.getStatusCode());
                            }
                            if (StringUtils.isNotEmpty(response.getBody())) {
                                com.alibaba.fastjson.JSONObject taskObject = com.alibaba.fastjson.JSONObject.parseObject(response.getBody());
                                if (taskObject.getInteger("code") == 200) {
                                    com.alibaba.fastjson.JSONObject data = taskObject.getJSONObject("data");
                                    if (data != null) {
                                        String taskId = data.getString("task_id");
                                        violation.setAiTaskId(taskId);
                                        lifeUserViolationMapper.updateById(violation);
                                    }
                                }
                            }
                        } catch (ResourceAccessException e) {
                            if (e.getCause() instanceof SocketException) {
                                log.error("AI自动审核请求网络异常，连接被中断: {}", e.getMessage());
                            } else {
                                log.error("AI自动审核请求资源访问异常", e);
                            }
                        } catch (Exception e) {
                            log.error("AI自动审核请求异常", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("AI自动审核任务执行异常", e);
        }

        log.info("AI自动审核任务执行完成");
    }

    @XxlJob("aiCheckJobHandlerResult")
    public void aiCheckJobHandlerResult() {
        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> postForEntity = null;
        try {
            log.info("请求Ai服务登录接口===================>");
            postForEntity = restTemplate.postForEntity(loginUrl, requestEntity, String.class);
        } catch (Exception e) {
            log.error("请求AI服务登录接口失败", e);
        }

        if (postForEntity != null) {
            if (postForEntity.getStatusCodeValue() == 200) {
                log.info("请求Ai服务登录成功 postForEntity.getBody()\t" + postForEntity.getBody());
                String responseBody = postForEntity.getBody();
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                JSONObject dataJson = jsonObject.getJSONObject("data");
                String accessToken = dataJson.getString("access_token");

                // 查询所有待处理的用户违规记录
                List<LifeUserViolation> lifeUserViolations = lifeUserViolationMapper.selectList(new LambdaQueryWrapper<LifeUserViolation>()
                        .eq(LifeUserViolation::getReportContextType, "4")
                        .eq(LifeUserViolation::getProcessingStatus, "0"));

                for (LifeUserViolation violation : lifeUserViolations) {
                    // 初始化请求体Map
                    Map<String, Object> requestBody = new HashMap<>();



                    if (violation.getAiTaskId() == null || violation.getAiTaskId() == "") {
                        continue;
                    }

                    // 设置投诉记录ID
                    requestBody.put("task_id", violation.getAiTaskId());
                    HttpHeaders aiHeaders = new HttpHeaders();
                    aiHeaders.setContentType(MediaType.APPLICATION_JSON);
                    aiHeaders.set("Authorization", "Bearer " + accessToken);

                    System.out.println(requestBody);
                    HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);
                    ResponseEntity<String> response = null;
                    try {
                        response = restTemplate.postForEntity(goodsResultUrl, request, String.class);
                        if (response.getStatusCodeValue() != 200) {
                            throw new RuntimeException("AI门店审核接口调用失败 http状态：" + response.getStatusCode());
                        }
                        if (StringUtils.isNotEmpty(response.getBody())) {
                            com.alibaba.fastjson.JSONObject taskObject = com.alibaba.fastjson.JSONObject.parseObject(response.getBody());
                            if (taskObject.getInteger("code") == 200) {
                                com.alibaba.fastjson.JSONObject data = taskObject.getJSONObject("data");
                                if (data != null) {
                                    String status = data.getString("status");
                                    if (!"processing".equals(status)) {
                                        boolean isValid = data.getBoolean("is_valid");
                                        violation.setReportResult(data.getString("matched_type"));
                                        violation.setProcessingStatus(isValid ? "1" : "2");
                                        violation.setProcessingTime(new Date());
                                        lifeUserViolationMapper.updateById(violation);

                                        // 发送通知
                                        LifeNotice lifeMessage = new LifeNotice();
                                        LifeUser lifeUser = lifeUserMapper.selectById(violation.getReportingUserId());
                                        lifeMessage.setReceiverId("user_" + lifeUser.getUserPhone());
                                        String text = "您的举报商品结果为" + (isValid ? "违规" : "未违规");
                                        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(violation.getId());
                                        lifeMessage.setSenderId("system");
                                        lifeMessage.setIsRead(0);
                                        lifeMessage.setNoticeType(1);
                                        lifeNoticeUtil.fillUserTypeAndRefId(lifeMessage);
                                        lifeNoticeMapper.insert(lifeMessage);
                                    }
                                }
                            }
                        }
                    } catch (ResourceAccessException e) {
                        if (e.getCause() instanceof SocketException) {
                            log.error("AI自动审核结果查询网络异常，连接被中断: {}", e.getMessage());
                        } else {
                            log.error("AI自动审核结果查询资源访问异常", e);
                        }
                    } catch (Exception e) {
                        log.error("AI自动审核结果查询异常", e);
                    }

                }
            }
        }

    }

    /**
     * 二手商品风控记录审核任务
     * <p>
     * 定时查询风控记录表中待处理的数据（risk_status = 0），
     * 预留后续风控审核/处理逻辑（如调用 AI 服务、通知运营等）。
     * </p>
     */
    @XxlJob("riskControlCheckJobHandler")
    public void riskControlCheckJobHandler() {
        log.info("开始执行二手商品风控记录审核任务");

        try {
            // 查询风控记录表中待处理的记录（risk_status = 0）
            List<SecondRiskControlRecord> riskControlRecords = secondRiskControlRecordMapper.selectList(
                    new LambdaQueryWrapper<SecondRiskControlRecord>()
                            .eq(SecondRiskControlRecord::getRiskStatus, 0)
            );

            log.info("本次待处理风控记录数量：{}", riskControlRecords.size());

            // 按 ruleType 和 businessId 进行分组，生成新的嵌套结构
            List<Map<String, List<SecondRiskControlRecord>>> groupedByRuleAndBusiness =
                    (List<Map<String, List<SecondRiskControlRecord>>>) riskControlRecords.stream()
                            .collect(Collectors.groupingBy(
                                    SecondRiskControlRecord::getRuleType,
                                    Collectors.groupingBy(SecondRiskControlRecord::getBusinessId)
                            )).values();

            for (Map<String, List<SecondRiskControlRecord>> byRuleAndBusiness : groupedByRuleAndBusiness) {


            }
        } catch (Exception e) {
            log.error("二手商品风控记录审核任务执行异常", e);
        }

        log.info("二手商品风控记录审核任务执行完成");
    }
}
