package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.entity.PointsOrder;
import com.zhentao.entity.SystemMessages;
import com.zhentao.entity.Users;
import com.zhentao.mapper.SystemMessagesMapper;
import com.zhentao.mapper.UsersMapper;
import com.zhentao.service.SystemMessagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
* @author 联想
* @description 针对表【system_messages(系统消息)】的数据库操作Service实现
* @createDate 2025-12-12 14:54:02
*/
@Service
public class SystemMessagesServiceImpl extends ServiceImpl<SystemMessagesMapper, SystemMessages>
    implements SystemMessagesService{

    @Autowired
    private UsersMapper usersMapper;
    
    @Autowired
    private SystemMessagesMapper systemMessagesMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPointsOrderReviewMessage(PointsOrder pointsOrder) {
        System.out.println("========== 开始创建积分订单审核系统消息 ==========");
        System.out.println("订单信息: " + (pointsOrder != null ? pointsOrder.toString() : "null"));
        
        if (pointsOrder == null) {
            System.err.println("错误：pointsOrder 为 null，无法创建系统消息");
            return;
        }
        
        if (pointsOrder.getReceiverPhone() == null || pointsOrder.getReceiverPhone().trim().isEmpty()) {
            System.err.println("错误：订单收件人电话为空，订单ID=" + pointsOrder.getId() + "，订单号=" + pointsOrder.getOrderNo());
            return;
        }

        System.out.println("收件人电话: " + pointsOrder.getReceiverPhone());
        System.out.println("订单号: " + pointsOrder.getOrderNo());
        System.out.println("审核状态: " + pointsOrder.getReview());
        
        // 检查订单号是否为空
        if (pointsOrder.getOrderNo() == null || pointsOrder.getOrderNo().trim().isEmpty()) {
            System.err.println("错误：订单号为空，订单ID=" + pointsOrder.getId() + "，无法创建系统消息");
            return;
        }

        // 通过收件人电话查询用户ID
        LambdaQueryWrapper<Users> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(Users::getPhone, pointsOrder.getReceiverPhone());
        Users user = usersMapper.selectOne(userWrapper);

        if (user == null) {
            System.err.println("错误：未找到手机号为 " + pointsOrder.getReceiverPhone() + " 的用户，无法创建系统消息");
            return;
        }
        
        if (user.getUserId() == null) {
            System.err.println("错误：找到用户但 userId 为 null，手机号=" + pointsOrder.getReceiverPhone());
            return;
        }

        System.out.println("找到用户: userId=" + user.getUserId() + ", phone=" + user.getPhone());

        // 创建系统消息
        SystemMessages message = new SystemMessages();
        message.setUserId(user.getUserId());
        message.setTitle("系统通知-积分商城货物通知");
        message.setType("points_order_review"); // 设置消息类型为积分订单审核
        
        // 根据审核状态设置内容
        if (pointsOrder.getReview() != null) {
            if (pointsOrder.getReview() == 1) {
                // 审核通过
                String content = "订单号为\"" + pointsOrder.getOrderNo() + "\"的货物，经过管理人员审核成功，准备发送货物。";
                message.setContent(content);
                System.out.println("审核通过，消息内容: " + content);
            } else if (pointsOrder.getReview() == 2) {
                // 审核未通过
                String reviewFailReason = pointsOrder.getReviewFail() != null ? pointsOrder.getReviewFail() : "未说明原因";
                String content = "订单号为\"" + pointsOrder.getOrderNo() + "\"的货物，经过管理人员审核，表示未通过，具体原因是" + reviewFailReason;
                message.setContent(content);
                System.out.println("审核未通过，消息内容: " + content);
            } else {
                // 其他状态，不创建消息
                System.out.println("审核状态为其他值(" + pointsOrder.getReview() + ")，不创建消息");
                return;
            }
        } else {
            // 审核状态为空，不创建消息
            System.err.println("错误：审核状态为 null，不创建消息");
            return;
        }

        message.setIsRead(0); // 0-未读
        message.setCreatedAt(new Date());
        
        System.out.println("准备保存系统消息: userId=" + message.getUserId() + ", title=" + message.getTitle() + ", content=" + message.getContent());
        System.out.println("消息对象详情: " + message.toString());
        
        // 保存系统消息 - 使用 systemMessagesMapper.insert() 直接插入
        try {
            int insertResult = systemMessagesMapper.insert(message);
            if (insertResult > 0) {
                System.out.println("系统消息保存成功！插入行数=" + insertResult + ", 消息ID=" + (message.getId() != null ? message.getId() : "待生成"));
                System.out.println("保存后的消息对象: " + message.toString());
                
                // 验证数据是否真的插入到数据库
                if (message.getId() != null) {
                    SystemMessages savedMessage = systemMessagesMapper.selectById(message.getId());
                    if (savedMessage != null) {
                        System.out.println("验证成功：从数据库查询到保存的消息，ID=" + savedMessage.getId());
                    } else {
                        System.err.println("警告：消息保存后无法从数据库查询到，可能存在事务问题");
                    }
                }
            } else {
                System.err.println("系统消息保存失败！insert() 方法返回 0，未插入任何数据");
            }
        } catch (Exception e) {
            System.err.println("系统消息保存时发生异常：" + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("保存系统消息失败：" + e.getMessage(), e);
        }
        
        System.out.println("========== 创建积分订单审核系统消息完成 ==========");
    }
}




