package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.cultivate.mapper.CultivateCoverInfoMapper;
import jnpf.cultivate.service.CultivateCoverInfoService;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.po.common.FtbCultivateCoverInfoEntity;
import jnpf.model.cultivate.v2.exam.req.V2QueryCoverReq;
import jnpf.model.cultivate.v2.exam.req.V2SaveCoverReq;
import jnpf.model.cultivate.v2.exam.vo.V2CoverVo;
import jnpf.permission.entity.UserEntity;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Desc 封面-实现类
 * @Author shangyi
 * @Date 2026/1/22
 */
@Slf4j
@Service
public class CultivateCoverInfoServiceImpl extends ServiceImpl<CultivateCoverInfoMapper, FtbCultivateCoverInfoEntity> implements CultivateCoverInfoService {


    @Autowired
    private UserApiV2Util userApiV2Util;


    @Override
    public void saveCover(V2SaveCoverReq req) {

        FtbCultivateCoverInfoEntity entity = new FtbCultivateCoverInfoEntity();
        entity.setIsSystem(0);
        entity.setCategoryId(req.getCategoryId());
        entity.setPath(req.getPath());
        entity.setLastModifyTime(new Date());
        entity.setLastModifyUserId(UserProvider.getLoginUserId());
        if (StringUtil.isNotEmpty(req.getId())) {
            FtbCultivateCoverInfoEntity old = getById(req.getId());
            if (old == null) {
                throw new RuntimeException("封面不存在");
            }
            if (old.getIsSystem().equals(1)) {
                throw new RuntimeException("系统内置封面不允许修改");
            }
            entity.setId(req.getId());
            updateById(entity);
            return;
        }
        save(entity);
    }

    @Override
    public Page<V2CoverVo> getPageList(V2QueryCoverReq req) {
        //构建分页
        Page<V2CoverVo> page = Page.of(req.getCurrentPage(), req.getPageSize());
        //根据分类id查询分页列表
        page = baseMapper.getPageList(page, req);

        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<String> userIds = page.getRecords().stream().map(V2CoverVo::getUserId).distinct().collect(Collectors.toList());
            Map<String, UserEntity> userNameForUserIds = userApiV2Util.getUserNameAndCopyForUserIds(userIds);
            for (V2CoverVo record : page.getRecords()) {
                UserEntity userEntity = userNameForUserIds.get(record.getUserId());
                if (userEntity != null) {
                    record.setUserName(userEntity.getRealName());
                }
            }
        }
        return page;
    }
}
