package com.wzj.soopin.order.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzj.soopin.member.domain.po.AccountBill;
import com.wzj.soopin.member.enums.AccountBillChangeTypeEnum;
import com.wzj.soopin.member.enums.AccountBillSourceEnum;
import com.wzj.soopin.member.mapper.MemberAccountMapper;
import com.wzj.soopin.order.domain.entity.RedPacket;
import com.wzj.soopin.order.domain.entity.RedPacketReceive;
import com.wzj.soopin.order.domain.query.GrabRedPacketRequest;
import com.wzj.soopin.order.domain.query.SendRedPacketRequest;
import com.wzj.soopin.order.mapper.RedPacketMapper;
import com.wzj.soopin.order.mapper.RedPacketReceiveMapper;
import com.wzj.soopin.order.service.RedPacketService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class RedPacketServiceImpl extends ServiceImpl<RedPacketMapper, RedPacket> implements RedPacketService {

    private final RedPacketMapper redPacketMapper;
    private final RedPacketReceiveMapper redPacketReceiveMapper;
    private final MemberAccountMapper umsAccountMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    // Redis锁前缀
    private static final String LOCK_PREFIX = "red_packet:lock:";

    // 红包状态：0-未领取 1-已领取部分 2-已领完 3-已过期 4-已退款
    private static final int STATUS_UNRECEIVED = 0;
    private static final int STATUS_PART_RECEIVED = 1;
    private static final int STATUS_ALL_RECEIVED = 2;
    private static final int STATUS_EXPIRED = 3;
    private static final int STATUS_REFUNDED = 4;

    // 聊天类型：1-单聊 2-群聊
    private static final int CHAT_TYPE_SINGLE = 1;
    private static final int CHAT_TYPE_GROUP = 2;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> sendRedPacket(SendRedPacketRequest request) {
        // 参数校验
        validateSendParams(request);

        Long memberId = request.getSenderId();

        // 验证发送者余额
        BigDecimal balance = umsAccountMapper.getMoneyBalanceByMemberId(memberId);
        if (balance == null || balance.compareTo(request.getTotalAmount()) < 0) {
            throw new RuntimeException("账户余额不足，无法发送红包");
        }

        // 创建红包记录
        RedPacket redPacket = createRedPacket(request);
        redPacketMapper.insert(redPacket);
        Long packetId = redPacket.getId();

        // 扣减发送者余额并记录变动
        deductSenderBalance(request.getSenderId(), redPacket, balance);

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("packetId", packetId);
        result.put("receiverId", redPacket.getReceiverId());
        result.put("totalAmount", redPacket.getTotalAmount());
        result.put("totalCount", redPacket.getTotalCount());
        result.put("createTime", redPacket.getCreateTime());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> grabRedPacket(GrabRedPacketRequest request) {

        Long packetId = request.getPacketId();
        Long memberId = request.getMemberId();
        // 获取分布式锁
        String lockKey = LOCK_PREFIX + packetId;
        Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 5, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(locked)) {
            try {
                return doReceiveRedPacket(packetId, memberId);
            } finally {
                // 释放锁
                redisTemplate.delete(lockKey);
            }
        } else {
            throw new RuntimeException("抢红包太火爆，请稍后再试");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> doReceiveRedPacket(Long packetId, Long memberId) {
        // 查询红包信息
        RedPacket redPacket = redPacketMapper.selectById(packetId);
        if (redPacket == null) {
            throw new RuntimeException("红包不存在");
        }

        // 验证红包状态
        validateRedPacketStatus(redPacket, memberId);

        // 检查是否已领取
        Integer received = redPacketReceiveMapper.checkReceived(packetId, memberId);
        if (received != null && received > 0) {
            throw new RuntimeException("您已领取过该红包");
        }

        // 计算领取金额
        BigDecimal receiveAmount = calculateReceiveAmount(redPacket);

        // 更新红包剩余金额和数量
        updateRedPacketRemaining(redPacket, receiveAmount);

        // 创建领取记录
        RedPacketReceive receiveRecord = createReceiveRecord(redPacket, memberId, receiveAmount);
        redPacketReceiveMapper.insert(receiveRecord);

        // 增加领取者余额并记录变动
        addReceiverBalance(memberId, receiveAmount, packetId);

        // 更新红包状态
        updateRedPacketStatus(redPacket);

        Map<String, Object> result = new HashMap<>();
        result.put("packetId", packetId);
        result.put("receiveAmount", receiveAmount);
        result.put("receiveTime", receiveRecord.getReceviceTime());
        result.put("isLastOne", redPacket.getRemainingCount() == 0);
        return result;
    }

    /**
     * 验证发送红包参数
     */
    private void validateSendParams(SendRedPacketRequest request) {
        // 验证聊天类型
        if (request.getChatType() != CHAT_TYPE_SINGLE && request.getChatType() != CHAT_TYPE_GROUP) {
            throw new RuntimeException("聊天类型无效，只能是单聊或群聊");
        }

        // 单聊必须指定接收者
        if (request.getChatType() == CHAT_TYPE_SINGLE && request.getReceiverId() == null) {
            throw new RuntimeException("单聊红包必须指定接收者ID");
        }

        // 群聊必须指定群ID和红包个数
        if (request.getChatType() == CHAT_TYPE_GROUP) {
            if (request.getGroupId() == null) {
                throw new RuntimeException("群聊红包必须指定群ID");
            }
            if (request.getTotalCount() == null || request.getTotalCount() < 1) {
                throw new RuntimeException("群聊红包必须指定有效个数（至少1个）");
            }
        }
    }

    /**
     * 创建红包记录
     */
    private RedPacket createRedPacket(SendRedPacketRequest request) {
        RedPacket redPacket = new RedPacket();
        redPacket.setSenderId(request.getSenderId());
        redPacket.setChatType(request.getChatType());
        redPacket.setReceiverId(request.getReceiverId());
        redPacket.setGroupId(request.getGroupId());
        // 默认为普通红包
        redPacket.setPacketType(1);
        redPacket.setTotalAmount(request.getTotalAmount());
        redPacket.setTotalCount(request.getTotalCount());
        redPacket.setRemainingAmount(request.getTotalAmount());
        redPacket.setRemainingCount(request.getTotalCount());
        redPacket.setStatus(STATUS_UNRECEIVED);
        // 24小时后过期
        redPacket.setExpireTime(LocalDateTime.now().plusDays(1));
        redPacket.setRemark(request.getRemark() != null && !request.getRemark().isEmpty()
            ? request.getRemark()
            : "恭喜发财，大吉大利!");
        return redPacket;
    }

    /**
     * 扣减发送者余额并记录变动
     */
    private void deductSenderBalance(Long senderId, RedPacket redPacket, BigDecimal beforeBalance) {
        // 计算扣减后的余额
        BigDecimal afterBalance = beforeBalance.subtract(redPacket.getTotalAmount());
        umsAccountMapper.updateMoneyBalance(senderId, afterBalance);

        // 记录金额变动
//        AccountBill record = AccountBill.builder()
//            .moneyBalance(beforeBalance)
//            .accountId(senderId)
//            .beforeBalance(beforeBalance)
//            .afterBalance(afterBalance)
//            .changeAmount(redPacket.getTotalAmount())
//            .changeType(AccountBillChangeTypeEnum.OUT.getCode())
//            .source(AccountBillSourceEnum.RED_PACKAGE_SEND.getCode())
//            .changeDesc("发送红包扣减，红包ID：" + redPacket.getId())
//            .build();
//
//        accountChangeRecordMapper.insert(record);
    }

    /**
     * 验证红包状态
     */
    private void validateRedPacketStatus(RedPacket redPacket, Long memberId) {
        // 检查是否过期
        if (redPacket.getExpireTime().isBefore(LocalDateTime.now())) {
            if (redPacket.getRemainingAmount().compareTo(BigDecimal.ZERO) > 0) {
                refundRemainingAmount(redPacket);
            } else {
                redPacket.setStatus(STATUS_EXPIRED);
                redPacketMapper.updateById(redPacket);
                throw new RuntimeException("红包已过期");
            }
        }

        // 检查是否已领完
        if (redPacket.getStatus() == STATUS_ALL_RECEIVED) {
            throw new RuntimeException("红包已被领完");
        }

        // 检查是否是自己发的红包
        if (redPacket.getSenderId().equals(memberId)) {
            throw new RuntimeException("不能领取自己发送的红包");
        }

        // 单聊红包只能指定接收者领取
        if (redPacket.getChatType() == CHAT_TYPE_SINGLE &&
            !redPacket.getReceiverId().equals(memberId)) {
            throw new RuntimeException("您无权领取该红包");
        }
    }

    /**
     * 退款剩余金额
     */
    private void refundRemainingAmount(RedPacket redPacket) {
        Long senderId = redPacket.getSenderId();
        BigDecimal remainingAmount = redPacket.getRemainingAmount();

        // 查询当前余额
        BigDecimal beforeBalance = umsAccountMapper.getMoneyBalanceByMemberId(senderId);
        if (beforeBalance == null) {
            throw new RuntimeException("发送者账户不存在");
        }

        // 增加余额
        BigDecimal afterBalance = beforeBalance.add(remainingAmount);
        umsAccountMapper.updateMoneyBalance(senderId, afterBalance);

//        // 记录金额变动
//        AccountBill record = AccountBill.builder()
//            .accountId(senderId)
//            .beforeBalance(beforeBalance)
//            .afterBalance(afterBalance)
//            .changeAmount(remainingAmount)
//            .changeType(AccountBillChangeTypeEnum.IN.getCode())
//            .source(AccountBillSourceEnum.RED_PACKAGE_REFUND.getCode())
//            .changeDesc("红包退款，红包ID：" + redPacket.getId())
//            .build();
//
//        accountChangeRecordMapper.insert(record);

        // 更新红包状态为已退款
        redPacket.setStatus(STATUS_REFUNDED);
        redPacket.setRemainingAmount(BigDecimal.ZERO);
        redPacketMapper.updateById(redPacket);
    }

    /**
     * 计算领取金额
     */
    private BigDecimal calculateReceiveAmount(RedPacket redPacket) {
        int remainingCount = redPacket.getRemainingCount();
        BigDecimal remainingAmount = redPacket.getRemainingAmount();

        if (remainingCount == 1) {
            // 最后一个红包，领取全部剩余金额
            return remainingAmount;
        }
        BigDecimal minAmount = new BigDecimal("0.01");
        BigDecimal maxAmount = remainingAmount.subtract(new BigDecimal(remainingCount - 1).multiply(minAmount));
        BigDecimal randomAmount = minAmount.add(new BigDecimal(Math.random() * maxAmount.doubleValue())).setScale(2, BigDecimal.ROUND_HALF_UP);

        return randomAmount;
    }

    /**
     * 更新红包剩余金额和数量
     */
    private void updateRedPacketRemaining(RedPacket redPacket, BigDecimal receiveAmount) {
        redPacket.setRemainingAmount(redPacket.getRemainingAmount().subtract(receiveAmount));
        redPacket.setRemainingCount(redPacket.getRemainingCount() - 1);
        redPacketMapper.updateById(redPacket);
    }

    /**
     * 创建领取记录
     */
    private RedPacketReceive createReceiveRecord(RedPacket redPacket, Long memberId, BigDecimal amount) {
        RedPacketReceive record = new RedPacketReceive();
        record.setPacketId(redPacket.getId());
        record.setReceiverId(memberId);
        record.setAmount(amount);
        record.setReceviceTime(new DateTime());
        return record;
    }

    /**
     * 增加领取者余额并记录变动
     */
    private void addReceiverBalance(Long memberId, BigDecimal amount, Long packetId) {
        // 查询当前余额
        BigDecimal beforeBalance = umsAccountMapper.getMoneyBalanceByMemberId(memberId);
        if (beforeBalance == null) {
            throw new RuntimeException("领取者账户不存在");
        }

        // 增加余额
        BigDecimal afterBalance = beforeBalance.add(amount);
        umsAccountMapper.updateMoneyBalance(memberId, afterBalance);

//        // 记录金额变动
//        AccountBill record = AccountBill.builder()
//            .accountId(memberId)
//            .beforeBalance(beforeBalance)
//            .afterBalance(afterBalance)
//            .changeAmount(amount)
//            .changeType(AccountBillChangeTypeEnum.IN.getCode())
//            .source(AccountBillSourceEnum.RED_PACKAGE_RECEIVE.getCode())
//            .changeDesc("红包领取，红包ID：" + packetId)
//            .build();
//
//        accountChangeRecordMapper.insert(record);
    }

    /**
     * 更新红包状态
     */
    private void updateRedPacketStatus(RedPacket redPacket) {
        if (redPacket.getRemainingCount() == 0) {
            redPacket.setStatus(STATUS_ALL_RECEIVED);
        } else {
            redPacket.setStatus(STATUS_PART_RECEIVED);
        }
        redPacketMapper.updateById(redPacket);
    }

    /**
     * 定时任务：检查并退款过期的红包
     */
    @Scheduled(fixedRate = 1800000) // 每30分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void checkAndRefundExpiredRedPackets() {
        // 查询所有未领取或部分领取且已过期的红包
        List<RedPacket> expiredRedPackets = redPacketMapper.selectExpiredRedPackets();

        for (RedPacket redPacket : expiredRedPackets) {
            if (redPacket.getRemainingAmount().compareTo(BigDecimal.ZERO) > 0) {
                refundRemainingAmount(redPacket);
            } else {
                redPacket.setStatus(STATUS_EXPIRED);
                redPacketMapper.updateById(redPacket);
            }
        }
    }

}
