package com.fs.live.service.impl;

import com.fs.common.constant.LiveKeysConstant;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.live.domain.LiveCommentFeatureConfig;
import com.fs.live.domain.LiveFloatMsgLog;
import com.fs.live.domain.LiveMsg;
import com.fs.live.domain.LiveWatchUser;
import com.fs.live.mapper.LiveMsgMapper;
import com.fs.live.service.ILiveCommentFeatureConfigService;
import com.fs.live.service.ILiveCommentFloatScreenService;
import com.fs.live.service.ILiveFloatMsgLogService;
import com.fs.live.service.ILiveWatchUserService;
import com.fs.company.mapper.CompanyUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LiveCommentFloatScreenServiceImpl implements ILiveCommentFloatScreenService {

    @Autowired
    private ILiveCommentFeatureConfigService featureConfigService;
    @Autowired
    private ILiveFloatMsgLogService floatMsgLogService;
    @Autowired
    private LiveMsgMapper liveMsgMapper;
    @Autowired
    private ILiveWatchUserService liveWatchUserService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CompanyUserRoleMapper companyUserRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R handleFloatScreen(Long liveId, Long userId, String nickName, String avatar, String msg,
                               String liveRoleCode, Long companyUserId) {
        LiveCommentFeatureConfig cfg = featureConfigService.getEffectiveConfig();
        if (cfg.getFloatEnabled() == null || cfg.getFloatEnabled() != 1) {
            return R.error("飘屏功能未开放");
        }
        Long checkUserId = (companyUserId != null && companyUserId > 0) ? companyUserId : userId;
        if (!hasAnyRoleRelation(checkUserId)) {
            return R.error("无飘屏权限");
        }
        String cooldownKey = String.format(LiveKeysConstant.LIVE_FLOAT_COOLDOWN, liveId, userId);
        if (redisCache.getCacheObject(cooldownKey) != null) {
            return R.error("飘屏冷却中，请稍后再试");
        }
        List<LiveWatchUser> wu = liveWatchUserService.getByLiveIdAndUserId(liveId, userId);
        if (!wu.isEmpty() && wu.get(0).getMsgStatus() != null && wu.get(0).getMsgStatus() == 1) {
            return R.error("你已被禁言");
        }
        Map<String, Integer> flagMap = liveWatchUserService.getLiveFlagWithCache(liveId);
        LiveMsg liveMsg = new LiveMsg();
        liveMsg.setLiveId(liveId);
        liveMsg.setUserId(userId);
        liveMsg.setNickName(nickName);
        liveMsg.setAvatar(avatar);
        liveMsg.setMsg(msg);
        liveMsg.setCreateTime(new Date());
        liveMsg.setLiveFlag(flagMap.get("liveFlag"));
        liveMsg.setReplayFlag(flagMap.get("replayFlag"));
        liveMsgMapper.insertLiveMsg(liveMsg);

        LiveFloatMsgLog log = new LiveFloatMsgLog();
        log.setLiveId(liveId);
        log.setUserId(userId);
        log.setNickName(nickName);
        log.setMsgId(liveMsg.getMsgId());
        log.setLiveRoleCode(liveRoleCode);
        log.setMsgContent(msg);
        floatMsgLogService.insertLog(log);

        int sec = cfg.getFloatCooldownSec() != null && cfg.getFloatCooldownSec() > 0 ? cfg.getFloatCooldownSec() : 60;
        redisCache.setCacheObject(cooldownKey, 1, sec, TimeUnit.SECONDS);

        return R.ok().put("liveMsg", liveMsg);
    }

    private boolean hasAnyRoleRelation(Long companyUserId) {
        if (companyUserId == null || companyUserId <= 0) {
            return false;
        }
        return companyUserRoleMapper.countByUserId(companyUserId) > 0;
    }
}
