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

import cn.hutool.core.collection.CollUtil;
import com.cico.nest.lcdp.boot.core.system.convert.logger.OperateLogConvert;
import com.cico.nest.lcdp.boot.core.system.service.logger.OperateLogService;
import com.cico.nest.lcdp.boot.core.system.service.user.AdminUserService;
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.boot.web.core.util.WebFrameworkUtils;
import com.cico.nest.lcdp.framework.api.logger.LcdpOperateLogApi;
import com.cico.nest.lcdp.framework.api.logger.dto.*;
import com.cico.nest.lcdp.framework.common.enums.UserTypeEnum;
import com.cico.nest.lcdp.framework.common.pojo.PageResult;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Objects;

import static com.cico.nest.lcdp.framework.common.util.collection.CollectionUtils.convertSet;


/**
 * 操作日志 API 实现类
 *
 * @author zws
 */
@Service
@Validated
public class LcdpOperateLogApiImpl implements LcdpOperateLogApi {

    @Resource
    private OperateLogService operateLogService;
    @Resource
    private AdminUserService adminUserService;

    @Override
    @Async
    public void createOperateLog(LcdpOperateLogCreateDTO createReqDTO) {
        operateLogService.createOperateLog(createReqDTO);
    }

    @Override
    @Async
    public void createOperateLogV2(LcdpOperateLogV2CreateDTO createReqDTO) {
        operateLogService.createOperateLogV2(createReqDTO);
    }

    @Override
    public PageResult<LcdpOperateLogV2DTO> getOperateLogPage(LcdpOperateLogV2PageDTO pageReqVO) {
        PageResult<OperateLogV2DO> operateLogPage = operateLogService.getOperateLogPage(pageReqVO);
        if (CollUtil.isEmpty(operateLogPage.getList())) {
            return PageResult.empty();
        }

        // 获取用户
        List<AdminUserDO> userList = adminUserService.getUserList(
                convertSet(operateLogPage.getList(), OperateLogV2DO::getUserId));
        return OperateLogConvert.INSTANCE.convertPage(operateLogPage, userList);
    }

    @Override
    public boolean isOperateLogOpen() {
        //目前，只有管理员，才记录操作日志！所以非管理员，直接调用，不进行记录
        Integer userType = WebFrameworkUtils.getLoginUserType();
        return Objects.equals(userType, UserTypeEnum.ADMIN.getValue());
    }

    @Override
    public LcdpOperateLogUserInfoDTO getOperateLogUserInfo() {
        LcdpOperateLogUserInfoDTO userInfo = new LcdpOperateLogUserInfoDTO();
        userInfo.setUserId(String.valueOf(WebFrameworkUtils.getLoginUserId()));
        userInfo.setUserType(WebFrameworkUtils.getLoginUserType());
        return userInfo;
    }

}
