package shop.alien.second.util;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.second.SecondGoods;
import shop.alien.entity.second.vo.SecondUserViolationVo;
import shop.alien.entity.store.LifeMessage;
import shop.alien.entity.store.LifeUserViolation;
import shop.alien.entity.store.vo.LifeUserVo;
import shop.alien.mapper.LifeMessageMapper;
import shop.alien.util.type.LifeMessageUtil;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.LifeUserViolationMapper;
import shop.alien.mapper.second.SecondGoodsMapper;
import shop.alien.util.type.LifeMessageUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

    private final RestTemplate restTemplate;
    private final LifeUserMapper lifeUserMapper;
    private final LifeMessageMapper lifeMessageMapper;
    private final LifeMessageUtil lifeMessageUtil;
    private final SecondGoodsMapper secondGoodsMapper;

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

    @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-ai.reportuser-review.base-url}")
    private String userComplaintRecordUrl;

    @Value("${third-party-ai.report-review.base-url}")
    private String goodsComplaintRecordUrl;

    private final LifeUserViolationMapper lifeUserViolationMapper;

    /**
     * 登录 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, LifeUserViolation lifeuserViolation) {
        log.info("创建Ai服务任务...{}", userComplaintRecordUrl);

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

        Map<String, Object> analyzeRequest = new HashedMap<>();
        // 对应参数举报类型
        if (1 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "用户违规");
        } else if (2 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "色情低俗");
        } else if (3 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "违法违规");
        } else if (4 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "谩骂嘲讽、煽动对立");
        } else if (5 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "涉嫌诈骗");
        } else if (6 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "人身攻击");
        } else if (7 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "种族歧视");
        } else if (8 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "政治敏感");
        } else if (9 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "虚假、不实内容");
        } else if (10 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "违反公德秩序");
        } else if (11 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "危害人身安全");
        } else if (12 == lifeuserViolation.getDictId()){
            analyzeRequest.put("complaint_type", "网络暴力");
        } else {
            analyzeRequest.put("complaint_type", "其他");
        }
        // 设置举报补充
        analyzeRequest.put("complaint_text",lifeuserViolation.getOtherReasonContent());
        // 举报凭证
        analyzeRequest.put("evidence_urls",((SecondUserViolationVo) lifeuserViolation).getImgUrl());
//        analyzeRequest.put("id", lifeuserViolation.getId());
//        analyzeRequest.put("type", lifeuserViolation.getReportContextType());

        //举报人
        String reporterUserId = lifeuserViolation.getReportingUserId();
        //被举报人
        String reportedUserId = lifeuserViolation.getReportedUserId();

        //通过双方userId查询用户信息,查出用户电话,
        QueryWrapper<LifeUserVo> reporterUserQueryWrapper = new QueryWrapper<>();
        reporterUserQueryWrapper.eq("id", reporterUserId);
        LifeUserVo reporterUserById = lifeUserMapper.getUserById(reporterUserQueryWrapper);
        QueryWrapper<LifeUserVo> reportedUserQueryWrapper = new QueryWrapper<>();
        reportedUserQueryWrapper.eq("id", reportedUserId);
        LifeUserVo reportedUserById = lifeUserMapper.getUserById(reportedUserQueryWrapper);
        // 用user_去拼接,查询life_message表,获取双方两天记录
        String userReporterUserById = "user_" + reporterUserById.getUserPhone();
        String userReportedUserById = "user_" + reportedUserById.getUserPhone();

        //将双方两天记录拼接成text,传入analyzeRequest
        // 获取双方最近的聊天记录
        List<LifeMessage> chatMessages = getRecentChatMessages(userReporterUserById, userReportedUserById);

        // 将聊天记录转换为文本格式
        String text = convertMessagesToText(chatMessages,userReporterUserById);
        analyzeRequest.put("chat_records", StringUtils.hasText(text) ? text : "");
        analyzeRequest.put("reporter_user_id", reporterUserId);
        analyzeRequest.put("reported_user_id", reportedUserId);

//        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(userComplaintRecordUrl, 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;
            }
          /*  // 解析AI审核结果
            String processingStatus = JSONObject.parseObject(analyzeResp.getBody()).getJSONObject("data").getJSONObject("result").getString("processing_status");
            boolean success = "1".equals(processingStatus);

            LifeUserViolation lifeUserViolation = lifeUserViolationMapper.selectById(lifeuserViolation.getId());

            // 更新举报处理状态
            lifeUserViolation.setProcessingStatus(processingStatus);
            lifeUserViolation.setProcessingTime(new Date());
            lifeUserViolationMapper.updateById(lifeUserViolation);*/
            return taskId;
        } else {
            if (analyzeResp != null) {
                log.error("调用提交用户投诉审核任务接口失败, http状态: {}", analyzeResp.getStatusCode());
                R.fail("调用提交用户投诉审核任务接口失败, http状态: " + analyzeResp.getStatusCode());
                return  null;
            }
        }
        return  null;
    }

    /**
     * 调用AI服务创建商品举报审核任务（参数格式：complaint_id、complaint_type、reporter/reported 信息、product 信息、complaint_text、evidence_images）
     *
     * @param accessToken 访问令牌
     * @param lifeuserViolation 举报信息（商品举报时可为 SecondUserViolationVo，含 imgUrl）
     * @return task_id 任务ID，失败返回 null
     */
    public String createGoodsTask(String accessToken, SecondUserViolationVo lifeuserViolation) {
        log.info("创建Ai服务商品举报任务...{}", goodsComplaintRecordUrl);

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

        Map<String, Object> analyzeRequest = new HashedMap<>();
        // complaint_id
        analyzeRequest.put("complaint_id", lifeuserViolation.getId().toString());

        // complaint_type：举报商品类型 dictId 1-8（见图表）
        Integer dictId = lifeuserViolation.getDictId() != null ? lifeuserViolation.getDictId() : 8;
        if (1 == dictId) {
            analyzeRequest.put("complaint_type", "禁限售商品");
        } else if (2 == dictId) {
            analyzeRequest.put("complaint_type", "政治敏感类");
        } else if (3 == dictId) {
            analyzeRequest.put("complaint_type", "有害信息");
        } else if (4 == dictId) {
            analyzeRequest.put("complaint_type", "假货/盗版");
        } else if (5 == dictId) {
            analyzeRequest.put("complaint_type", "盗用他人图片");
        } else if (6 == dictId) {
            analyzeRequest.put("complaint_type", "危害用户产权");
        } else if (7 == dictId) {
            analyzeRequest.put("complaint_type", "危害国家与社会安全");
        } else {
            analyzeRequest.put("complaint_type", "其他");
        }

        String reporterUserId = lifeuserViolation.getReportingUserId() != null ? lifeuserViolation.getReportingUserId() : "";
        LifeUserVo reporterUser = null;
        if (StringUtils.hasText(reporterUserId)) {
            QueryWrapper<LifeUserVo> reporterQ = new QueryWrapper<>();
            reporterQ.eq("id", reporterUserId);
            reporterUser = lifeUserMapper.getUserById(reporterQ);
        }
        // 被举报人：通过 businessId 查 second_goods_record(id=businessId) 得到 userId，再查 life_user
        String reportedUserId = lifeuserViolation.getReportedUserId() != null ? lifeuserViolation.getReportedUserId() : "";
        LifeUserVo reportedUser = null;
        Integer businessId = lifeuserViolation.getBusinessId();
        SecondGoods secondGoods = secondGoodsMapper.selectById(businessId);
        if (secondGoods != null && secondGoods.getUserId() != null) {
            reportedUserId = String.valueOf(secondGoods.getUserId());
            QueryWrapper<LifeUserVo> reportedQ = new QueryWrapper<>();
            reportedQ.eq("id", secondGoods.getUserId());
            reportedUser = lifeUserMapper.getUserById(reportedQ);
        }

        // 用user_去拼接,查询life_message表,获取双方两天记录
        analyzeRequest.put("reporter_user_id", "user_" + reporterUser.getUserPhone());
        analyzeRequest.put("reporter_user_type", "buyer");
        analyzeRequest.put("reported_user_id", "user_" + reportedUser.getUserPhone());
        analyzeRequest.put("reported_user_type", "seller");

        // reporter_info
        Map<String, Object> reporterInfo = new HashedMap<>();
        QueryWrapper<LifeUserVo> reporterQ = new QueryWrapper<>();
        reporterQ.eq("id", reporterUserId);
        reporterInfo.put("name", reporterUser != null && StringUtils.hasText(reporterUser.getUserName()) ? reporterUser.getUserName() : "");
        reporterInfo.put("phone", reporterUser != null && StringUtils.hasText(reporterUser.getUserPhone()) ? maskPhone(reporterUser.getUserPhone()) : "");
        analyzeRequest.put("reporter_info", reporterInfo);

        // reported_info（二手无店铺，用被举报人姓名/电话填充或填空）
        Map<String, Object> reportedInfo = new HashedMap<>();
        reportedInfo.put("shop_name", reportedUser != null && StringUtils.hasText(reportedUser.getUserName()) ? reportedUser.getUserName() : "");
        reportedInfo.put("shop_id", reportedUserId);
        analyzeRequest.put("reported_info", reportedInfo);

        // product_id / product_name / product_info
        analyzeRequest.put("product_id", secondGoods.getId().toString());
        analyzeRequest.put("product_name", secondGoods.getTitle());
        Map<String, Object> productInfo = new HashedMap<>();
        productInfo.put("price", secondGoods.getPrice());
        productInfo.put("category", secondGoods.getLabel());
        productInfo.put("sku", secondGoods.getLabel());
        analyzeRequest.put("product_info", productInfo);

        analyzeRequest.put("complaint_text", StringUtils.hasText(lifeuserViolation.getOtherReasonContent()) ? lifeuserViolation.getOtherReasonContent() : "");

        analyzeRequest.put("evidence_images", lifeuserViolation.getImgUrl());

        analyzeRequest.put("id", lifeuserViolation.getId());
        analyzeRequest.put("type", lifeuserViolation.getReportContextType());

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

        ResponseEntity<String> analyzeResp = null;
        try {
            analyzeResp = restTemplate.postForEntity(goodsComplaintRecordUrl, 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("提交商品举报审核任务返回数据为空");
                return null;
            }

            String taskId = dataJsonObj.getString("task_id");
            // 解析AI审核结果
            String processingStatus = JSONObject.parseObject(analyzeResp.getBody()).getJSONObject("data").getJSONObject("result").getString("processing_status");
            boolean success = "1".equals(processingStatus);

            LifeUserViolation lifeUserViolation = lifeUserViolationMapper.selectById(lifeuserViolation.getId());

            // 更新举报处理状态
            lifeUserViolation.setProcessingStatus(processingStatus);
            lifeUserViolation.setProcessingTime(new Date());
            lifeUserViolationMapper.updateById(lifeUserViolation);
            if (taskId == null) {
                log.error("提交商品举报审核任务返回task_id为空");
                return null;
            }
            return taskId;
        } else {
            if (analyzeResp != null) {
                log.error("调用提交商品举报审核任务接口失败, http状态: {}", analyzeResp.getStatusCode());
                return null;
            }
        }
        return null;
    }

    private static String maskPhone(String phone) {
        if (phone == null || phone.length() < 8) {
            return phone != null ? phone : "";
        }
        return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
    }

    /**
     * 获取双方用户的最近聊天记录
     * @param userReporterUserById 举报人ID
     * @param userReportedUserById 被举报人ID
     * @return 聊天记录列表
     */
    public List<LifeMessage> getRecentChatMessages(String userReporterUserById, String userReportedUserById) {
        // 构建查询条件
        LambdaQueryWrapper<LifeMessage> queryWrapper = new LambdaQueryWrapper<>();
        lifeMessageUtil.applyConversationQuery(queryWrapper, userReporterUserById, userReportedUserById);
        queryWrapper.orderByDesc(LifeMessage::getCreatedTime);
        queryWrapper.last("LIMIT 50");
        return lifeMessageMapper.selectList(queryWrapper);
    }

    /**
     * 将聊天消息列表转换为文本格式
     * @param messages 聊天消息列表
     * @return 格式化后的文本字符串
     */
    private String convertMessagesToText(List<LifeMessage> messages, String userReporterUserById) {
        if (messages == null || messages.isEmpty()) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        // 按时间顺序排列（因为数据库查询是倒序的，这里需要重新排序）
        for (int i = messages.size() - 1; i >= 0; i--) {
            LifeMessage message = messages.get(i);
            // 格式：[时间] 发送者ID: 消息内容
            sb.append("[").append(formatTime(message.getCreatedTime())).append("] ");
            if( message.getSenderId().equals(userReporterUserById) ) {
                sb.append("0: ");
            } else {
                sb.append("1: ");
            }
            sb.append(message.getContent()).append("\n");
        }

        return sb.toString().trim();
    }

    /**
     * 格式化时间显示
     * @param date 时间
     * @return 格式化后的时间字符串
     */
    private String formatTime(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
}
