package shop.alien.lawyer.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import shop.alien.entity.store.LawyerConsultationOrder;
import shop.alien.entity.store.LawyerUserViolation;
import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.LawyerUser;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.lawyer.config.WebSocketProcess;
import shop.alien.lawyer.service.AiUserAuditTaskService;
import shop.alien.lawyer.service.LawyerUserViolationService;
import shop.alien.lawyer.util.ali.AliApi;
import shop.alien.mapper.LawyerConsultationOrderMapper;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.util.type.LifeNoticeUtil;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.LawyerUserMapper;
import shop.alien.mapper.StoreUserMapper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

/**
 * AI用户申诉任务服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@RefreshScope
public class AiUserAuditTaskServiceImpl implements AiUserAuditTaskService {

    private final RestTemplate restTemplate;

    private final LawyerUserViolationService lawyerUserViolationService;

    @Value("${third-party-ai-auto-review.user-complaint-url:http://124.93.18.180:9100/ai/auto-review/api/v1/lawyer_user_complaint_audit_task/submit}")
    private String aiUserAuditTaskUrl;

    @Value("${third-party-ai-auto-review.lawyer-complaint-url:http://124.93.18.180:9100/ai/auto-review/api/v1/lawyer_complaint_audit_task/submit}")
    private String aiAutoReviewUrl;

    private final LawyerConsultationOrderMapper consultationOrderMapper;

    private final AliApi aliApi;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final WebSocketProcess webSocketProcess;

    private final LifeUserMapper lifeUserMapper;

    private final LawyerUserMapper lawyerUserMapper;

    private final StoreUserMapper storeUserMapper;

    private static final String SYSTEM_SENDER_ID = "system";

    @Override
    @Async("lawyerTaskExecutor")
    public void asyncCallUserAuditTask(Map<String, Object> requestBody, String accessToken) {
        log.info("开始异步调用AI用户申诉接口，请求URL：{}，请求参数：{}", aiUserAuditTaskUrl, requestBody);

        try {
            // 初始化请求头（使用已获取的访问令牌）
            HttpHeaders aiHeaders = new HttpHeaders();
            aiHeaders.setContentType(MediaType.APPLICATION_JSON);
            aiHeaders.set("Authorization", "Bearer " + accessToken);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);

            log.info("异步调用AI用户申诉接口，URL：{}，请求头：{}", aiUserAuditTaskUrl, aiHeaders);

            // 调用AI服务
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(
                    aiUserAuditTaskUrl, request, String.class);

            log.info("异步调用AI用户申诉接口成功，响应状态：{}，响应体：{}",
                    responseEntity.getStatusCode(), responseEntity.getBody());

            // 解析响应并更新举报记录
            parseAndUpdateViolation(responseEntity.getBody());

        } catch (HttpServerErrorException e) {
            String responseBody = e.getResponseBodyAsString();
            log.error("异步调用AI用户申诉接口返回服务器错误，状态码：{}，响应体：{}，URL：{}",
                    e.getStatusCode(), responseBody, aiUserAuditTaskUrl, e);
            // 即使返回错误，也尝试解析响应体（可能包含审核结果）
            if (StringUtils.hasText(responseBody)) {
                parseAndUpdateViolation(responseBody);
            }
        } catch (HttpClientErrorException e) {
            String responseBody = e.getResponseBodyAsString();
            log.error("异步调用AI用户申诉接口返回客户端错误，状态码：{}，响应体：{}，URL：{}",
                    e.getStatusCode(), responseBody, aiUserAuditTaskUrl, e);
            // 即使返回错误，也尝试解析响应体（可能包含审核结果）
            if (StringUtils.hasText(responseBody)) {
                parseAndUpdateViolation(responseBody);
            }
        } catch (Exception e) {
            log.error("异步调用AI用户申诉接口异常，URL：{}，异常信息：{}", aiUserAuditTaskUrl, e.getMessage(), e);
        }
    }

    @Override
    @Async("lawyerTaskExecutor")
    public void asyncAiReview(Map<String, Object> requestBody, String accessToken) {
        log.info("开始异步调用AI申诉接口，请求URL：{}，请求参数：{}", aiUserAuditTaskUrl, requestBody);

        try {
            // 初始化请求头（使用已获取的访问令牌）
            HttpHeaders aiHeaders = new HttpHeaders();
            aiHeaders.setContentType(MediaType.APPLICATION_JSON);
            aiHeaders.set("Authorization", "Bearer " + accessToken);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);

            log.info("异步调用AI用户申诉接口，URL：{}，请求头：{}", aiUserAuditTaskUrl, aiHeaders);

            // 调用AI服务
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(
                    aiAutoReviewUrl, request, String.class);

            log.info("异步调用AI用户申诉接口成功，响应状态：{}，响应体：{}",
                    responseEntity.getStatusCode(), responseEntity.getBody());

        } catch (HttpServerErrorException e) {
            log.error("异步调用AI申诉接口返回服务器错误，状态码：{}，响应体：{}，URL：{}",
                    e.getStatusCode(), e.getResponseBodyAsString(), aiAutoReviewUrl, e);
        } catch (HttpClientErrorException e) {
            log.error("异步调用AI用户申诉接口返回客户端错误，状态码：{}，响应体：{}，URL：{}",
                    e.getStatusCode(), e.getResponseBodyAsString(), aiAutoReviewUrl, e);
        } catch (Exception e) {
            log.error("异步调用AI申诉接口异常，URL：{}，异常信息：{}", aiAutoReviewUrl, e.getMessage(), e);
        }
    }

    /**
     * 解析AI响应并更新举报记录
     *
     * @param responseBody 响应体JSON字符串
     */
    private void parseAndUpdateViolation(String responseBody) {
        if (!StringUtils.hasText(responseBody)) {
            log.warn("AI响应体为空，无法解析");
            return;
        }

        try {
            // 解析JSON响应
            JSONObject responseJson = JSONObject.parseObject(responseBody);

            // 检查响应码
            Integer code = responseJson.getInteger("code");
            if (code == null || code != 200) {
                log.warn("AI响应码异常，code：{}，message：{}", code, responseJson.getString("message"));
                return;
            }

            // 获取data对象
            JSONObject data = responseJson.getJSONObject("data");
            if (data == null) {
                log.warn("AI响应data为空，无法获取审核结果");
                return;
            }

            // 获取订单号
            String orderNumber = data.getString("order_number");
            if (!StringUtils.hasText(orderNumber)) {
                log.warn("AI响应订单号为空，无法更新举报记录");
                return;
            }

            // 获取result对象
            JSONObject result = data.getJSONObject("result");
            if (result == null) {
                log.warn("AI响应result为空，订单号：{}", orderNumber);
                return;
            }

            // 获取处理状态和审核结果
            Integer processingStatus = result.getInteger("processing_status");
            Boolean isReportValid = result.getBoolean("is_report_valid");
            String decisionReason = result.getString("decision_reason");

            log.info("解析AI响应成功，订单号：{}，processing_status：{}，is_report_valid：{}，decision_reason：{}",
                    orderNumber, processingStatus, isReportValid, decisionReason);

            if (processingStatus != null) {
                if (processingStatus == 1 && StringUtils.hasText(orderNumber)) {
                    // processing_status = 1 表示已通过，进行退款操作
                    processRefund(orderNumber);
                    
                    // 发送举报成功通知
                    //sendReportSuccessNotifications(orderNumber);
                } else if (processingStatus == 2 && StringUtils.hasText(orderNumber)) {
                    // processing_status = 2 表示未违规（举报失败），发送举报失败通知
                    //sendReportFailureNotification(orderNumber, decisionReason);
                }
            } else {
                log.warn("processing_status为空，订单号：{}", orderNumber);
            }

        } catch (Exception e) {
            log.error("解析AI响应并更新举报记录异常，响应体：{}，异常信息：{}", responseBody, e.getMessage(), e);
        }
    }

    /**
     * 处理订单退款
     * <p>
     * 根据订单号查询订单信息，调用支付宝退款接口进行退款
     * 如果退款失败，会抛出异常以触发事务回滚
     * </p>
     *
     * @param orderNumber 订单号
     * @throws RuntimeException 当退款失败时抛出异常，触发事务回滚
     */
    private void processRefund(String orderNumber) {
        if (!StringUtils.hasText(orderNumber)) {
            log.error("处理退款失败：订单号为空");
            throw new RuntimeException("订单号不能为空，无法处理退款");
        }

        try {
            // 查询订单信息
            LambdaQueryWrapper<LawyerConsultationOrder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LawyerConsultationOrder::getOrderNumber, orderNumber)
                    .eq(LawyerConsultationOrder::getDeleteFlag, 0)
                    .last("LIMIT 1");
            LawyerConsultationOrder order = consultationOrderMapper.selectOne(queryWrapper);

            if (order == null) {
                log.error("处理退款失败：订单不存在，订单号：{}", orderNumber);
                throw new RuntimeException("订单不存在，无法处理退款，订单号：" + orderNumber);
            }

            // 检查订单是否有支付宝交易号
            if (!StringUtils.hasText(order.getAlipayNo())) {
                log.error("处理退款失败：订单无支付宝交易号，订单号：{}", orderNumber);
                throw new RuntimeException("订单无支付宝交易号，无法处理退款，订单号：" + orderNumber);
            }

            // 检查订单金额
            if (order.getOrderAmount() == null || order.getOrderAmount() <= 0) {
                log.error("处理退款失败：订单金额无效，订单号：{}，订单金额：{}", orderNumber, order.getOrderAmount());
                throw new RuntimeException("订单金额无效，无法处理退款，订单号：" + orderNumber);
            }

            // 将订单金额从分转换为元
            BigDecimal refundAmount = new BigDecimal(order.getOrderAmount())
                    .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);

            // 退款原因
            String refundReason = "举报审核通过，订单退款";

            // 调用支付宝退款接口
            log.info("开始处理订单退款，订单号：{}，支付宝交易号：{}，退款金额：{}元",
                    orderNumber, order.getAlipayNo(), refundAmount.toString());

            String refundResult = aliApi.processRefund(order.getAlipayNo(), refundAmount.toString(), refundReason, "");

            if ("调用成功".equals(refundResult)) {
                log.info("订单退款成功，订单号：{}，退款金额：{}元", orderNumber, refundAmount.toString());
                // 退款成功后，发送退款成功通知和退款到账通知
                sendRefundSuccessNotifications(order);
            } else {
                log.error("订单退款失败，订单号：{}，退款结果：{}", orderNumber, refundResult);
                // 退款失败时抛出异常，触发事务回滚
                throw new RuntimeException("订单退款失败，订单号：" + orderNumber + "，退款结果：" + refundResult);
            }

        } catch (RuntimeException e) {
            // 重新抛出RuntimeException，触发事务回滚
            log.error("处理订单退款失败，订单号：{}，异常信息：{}", orderNumber, e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            // 其他异常也转换为RuntimeException，触发事务回滚
            log.error("处理订单退款异常，订单号：{}，异常信息：{}", orderNumber, e.getMessage(), e);
            throw new RuntimeException("处理订单退款时发生异常，订单号：" + orderNumber + "，异常信息：" + e.getMessage(), e);
        }
    }

    /**
     * 发送举报失败通知
     * <p>
     * 当举报审核未通过时，向举报用户发送通知
     * </p>
     *
     * @param orderNumber   订单号
     * @param decisionReason 拒绝原因
     */
    private void sendReportFailureNotification(String orderNumber, String decisionReason) {
        try {
            // 根据订单号查询最新的举报记录
            LambdaQueryWrapper<LawyerUserViolation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LawyerUserViolation::getOrderNumber, orderNumber)
                    .orderByDesc(LawyerUserViolation::getId)
                    .last("LIMIT 1");

            LawyerUserViolation violation = lawyerUserViolationService.getOne(queryWrapper);
            if (violation == null) {
                log.warn("未找到举报记录，订单号：{}", orderNumber);
                return;
            }

            // 获取举报人接收ID
            String receiverId = getReporterReceiverId(violation);
            if (!StringUtils.hasText(receiverId)) {
                log.warn("获取举报人接收ID失败，举报ID：{}", violation.getId());
                return;
            }

            // 获取举报理由文本
            String violationReasonText = getViolationReasonText(violation);

            // 构建通知内容
            StringBuilder messageBuilder = new StringBuilder();
            messageBuilder.append("您举报律师").append(violationReasonText)
                    .append("，经核实，不存在此行为，订单金额不予退还。");
            
            // 添加拒绝原因
            if (StringUtils.hasText(decisionReason)) {
                messageBuilder.append("拒绝原因：").append(decisionReason);
            } else {
                // 如果没有拒绝原因，使用默认值
                messageBuilder.append("拒绝原因：举报不实");
            }

            String message = messageBuilder.toString();

            // 创建并保存通知
            LifeNotice lifeNotice = createLifeNotice(violation.getId(), receiverId, "举报失败通知", message);
            lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
            lifeNoticeMapper.insert(lifeNotice);

            // 发送WebSocket消息
            sendWebSocketMessage(receiverId, lifeNotice);

            log.info("举报失败通知发送成功，订单号：{}，接收人ID：{}", orderNumber, receiverId);

        } catch (Exception e) {
            log.error("发送举报失败通知异常，订单号：{}，异常信息：{}", orderNumber, e.getMessage(), e);
        }
    }

    /**
     * 发送举报成功通知
     * <p>
     * 当举报审核通过时，向举报用户和被举报律师发送通知
     * </p>
     *
     * @param orderNumber 订单号
     */
    private void sendReportSuccessNotifications(String orderNumber) {
        try {
            // 根据订单号查询最新的举报记录
            LambdaQueryWrapper<LawyerUserViolation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LawyerUserViolation::getOrderNumber, orderNumber).eq(LawyerUserViolation::getDeleteFlag, 0)
                    .orderByDesc(LawyerUserViolation::getId)
                    .last("LIMIT 1");

            LawyerUserViolation violation = lawyerUserViolationService.getOne(queryWrapper);
            if (violation == null) {
                log.warn("未找到举报记录，订单号：{}", orderNumber);
                return;
            }

            // 发送举报人通知
            sendReporterNotification(violation);

            // 发送被举报人通知
            sendReportedNotification(violation, orderNumber);

        } catch (Exception e) {
            log.error("发送举报成功通知异常，订单号：{}，异常信息：{}", orderNumber, e.getMessage(), e);
        }
    }

    /**
     * 发送举报人通知
     *
     * @param violation 举报记录
     */
    private void sendReporterNotification(LawyerUserViolation violation) {
        try {
            // 获取举报人接收ID
            String receiverId = getReporterReceiverId(violation);
            if (!StringUtils.hasText(receiverId)) {
                log.warn("获取举报人接收ID失败，举报ID：{}", violation.getId());
                return;
            }

            // 获取举报理由文本
            String violationReasonText = getViolationReasonText(violation);

            // 构建通知内容
            String message = String.format("您举报律师%s，经核实，确实存在此行为，订单金额将在1-3个工作日原路返还，请注意查收。",
                    violationReasonText);

            // 创建并保存通知
            LifeNotice lifeNotice = createLifeNotice(violation.getId(), receiverId, "举报成功通知", message);
            lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
            lifeNoticeMapper.insert(lifeNotice);

            // 发送WebSocket消息
            sendWebSocketMessage(receiverId, lifeNotice);

            log.info("举报人通知发送成功，订单号：{}，接收人ID：{}", violation.getOrderNumber(), receiverId);

        } catch (Exception e) {
            log.error("发送举报人通知异常，举报ID：{}，异常信息：{}", violation.getId(), e.getMessage(), e);
        }
    }

    /**
     * 发送被举报人通知
     *
     * @param violation   举报记录
     * @param orderNumber 订单号
     */
    private void sendReportedNotification(LawyerUserViolation violation, String orderNumber) {
        try {
            // 获取被举报人接收ID
            String receiverId = getReportedReceiverId(violation);
            if (!StringUtils.hasText(receiverId)) {
                log.warn("获取被举报人接收ID失败，举报ID：{}", violation.getId());
                return;
            }

            // 构建通知内容
            String message = String.format("用户对编号为%s的订单进行申诉，经核实，用户举报属实，订单金额将会退还给用户。",
                    orderNumber);

            // 创建并保存通知
            LifeNotice lifeNotice = createLifeNotice(violation.getId(), receiverId, "被举报成功通知", message);
            lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
            lifeNoticeMapper.insert(lifeNotice);

            // 发送WebSocket消息
            sendWebSocketMessage(receiverId, lifeNotice);

            log.info("被举报人通知发送成功，订单号：{}，接收人ID：{}", orderNumber, receiverId);

        } catch (Exception e) {
            log.error("发送被举报人通知异常，举报ID：{}，异常信息：{}", violation.getId(), e.getMessage(), e);
        }
    }

    /**
     * 获取举报理由文本
     *
     * @param violation 举报记录
     * @return 举报理由文本
     */
    private String getViolationReasonText(LawyerUserViolation violation) {
        String violationReasonId = violation.getViolationReason();
        if (!StringUtils.hasText(violationReasonId)) {
            return "其他原因";
        }

        switch (violationReasonId) {
            case "1":
                return "服务态度差";
            case "2":
                return "专业能力差";
            case "3":
                return "响应时间超过24小时";
            case "4":
                // 其他原因，使用用户填写的内容
                String otherReason = violation.getOtherReasonContent();
                return StringUtils.hasText(otherReason) ? otherReason : "其他原因";
            default:
                return "其他原因";
        }
    }

    /**
     * 获取举报人接收ID
     *
     * @param violation 举报记录
     * @return 接收人ID，格式：lawyer_/store_/user_ + 手机号
     */
    private String getReporterReceiverId(LawyerUserViolation violation) {
        String reportingUserType = violation.getReportingUserType();
        String reportingUserId = violation.getReportingUserId();

        if (!StringUtils.hasText(reportingUserId)) {
            log.warn("举报用户ID为空");
            return null;
        }

        // 用户类型：1-商户用户，2-普通用户，3-律师用户
        if ("3".equals(reportingUserType)) {
            // 律师用户
            LawyerUser lawyerUser = lawyerUserMapper.selectById(reportingUserId);
            if (lawyerUser != null && StringUtils.hasText(lawyerUser.getPhone())) {
                return "lawyer_" + lawyerUser.getPhone();
            }
        } else if ("1".equals(reportingUserType)) {
            // 商户用户
            StoreUser storeUser = storeUserMapper.selectById(reportingUserId);
            if (storeUser != null && StringUtils.hasText(storeUser.getPhone())) {
                return "store_" + storeUser.getPhone();
            }
        } else if ("2".equals(reportingUserType)) {
            // 普通用户
            LifeUser lifeUser = lifeUserMapper.selectById(reportingUserId);
            if (lifeUser != null && StringUtils.hasText(lifeUser.getUserPhone())) {
                return "user_" + lifeUser.getUserPhone();
            }
        }

        log.warn("获取举报人手机号失败，用户类型：{}，用户ID：{}", reportingUserType, reportingUserId);
        return null;
    }

    /**
     * 获取被举报人接收ID
     *
     * @param violation 举报记录
     * @return 接收人ID，格式：lawyer_/store_/user_ + 手机号
     */
    private String getReportedReceiverId(LawyerUserViolation violation) {
        String reportedUserType = violation.getReportedUserType();
        String reportedUserId = violation.getReportedUserId();

        if (!StringUtils.hasText(reportedUserId)) {
            log.warn("被举报用户ID为空");
            return null;
        }

        // 用户类型：1-商户用户，2-普通用户，3-律师用户
        if ("3".equals(reportedUserType)) {
            // 律师用户
            LawyerUser lawyerUser = lawyerUserMapper.selectById(reportedUserId);
            if (lawyerUser != null && StringUtils.hasText(lawyerUser.getPhone())) {
                return "lawyer_" + lawyerUser.getPhone();
            }
        } else if ("1".equals(reportedUserType)) {
            // 商户用户
            StoreUser storeUser = storeUserMapper.selectById(reportedUserId);
            if (storeUser != null && StringUtils.hasText(storeUser.getPhone())) {
                return "store_" + storeUser.getPhone();
            }
        } else if ("2".equals(reportedUserType)) {
            // 普通用户
            LifeUser lifeUser = lifeUserMapper.selectById(reportedUserId);
            if (lifeUser != null && StringUtils.hasText(lifeUser.getUserPhone())) {
                return "user_" + lifeUser.getUserPhone();
            }
        }

        log.warn("获取被举报人手机号失败，用户类型：{}，用户ID：{}", reportedUserType, reportedUserId);
        return null;
    }

    /**
     * 创建通知对象
     *
     * @param businessId 业务ID（举报ID）
     * @param receiverId 接收人ID
     * @param title      通知标题
     * @param message    通知消息
     * @return 通知对象
     */
    private LifeNotice createLifeNotice(Integer businessId, String receiverId, String title, String message) {
        LifeNotice lifeNotice = new LifeNotice();
        lifeNotice.setSenderId(SYSTEM_SENDER_ID);
        lifeNotice.setBusinessId(businessId);
        lifeNotice.setReceiverId(receiverId);
        lifeNotice.setTitle(title);
        lifeNotice.setNoticeType(1);
        lifeNotice.setIsRead(0);
        lifeNotice.setBusinessType(1);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", message);
        lifeNotice.setContext(jsonObject.toJSONString());

        return lifeNotice;
    }

    /**
     * 发送WebSocket消息
     *
     * @param receiverId 接收人ID
     * @param lifeNotice 通知对象
     */
    private void sendWebSocketMessage(String receiverId, LifeNotice lifeNotice) {
        try {
            WebSocketVo webSocketVo = new WebSocketVo();
            webSocketVo.setSenderId(SYSTEM_SENDER_ID);
            webSocketVo.setReceiverId(receiverId);
            webSocketVo.setCategory("notice");
            webSocketVo.setNoticeType("1");
            webSocketVo.setIsRead(0);
            webSocketVo.setText(JSONObject.from(lifeNotice).toJSONString());

            webSocketProcess.sendMessage(receiverId, JSONObject.from(webSocketVo).toJSONString());
        } catch (Exception e) {
            log.error("发送WebSocket消息异常，接收人ID：{}，异常信息：{}", receiverId, e.getMessage(), e);
        }
    }

    /**
     * 发送退款成功通知和退款到账通知
     * <p>
     * 当退款成功后，向订单用户发送退款成功通知和退款到账通知
     * </p>
     *
     * @param order 订单信息
     */
    private void sendRefundSuccessNotifications(LawyerConsultationOrder order) {
        try {
            // 获取订单用户的接收人ID
            String receiverId = getOrderUserReceiverId(order);
            if (!StringUtils.hasText(receiverId)) {
                log.warn("获取订单用户接收ID失败，订单号：{}", order.getOrderNumber());
                return;
            }

            // 构建通知内容
            String message = String.format("您的编号为%s的订单，订单金额已原路返还至您的支付渠道，请查收。",
                    order.getOrderNumber());

            // 发送退款成功通知
//            LifeNotice refundSuccessNotice = createLifeNotice(order.getId(), receiverId, "退款成功通知", message);
//            lifeNoticeMapper.insert(refundSuccessNotice);
//            sendWebSocketMessage(receiverId, refundSuccessNotice);

            // 发送退款到账通知
            LifeNotice refundArrivalNotice = createLifeNotice(order.getId(), receiverId, "退款到账通知", message);
            lifeNoticeUtil.fillUserTypeAndRefId(refundArrivalNotice);
            lifeNoticeMapper.insert(refundArrivalNotice);
            sendWebSocketMessage(receiverId, refundArrivalNotice);

            log.info("退款成功通知和退款到账通知发送成功，订单号：{}，接收人ID：{}", order.getOrderNumber(), receiverId);

        } catch (Exception e) {
            log.error("发送退款成功通知异常，订单号：{}，异常信息：{}", order.getOrderNumber(), e.getMessage(), e);
        }
    }

    /**
     * 获取订单用户的接收人ID
     * <p>
     * 根据订单的客户端用户ID获取用户信息，返回接收人ID
     * </p>
     *
     * @param order 订单信息
     * @return 接收人ID，格式：user_ + 手机号
     */
    private String getOrderUserReceiverId(LawyerConsultationOrder order) {
        if (order == null || order.getClientUserId() == null) {
            log.warn("订单或客户端用户ID为空");
            return null;
        }

        try {
            // 查询普通用户信息
            LifeUser lifeUser = lifeUserMapper.selectById(order.getClientUserId());
            if (lifeUser != null && StringUtils.hasText(lifeUser.getUserPhone())) {
                return "user_" + lifeUser.getUserPhone();
            }

            log.warn("获取订单用户手机号失败，订单号：{}，客户端用户ID：{}", order.getOrderNumber(), order.getClientUserId());
            return null;
        } catch (Exception e) {
            log.error("获取订单用户接收ID异常，订单号：{}，客户端用户ID：{}，异常信息：{}",
                    order.getOrderNumber(), order.getClientUserId(), e.getMessage(), e);
            return null;
        }
    }
}

