package shop.alien.lawyer.controller;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import shop.alien.entity.store.CommentAppeal;
import shop.alien.entity.store.LawyerUserViolation;
import shop.alien.lawyer.service.AiUserAuditTaskService;
import shop.alien.lawyer.service.CommentAppealService;
import shop.alien.lawyer.service.LawyerUserViolationService;
import shop.alien.lawyer.util.ai.AiAuthTokenUtil;

import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = {"ai申诉"})
@CrossOrigin
@RestController
@RequestMapping("/aiAutoReview")
@RequiredArgsConstructor
@RefreshScope
public class AiAutoReview {

    private final AiAuthTokenUtil aiAuthTokenUtil;

    private final RestTemplate restTemplate;

    private final AiUserAuditTaskService aiUserAuditTaskService;

    private final LawyerUserViolationService lawyerUserViolationService;

    private final CommentAppealService commentAppealService;

    /**
     * 调用 AI 服务，获取申诉结果
     *
     * @return 申诉结果
     */
    @RequestMapping("/aiReview")
    public ResponseEntity<String> aiReview(@RequestBody Map<String, Object> requestBody){
        // 参数校验
        if (requestBody == null || requestBody.isEmpty()) {
            log.warn("用户申诉任务请求参数为空");
            JSONObject errorData = new JSONObject();
            errorData.put("code", 400);
            errorData.put("message", "请求参数不能为空");
            return ResponseEntity.badRequest().body(errorData.toJSONString());
        }


        // 同步获取访问令牌（不在异步中执行）
        String accessToken = aiAuthTokenUtil.getAccessToken();
        if (!StringUtils.hasText(accessToken)) {
            log.error("调用AI申诉接口失败，获取accessToken失败");
            JSONObject errorData = new JSONObject();
            errorData.put("code", 500);
            errorData.put("message", "获取访问令牌失败");
            return ResponseEntity.status(500).body(errorData.toJSONString());
        }

        // 初始化请求体Map
        HttpHeaders aiHeaders = new HttpHeaders();
        aiHeaders.setContentType(MediaType.APPLICATION_JSON);
        aiHeaders.set("Authorization", "Bearer " + accessToken);

        CommentAppeal commentAppeal = new CommentAppeal();
        //申诉理由
        commentAppeal.setAppealReason(requestBody.get("appeal_reason").toString());
        //评价id
        commentAppeal.setCommentId(Integer.parseInt(requestBody.get("comment_id").toString()));
        //评价内容
        commentAppeal.setCommentInfo(requestBody.get("user_review").toString());
        //订单id
        commentAppeal.setOrderId(Integer.parseInt(requestBody.get("order_id").toString()));
        //申诉图片
        commentAppeal.setImgUrl(requestBody.get("appeal_images").toString());
        //评价图片
//        commentAppeal.setReviewImages(requestBody.get("review_images").toString());
        //律师id
        commentAppeal.setLawyerUserId(requestBody.get("lawyer_user_id").toString());
        commentAppealService.submitAppeal(commentAppeal);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);
        try {
            aiUserAuditTaskService.asyncAiReview(requestBody, accessToken);
            log.info("用户申诉任务已提交异步处理，请求参数：{}", requestBody);
        } catch (Exception e) {
            log.error("调用AI申诉接口 接口异常------", e);
        }
        // 立即返回成功响应
        JSONObject responseData = new JSONObject();
        responseData.put("code", 200);
        responseData.put("message", "用户申诉任务已提交，正在后台处理");
        responseData.put("data", new JSONObject());

