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.*;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.mapper.*;
import shop.alien.store.config.WebSocketProcess;
import shop.alien.util.type.LifeNoticeUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
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}")
    private String aiReportReviewUrl;

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

    private final LifeNoticeUtil lifeNoticeUtil;
    private final WebSocketProcess webSocketProcess;
    private final LifeUserMapper lifeUserMapper;
    private final StoreUserMapper storeUserMapper;
    private final StoreCommentMapper storeCommentMapper;

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

            LifeUserViolation lifeUserViolation = lifeUserViolationMapper.selectById(reportId);

            // 更新举报处理状态
            lifeUserViolation.setProcessingStatus(processingStatus);
            lifeUserViolation.setProcessingTime(new Date());
            lifeUserViolationMapper.updateById(lifeUserViolation);

            // 如果举报成功删除对应数据，动态/评论
            if(success){
                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);
                }
            }

            // 发送AI审核结果通知（举报人 + 被举报人）
            sendReviewResultNotification(lifeUserViolation, success);
        }
    }

    /**
     * 发送AI审核结果通知给举报人和被举报人
     *
     * @param v       举报记录
     * @param success 审核是否通过
     */
    private void sendReviewResultNotification(LifeUserViolation v, boolean success) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat simpleDateFormats = new SimpleDateFormat("yyyy-MM-dd");
            String violationTime = simpleDateFormat.format(v.getCreatedTime());

            // 获取被举报人名称
            String reportedUserName = "";
            if (StringUtils.hasText(v.getReportedUserId())) {
                if ("1".equals(v.getReportedUserType())) {
                    StoreUser storeUser = storeUserMapper.selectById(v.getReportedUserId());
                    if (storeUser != null) reportedUserName = storeUser.getNickName();
                } else {
                    LifeUser lifeUser = lifeUserMapper.selectById(v.getReportedUserId());
                    if (lifeUser != null) reportedUserName = lifeUser.getUserName();
                }
            }

            // 获取被举报动态日期
            String dynamicsDate = simpleDateFormats.format(new Date());
            if (StringUtils.hasText(v.getDynamicsId())) {
                LifeUserDynamics dynamics = lifeUserDynamicsMapper.selectById(v.getDynamicsId());
                if (dynamics != null) dynamicsDate = simpleDateFormats.format(dynamics.getCreatedTime());
            }

            // 获取被举报评论日期
            String commonDate = simpleDateFormats.format(new Date());
            if (StringUtils.hasText(v.getCommentId())) {
                StoreComment storeComment = storeCommentMapper.selectById(v.getCommentId());
                if (storeComment != null) commonDate = simpleDateFormats.format(storeComment.getCreatedTime());
            }

            String message = "";
            String reportedMessage = "";
            String title = "";
            String reportContextType = v.getReportContextType();

            if (success) {
                // 审核通过
                switch (reportContextType) {
                    case "1":
                        message = "您在" + violationTime + "举报用户\u201C" + reportedUserName + "\u201D，涉嫌违法违规，经核实，确实存在违规行为，平台已将用户禁用，感谢您为此做出的贡献。";
                        title = "用户举报成功通知";
                        break;
                    case "2":
                        message = "您在" + violationTime + "举报用户\u201C" + reportedUserName + "\u201D在" + dynamicsDate + "发布的动态，涉嫌违法违规，经核实，确实存在违规行为，平台已将此动态下架，感谢您为此做出的贡献";
                        reportedMessage = "您在" + dynamicsDate + "发布的动态，经核实，确实存在违规行为，平台已将此动态下架，应用内的环境需要我们共同维护";
                        title = "动态举报成功通知";
                        break;
                    case "3":
                        message = "您在" + violationTime + "举报用户\u201C" + reportedUserName + "\u201D在" + commonDate + "发布的评论，涉嫌违法违规，经核实，确实存在违规行为，平台已将此评论下架，感谢您为此做出的贡献。";
                        reportedMessage = "您在" + commonDate + "发布的评论，经核实，确实存在违规行为，平台已将此评论下架，应用内的环境需要我们共同维护。";
                        title = "评论举报成功通知";
                        break;
                    default:
                        message = "您的举报经平台审核，确实存在违规行为，感谢您为此做出的贡献。";
                        title = "举报成功通知";
                        break;
                }
            } else {
                // 审核驳回
                switch (reportContextType) {
                    case "1":
                        message = "您在" + violationTime + "举报用户\u201C" + reportedUserName + "\u201D，涉嫌违法违规，经核实，不存在违规行为，感谢您为此做出的贡献。";
                        title = "用户举报失败通知";
                        break;
                    case "2":
                        message = "您在" + violationTime + "举报用户\u201C" + reportedUserName + "\u201D在" + dynamicsDate + "发布的动态，涉嫌违法违规，经核实，不存在违规行为，感谢您为此做出的贡献。";
                        title = "动态举报失败通知";
                        break;
                    case "3":
                        message = "您在" + violationTime + "举报用户\u201C" + reportedUserName + "\u201D在" + commonDate + "发布的评论，涉嫌违法违规，经核实，不存在违规行为，感谢您为此做出的贡献。";
                        title = "评论举报失败通知";
                        break;
                    default:
                        message = "您的举报经平台审核，不存在违规行为，感谢您为此做出的贡献。";
                        title = "举报失败通知";
                        break;
                }
            }

