package com.ruoyi.cai.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.domain.UserErrorLog;
import com.ruoyi.cai.dto.admin.UserForbidDTO;
import com.ruoyi.cai.dto.admin.vo.UserErrorLogAdminVo;
import com.ruoyi.cai.dto.app.query.push.PushErrorReq;
import com.ruoyi.cai.enums.ForbidTimeEnum;
import com.ruoyi.cai.enums.ForbidTypeEnum;
import com.ruoyi.cai.enums.user.UserErrorLogHomeIndexEnum;
import com.ruoyi.cai.enums.user.UserErrorLogType;
import com.ruoyi.cai.manager.UserForbidManager;
import com.ruoyi.cai.mapper.UserErrorLogMapper;
import com.ruoyi.cai.service.LowHeightRiskService;
import com.ruoyi.cai.service.UserErrorLogService;
import com.ruoyi.common.core.domain.PageQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 用户异常记录Service业务层处理
 *
 * @author 77
 * @date 2024-01-22
 */
@Service
@Slf4j
public class UserErrorLogServiceImpl extends ServiceImpl<UserErrorLogMapper,UserErrorLog> implements UserErrorLogService {

    @Autowired
    private LowHeightRiskService lowHeightRiskService;
    @Autowired
    private UserForbidManager userForbidManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushError(PushErrorReq req) {
        UserErrorLogType logType = UserErrorLogType.getByCode(req.getType());
        if(logType == null){
            log.error("记录高危风险失败，参数异常! req={}", JSON.toJSONString(req));
            return;
        }
        if(req.getHomeIndex() == null){
            req.setHomeIndex(UserErrorLogHomeIndexEnum.OTHER.getCode());
        }
        UserErrorLog log = new UserErrorLog();
        log.setType(req.getType());
        log.setUserId(req.getUserId());
        log.setHomeIndex(req.getHomeIndex());
        this.save(log);
        lowHeightRiskService.incsNum(log);
        // 记录风险
        if(UserErrorLogHomeIndexEnum.VIDEO.getCode().equals(log.getHomeIndex())){ // 直播的直接封号
            String remark = String.format("于%s 直播期间%s封10年",
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                    logType.getName());
            UserForbidDTO dto = new UserForbidDTO();
            dto.setForbidTime(ForbidTimeEnum.YEAR_10.getCode());
            dto.setForbidType(ForbidTypeEnum.USER.getCode());
            dto.setMember(req.getUserId()+"");
            dto.setRemark(remark);
            userForbidManager.forbid(dto);
        }
    }

    @Override
    public Page<UserErrorLogAdminVo> pageAdmin(PageQuery pageQuery, UserErrorLogAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(),bo);
    }
}