        return ResponseEntity.ok(responseData.toJSONString());
    }

    /**
     * 用户申诉任务接口（异步处理）
     * <p>
     * 接口立即返回，AI服务调用在后台异步执行
     * </p>
     *
     * @param requestBody 请求参数
     * @return 立即返回成功响应
     */
    @RequestMapping("/userAuditTask")
    public ResponseEntity<String> userAuditTask(@RequestBody Map<String, Object> requestBody) {
        log.info("接收用户申诉任务请求，请求参数：{}", requestBody);

        // 参数校验
        if (requestBody == null || requestBody.isEmpty()) {
            log.warn("用户申诉任务请求参数为空");
            JSONObject errorData = new JSONObject();
            errorData.put("code", 400);
            errorData.put("message", "请求参数不能为空");
            return ResponseEntity.badRequest().body(errorData.toJSONString());
        }

        // 构建 LawyerUserViolation 对象并调用 userReporting 服务
        try {
            LawyerUserViolation lawyerUserViolation = buildLawyerUserViolation(requestBody);
            if (lawyerUserViolation == null) {
                log.warn("构建 LawyerUserViolation 对象失败，请求参数：{}", requestBody);
                JSONObject errorData = new JSONObject();
                errorData.put("code", 400);
                errorData.put("message", "订单号不能为空");
                return ResponseEntity.badRequest().body(errorData.toJSONString());
            }

            // 调用 userReporting 服务（同步执行）
            log.info("开始调用 userReporting 服务，订单号：{}", lawyerUserViolation.getOrderNumber());
            int result = lawyerUserViolationService.userReporting(lawyerUserViolation);
            if (result <= 0) {
                log.warn("userReporting 服务调用失败，订单号：{}", lawyerUserViolation.getOrderNumber());
                JSONObject errorData = new JSONObject();
                errorData.put("code", 500);
                errorData.put("message", "用户举报处理失败");
                return ResponseEntity.status(500).body(errorData.toJSONString());
            }
            log.info("userReporting 服务调用成功，订单号：{}，返回结果：{}", lawyerUserViolation.getOrderNumber(), result);
        } catch (RuntimeException e) {
            log.error("调用 userReporting 服务异常，请求参数：{}，异常信息：{}", requestBody, e.getMessage(), e);
            JSONObject errorData = new JSONObject();
            errorData.put("code", 500);
            errorData.put("message", "用户举报处理失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorData.toJSONString());
        } catch (Exception e) {
            log.error("调用 userReporting 服务异常，请求参数：{}，异常信息：{}", requestBody, e.getMessage(), e);
            JSONObject errorData = new JSONObject();
            errorData.put("code", 500);
            errorData.put("message", "用户举报处理失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorData.toJSONString());
        }

        // 同步获取访问令牌（不在异步中执行）
        String accessToken = aiAuthTokenUtil.getAccessToken();
        if (!StringUtils.hasText(accessToken)) {
            log.error("调用AI用户申诉接口失败，获取accessToken失败");
            JSONObject errorData = new JSONObject();
            errorData.put("code", 500);
            errorData.put("message", "获取访问令牌失败");
            return ResponseEntity.status(500).body(errorData.toJSONString());
        }

        // 异步调用AI服务（传递已获取的访问令牌）
        try {
            aiUserAuditTaskService.asyncCallUserAuditTask(requestBody, accessToken);
            log.info("用户申诉任务已提交异步处理，请求参数：{}", requestBody);
        } catch (Exception e) {
            log.error("提交用户申诉任务异步处理失败，请求参数：{}，异常信息：{}", requestBody, e.getMessage(), e);
        }

        // 立即返回成功响应
        JSONObject responseData = new JSONObject();
        responseData.put("code", 200);
        responseData.put("message", "用户申诉任务已提交，正在后台处理");
        responseData.put("data", new JSONObject());

        return ResponseEntity.ok(responseData.toJSONString());
    }

    /**
     * 从请求参数构建 LawyerUserViolation 对象
     *
     * @param requestBody 请求参数
     * @return LawyerUserViolation 对象，如果订单号为空则返回 null
     */
    private LawyerUserViolation buildLawyerUserViolation(Map<String, Object> requestBody) {
        if (requestBody == null) {
            return null;
        }

        // 获取订单号（必填）
        Object orderNumberObj = requestBody.get("order_number");
        if (orderNumberObj == null) {
            log.warn("请求参数中缺少订单号");
            return null;
        }
        String orderNumber = orderNumberObj.toString();

        LawyerUserViolation lawyerUserViolation = new LawyerUserViolation();
        lawyerUserViolation.setOrderNumber(orderNumber);

        // 根据 user_demand 内容设置 violationReason
        Object userDemandObj = requestBody.get("user_demand");
        if (userDemandObj != null) {
            String userDemand = userDemandObj.toString();
            String violationReason = determineViolationReason(userDemand);
            lawyerUserViolation.setViolationReason(violationReason);
            if(violationReason.equals("4")){
                lawyerUserViolation.setOtherReasonContent(userDemand);
            }
            log.info("根据 user_demand 设置 violationReason，user_demand：{}，violationReason：{}", userDemand, violationReason);
        }

        // 设置举报凭证图片（report_images）
        Object reportImagesObj = requestBody.get("report_images");
        if (reportImagesObj != null) {
            String reportEvidenceImg;
            if (reportImagesObj instanceof List) {
                // 如果是列表，转换为逗号分隔的字符串
                @SuppressWarnings("unchecked")
                List<String> imageList = (List<String>) reportImagesObj;
                reportEvidenceImg = String.join(",", imageList);
            } else {
                reportEvidenceImg = reportImagesObj.toString();
            }
            lawyerUserViolation.setReportEvidenceImg(reportEvidenceImg);
        }

        // 设置举报内容分类（默认为用户举报律师）
        lawyerUserViolation.setReportContextType("6");
        lawyerUserViolation.setReportedUserType("3");
        lawyerUserViolation.setReportingUserType("2");

        log.info("构建 LawyerUserViolation 对象，订单号：{}，举报原因：{}", orderNumber, lawyerUserViolation.getViolationReason());
        return lawyerUserViolation;
    }

    /**
     * 根据 user_demand 内容确定 violationReason
     * <p>
     * 规则：
     * - 包含"服务态度差" -> violationReason = "1"
     * - 包含"专业能力差" -> violationReason = "2"
     * - 包含"响应时间超过24小时" -> violationReason = "3"
     * - 其他情况 -> 返回原始 user_demand 内容
     * </p>
     *
     * @param userDemand 用户需求内容
     * @return violationReason 值
     */
    private String determineViolationReason(String userDemand) {
        if (userDemand == null || userDemand.trim().isEmpty()) {
            return null;
        }

        String demand = userDemand.trim();

        // 检查是否包含"服务态度差"
        if (demand.contains("服务态度差")) {
            return "1";
        } else if (demand.contains("专业能力差")) {
            // 检查是否包含"专业能力差"
            return "2";
        } else if (demand.contains("响应时间超过24小时")) {
            // 检查是否包含"响应时间超过24小时"
            return "3";
        } else {
            return "4";
        }
    }
}
