package com.cpop.core.service.impl;

import cn.dev33.satoken.session.SaSession;
import com.cpop.core.base.enums.OperationLogEnum;
import com.cpop.core.base.enums.UserType;
import com.cpop.core.base.table.OperationLog;
import com.cpop.core.mapper.OperationLogMapper;
import com.cpop.core.service.OperationLogService;
import com.cpop.core.utils.MessageUtils;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 操作日志表 服务层实现。
 *
 * @author DB
 * @since 2024-02-01
 */
@Service("operationLogService")
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService {

    /**
     * 插入操作日志。
     * @author DB
     * @since 2024/2/2
     * @param status 状态
     * @param operationLogEnum 日志枚举
     * @param loginUser 登陆用户
     * @param failReason 失败原因
     * @return String 主键
     */
    @Override
    public String insertOperationLog(Integer status, OperationLogEnum operationLogEnum, SaSession session, String failReason) {
        OperationLog operationLog = new OperationLog();
        operationLog.setCode(operationLogEnum.getCode())
                .setInfo(MessageUtils.message(operationLogEnum.getInfo()))
                .setDevIp(session.getString("loginIp"))
                .setOperationUserType((UserType) session.get("userType"))
                .setOperationUserName(session.getString("username"));
        if (200 == status) {
            operationLog.setOperationUserId(session.getString("userId"))
                    .setLevel(operationLogEnum.getSuccessLevel())
                    .setDescription(MessageUtils.message(operationLogEnum.getInfo()) + MessageUtils.message("i18n_baseInfo_success"))
                    .setResult(true)
                    .setActionType(1);
        } else {
            operationLog.setLevel(operationLogEnum.getExceptionLevel())
                    .setDescription(MessageUtils.message(operationLogEnum.getInfo()) + MessageUtils.message("i18n_baseInfo_failed"))
                    .setFailReason(failReason)
                    .setResult(false)
                    .setActionType(2);
        }
        if (this.save(operationLog)) {
        }
        return operationLog.getId();
    }
}
