package com.cico.nest.lcdp.boot.core.system.convert.logger;

import com.cico.nest.lcdp.boot.core.system.controller.admin.logger.vo.operatelog.OperateLogRespVO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.logger.OperateLogDO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.logger.OperateLogV2DO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.user.AdminUserDO;
import com.cico.nest.lcdp.framework.api.logger.dto.LcdpOperateLogV2DTO;
import com.cico.nest.lcdp.framework.common.pojo.PageResult;
import com.cico.nest.lcdp.framework.common.util.collection.CollectionUtils;
import com.cico.nest.lcdp.framework.common.util.object.BeanUtils;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.List;
import java.util.Map;

import static com.cico.nest.lcdp.framework.common.util.collection.CollectionUtils.convertMap;
import static com.cico.nest.lcdp.framework.common.util.collection.MapUtils.findAndThen;


@Mapper
public interface OperateLogConvert {

    OperateLogConvert INSTANCE = Mappers.getMapper(OperateLogConvert.class);

    default List<OperateLogRespVO> convertList(List<OperateLogDO> list, Map<Long, AdminUserDO> userMap) {
        return CollectionUtils.convertList(list, log -> {
            OperateLogRespVO logVO = BeanUtils.toBean(log, OperateLogRespVO.class);
            findAndThen(userMap, log.getUserId(), user -> logVO.setUserNickname(user.getNickname()));
            return logVO;
        });
    }

    default PageResult<LcdpOperateLogV2DTO> convertPage(PageResult<OperateLogV2DO> operateLogPage, List<AdminUserDO> userList) {
        return BeanUtils.toBean(operateLogPage, LcdpOperateLogV2DTO.class).setList(setUserInfo(operateLogPage.getList(), userList));
    }

    LcdpOperateLogV2DTO convert(OperateLogV2DO operateLogV2DO);

    default List<LcdpOperateLogV2DTO> setUserInfo(List<OperateLogV2DO> logList, List<AdminUserDO> userList) {
        Map<Long, AdminUserDO> userMap = convertMap(userList, AdminUserDO::getId);
        return CollectionUtils.convertList(logList, item -> {
            LcdpOperateLogV2DTO respDTO = convert(item);
            findAndThen(userMap, item.getUserId(), user -> respDTO.setUserName(user.getNickname()));
            return respDTO;
        });
    }

}
