package com.xindazhou.business.service.community.ban;

import com.xindazhou.business.controller.admin.community.ban.vo.BanPageReqVO;
import com.xindazhou.business.controller.admin.community.ban.vo.BanRespVO;
import com.xindazhou.business.controller.admin.community.ban.vo.BanSaveReqVO;
import com.xindazhou.business.convert.community.ban.BanConvert;
import com.xindazhou.business.dal.community.dataobject.ban.BanDO;
import com.xindazhou.business.dal.community.mysql.ban.BanMapper;
import com.xindazhou.framework.common.exception.util.ServiceExceptionUtil;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xindazhou.user.api.user.MemberUserApi;
import com.xindazhou.user.api.user.dto.MemberUserRespDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.xindazhou.framework.common.exception.enums.GlobalErrorCodeConstants.NOT_FOUND;

/**
 * 封禁 Service 实现类
 *
 * @author xindazhou
 */
@Service("communityBanServiceImpl")
@Validated
@Slf4j
public class BanServiceImpl implements BanService {

    @Resource
    private BanMapper banMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createBan(BanSaveReqVO createReqVO) {
        // 检查用户是否已封禁
        BanDO existBan = banMapper.selectOne(new LambdaQueryWrapperX<BanDO>()
                .eq(BanDO::getUserId, createReqVO.getUserId()));
        if (existBan != null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "用户已被封禁");
        }
        
        // 获取用户昵称
        String userNickname = null;
        try {
            MemberUserRespDTO user = memberUserApi.getUser(createReqVO.getUserId()).getCheckedData();
            if (user != null) {
                userNickname = user.getNickname();
            }
        } catch (Exception e) {
            log.warn("获取用户信息失败", e);
        }
        
        // 插入封禁
        BanDO ban = BanConvert.INSTANCE.convert(createReqVO);
        ban.setUserNickname(userNickname);
        if (createReqVO.getIsIndefinite() != null && createReqVO.getIsIndefinite()) {
            ban.setBanEndTime(null);
            ban.setIsIndefinite(true);
        } else {
            ban.setIsIndefinite(false);
        }
        banMapper.insert(ban);
        return ban.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBan(BanSaveReqVO updateReqVO) {
        // 校验存在
        BanDO existBan = banMapper.selectOne(new LambdaQueryWrapperX<BanDO>()
                .eq(BanDO::getUserId, updateReqVO.getUserId()));
        if (existBan == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "封禁记录不存在");
        }
        
        // 更新
        BanDO updateObj = BanConvert.INSTANCE.convert(updateReqVO);
        updateObj.setId(existBan.getId());
        if (updateReqVO.getIsIndefinite() != null && updateReqVO.getIsIndefinite()) {
            updateObj.setBanEndTime(null);
            updateObj.setIsIndefinite(true);
        } else {
            updateObj.setIsIndefinite(false);
        }
        banMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbanUser(Long userId) {
        BanDO ban = banMapper.selectOne(new LambdaQueryWrapperX<BanDO>()
                .eq(BanDO::getUserId, userId));
        if (ban == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "封禁记录不存在");
        }
        // 删除封禁记录
        banMapper.deleteById(ban.getId());
    }

    @Override
    public BanRespVO getBan(Long userId) {
        BanDO ban = banMapper.selectOne(new LambdaQueryWrapperX<BanDO>()
                .eq(BanDO::getUserId, userId));
        if (ban == null) {
            return null;
        }
        return BanConvert.INSTANCE.convert(ban);
    }

    @Override
    public PageResult<BanRespVO> getBanPage(BanPageReqVO pageReqVO) {
        LambdaQueryWrapperX<BanDO> queryWrapper = new LambdaQueryWrapperX<BanDO>()
                .eqIfPresent(BanDO::getUserId, pageReqVO.getUserId())
                .likeIfPresent(BanDO::getUserNickname, pageReqVO.getUsername())
                .likeIfPresent(BanDO::getBanReason, pageReqVO.getBanReason())
                .betweenIfPresent(BanDO::getBanStartTime, pageReqVO.getBanStartTimeStart(), pageReqVO.getBanStartTimeEnd())
                .orderByDesc(BanDO::getCreateTime);
        PageResult<BanDO> pageResult = banMapper.selectPage(pageReqVO, queryWrapper);
        return BanConvert.INSTANCE.convertPage(pageResult);
    }

}