/*            // 发送通知给举报人
            String reporterPhoneId = getPhoneId(v.getReportingUserType(), v.getReportingUserId());
            if (StringUtils.hasText(reporterPhoneId)) {
                LifeNotice notice = new LifeNotice();
                notice.setSenderId("system");
                notice.setBusinessId(v.getId());
                notice.setTitle(title);
                notice.setNoticeType(1);
                notice.setIsRead(0);
                notice.setReceiverId(reporterPhoneId);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("message", message);
                notice.setContext(jsonObject.toJSONString());
                lifeNoticeUtil.fillUserTypeAndRefId(notice);
                lifeNoticeMapper.insert(notice);

                WebSocketVo websocketVo = new WebSocketVo();
                websocketVo.setSenderId("system");
                websocketVo.setReceiverId(reporterPhoneId);
                websocketVo.setCategory("notice");
                websocketVo.setNoticeType("1");
                websocketVo.setIsRead(0);
                websocketVo.setText(JSONObject.from(notice).toJSONString());
                webSocketProcess.sendMessage(reporterPhoneId, JSONObject.from(websocketVo).toJSONString());
                log.info("AI审核结果通知已发送给举报人，reportId={}, phoneId={}, success={}", v.getId(), reporterPhoneId, success);
            }*/

            // 发送通知给被举报人（仅审核通过且有被举报通知内容时）
            if (StringUtils.hasText(reportedMessage)) {
                String reportedPhoneId = getPhoneId(v.getReportedUserType(), v.getReportedUserId());
                if (StringUtils.hasText(reportedPhoneId)) {
                    LifeNotice reportedNotice = new LifeNotice();
                    reportedNotice.setSenderId("system");
                    reportedNotice.setBusinessId(v.getId());
                    reportedNotice.setTitle(title);
                    reportedNotice.setNoticeType(1);
                    reportedNotice.setIsRead(0);
                    reportedNotice.setReceiverId(reportedPhoneId);
                    JSONObject reportedJson = new JSONObject();
                    reportedJson.put("message", reportedMessage);
                    reportedNotice.setContext(reportedJson.toJSONString());
                    lifeNoticeUtil.fillUserTypeAndRefId(reportedNotice);
                    lifeNoticeMapper.insert(reportedNotice);

                    WebSocketVo reportedWsVo = new WebSocketVo();
                    reportedWsVo.setSenderId("system");
                    reportedWsVo.setReceiverId(reportedPhoneId);
                    reportedWsVo.setCategory("notice");
                    reportedWsVo.setNoticeType("1");
                    reportedWsVo.setIsRead(0);
                    reportedWsVo.setText(JSONObject.from(reportedNotice).toJSONString());
                    webSocketProcess.sendMessage(reportedPhoneId, JSONObject.from(reportedWsVo).toJSONString());
                    log.info("AI审核结果通知已发送给被举报人，reportId={}, phoneId={}", v.getId(), reportedPhoneId);
                }
            }
        } catch (Exception e) {
            log.error("AI审核结果通知发送失败，reportId={}, error={}", v.getId(), e.getMessage(), e);
        }
    }

    /**
     * 根据用户类型和用户ID获取通知接收ID（phoneId）
     *
     * @param userType 用户类型: "1"-商户, "2"-用户
     * @param userId   用户ID
     * @return phoneId，格式为 "store_{phone}" 或 "user_{phone}"
     */
    private String getPhoneId(String userType, String userId) {
        if ("1".equals(userType)) {
            StoreUser storeUser = storeUserMapper.selectById(userId);
            return storeUser != null ? "store_" + storeUser.getPhone() : null;
        } else {
            LifeUser lifeUser = lifeUserMapper.selectById(userId);
            return lifeUser != null ? "user_" + lifeUser.getUserPhone() : null;
        }
    }
}
