package shop.alien.second.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.second.SecondUserCredit;
import shop.alien.entity.second.SecondUserCreditRecord;
import shop.alien.entity.second.vo.SecondUserCreditVo;
import shop.alien.mapper.second.SecondUserCreditMapper;
import shop.alien.mapper.second.SecondUserCreditRecordMapper;
import shop.alien.second.service.SecondGoodsService;
import shop.alien.second.service.SecondUserCreditRecordService;
import shop.alien.second.service.SecondUserCreditService;

import java.util.Date;

/**
 * 二手平台用户积分服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SecondUserCreditServiceImpl extends ServiceImpl<SecondUserCreditMapper, SecondUserCredit> implements SecondUserCreditService {
    
    private final SecondUserCreditMapper secondUserCreditMapper;
    private final SecondUserCreditRecordService secondUserCreditRecordService;
    private final SecondUserCreditRecordMapper secondUserCreditRecordMapper;

    /**
     * 二手商品服务
     */
    private final SecondGoodsService secondGoodsService;

    /**
     * 根据用户ID获取用户积分信息
     * @param userId 用户ID
     * @return 用户积分信息
     */
    @Override
    public SecondUserCredit getByUserId(Integer userId) {
        LambdaQueryWrapper<SecondUserCredit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SecondUserCredit::getUserId, userId)
                .eq(SecondUserCredit::getDeleteFlag, 0);
        return secondUserCreditMapper.selectOne(queryWrapper);
    }
    
    /**
     * 更新用户积分
     * @param credit
     * @return 是否更新成功
     */
    @Override
    public boolean updatePoints(SecondUserCreditVo credit) {
        try {
            // 查询用户积分记录
            SecondUserCredit userPoints = getByUserId(credit.getUserId());
            
            if (userPoints == null) {
                // 如果用户没有积分记录，则创建新记录
                userPoints = new SecondUserCredit();
                userPoints.setUserId(credit.getUserId());
                userPoints.setUserPoints(credit.getUserPoints() > 0 ? credit.getUserPoints() : 0);
                userPoints.setDeleteFlag(0);
                userPoints.setCreatedTime(new Date());
                userPoints.setUpdatedTime(new Date());
                secondUserCreditMapper.insert(userPoints);
            } else {
                // 更新积分
                int newPoints = userPoints.getUserPoints() - 50;
                userPoints.setUserPoints(newPoints > 0 ? newPoints : 0);
                userPoints.setUpdatedTime(new Date());
                secondUserCreditMapper.updateById(userPoints);
            }
            if (credit.getRuleType() == 3 || credit.getRuleType() == 4) {
                secondGoodsService.batchShelveGoodsByRiskControlRecord(credit.getRuleType(), credit.getBusinessId());
            }
            return true;
        } catch (Exception e) {
            log.error("更新用户积分失败，credit={}", credit, e);
            return false;
        }
    }
    
    /**
     * 新建用户积分记录
     * @param userId 用户ID
     * @param initialPoints 初始积分值
     * @return 是否创建成功
     */
    @Override
    public boolean createPointsRecord(Integer userId, Integer initialPoints, Integer pointsType) {
        try {
            // 检查是否已存在记录
            SecondUserCredit existingPoints = getByUserId(userId);
            if (existingPoints != null) {
                // 使用LambdaQueryWrapper的exists方法 查看是否已添加基础积分
                LambdaQueryWrapper<SecondUserCreditRecord> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SecondUserCreditRecord::getUserId, userId)
                        .eq(SecondUserCreditRecord::getPointsType, 1)
                        .eq(SecondUserCreditRecord::getDeleteFlag, 0);
                boolean exists = secondUserCreditRecordMapper.selectCount(queryWrapper) > 0;

                if (!exists) {
                    // 更新积分
                    int newPoints = existingPoints.getUserPoints() + initialPoints;
                    existingPoints.setUserPoints(newPoints > 0 ? newPoints : 0);
                    existingPoints.setUpdatedTime(new Date());
                    secondUserCreditMapper.updateById(existingPoints);

                    // 创建积分记录
                    SecondUserCreditRecord record = new SecondUserCreditRecord();
                    record.setUserId(userId);
                    record.setPoints(initialPoints);
                    record.setCurrentScoreCount(existingPoints.getUserPoints() + initialPoints);
                    record.setPointsType(pointsType);
                    secondUserCreditRecordService.createRecord(record);
                    return true;
                }

                log.warn("用户积分记录已存在，userId={}", userId);
                return false;
            }
            return addPointsRecord(userId, initialPoints, pointsType);
        } catch (Exception e) {
            log.error("创建用户积分记录失败，userId={}, initialPoints={}", userId, initialPoints, e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addIdInfoPoints(Integer userId) throws Exception {
        try {
            LambdaQueryWrapper<SecondUserCreditRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SecondUserCreditRecord::getUserId, userId);
            wrapper.eq(SecondUserCreditRecord::getPointsType, 2);
            if (secondUserCreditRecordMapper.selectCount(wrapper) == 0) {
                SecondUserCreditRecord record = new SecondUserCreditRecord();
                record.setUserId(userId);
                record.setPoints(200);

                LambdaQueryWrapper<SecondUserCredit> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SecondUserCredit::getUserId, userId);
                SecondUserCredit userCredit = secondUserCreditMapper.selectOne(queryWrapper);
                if (userCredit != null) {
                    secondUserCreditMapper.updatePointsByUserId(userId, 200);
                    record.setCurrentScoreCount(userCredit.getUserPoints() + 200);
                } else {
                    SecondUserCredit credit = new SecondUserCredit();
                    credit.setUserId(userId);
                    credit.setUserPoints(200);
                    record.setCurrentScoreCount(200);
                    secondUserCreditMapper.insert(credit);
                }
                record.setPointsType(2);
                secondUserCreditRecordMapper.insert(record);
            }
            return true;
        } catch (Exception e) {
            log.error("SecondUserCreditServiceImpl.addIdInfoPoints(): Error Msg={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public JSONObject isFree(Integer userId) throws Exception {
        try {
            LambdaQueryWrapper<SecondUserCredit> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SecondUserCredit::getUserId, userId);
            SecondUserCredit secondUserCredit = secondUserCreditMapper.selectOne(queryWrapper);

            JSONObject jsonObject = new JSONObject();
            if (secondUserCredit == null || secondUserCredit.getFreezeTime().after(new Date())) {
                jsonObject.put("flag", false);
                jsonObject.put("msg", "无法使用该功能");
            } else if (secondUserCredit.getFreezeTime() == null || secondUserCredit.getUserPoints() < 500) {
                jsonObject.put("flag", false);
                jsonObject.put("msg", "信用分不足无法使用该功能");
            } else  {
                jsonObject.put("flag", true);
            }

            return jsonObject;
        } catch (Exception e) {
            log.error("SecondUserCreditServiceImpl.isFree(): Error Msg={}", e.getMessage());
            throw new Exception(e);
        }
    }

    public boolean addPointsRecord(Integer userId, Integer points, Integer pointsType) {
        try {
            // 创建新的积分记录
            SecondUserCredit userPoints = new SecondUserCredit();
            userPoints.setUserId(userId);
            userPoints.setUserPoints(points != null ? points : 0);
            userPoints.setDeleteFlag(0);
            userPoints.setCreatedTime(new Date());
            userPoints.setUpdatedTime(new Date());

            int result = secondUserCreditMapper.insert(userPoints);

            // 创建积分记录
            SecondUserCreditRecord record = new SecondUserCreditRecord();
            record.setUserId(userId);
            record.setPoints(points);
            record.setCurrentScoreCount(userPoints.getUserPoints());
            record.setPointsType(pointsType);
            secondUserCreditRecordMapper.insert(record);

            return result > 0;
        } catch (Exception e) {
            log.error("删除用户积分记录失败，userId={}", userId, e);
            return false;
        }
    }


}