package org.xyzh.system.service.log.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xyzh.api.system.log.OperationLogService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.dto.system.TbSysOperationLog;
import org.xyzh.common.vo.UserDeptRoleVO;
import org.xyzh.system.mapper.SysOperationLogMapper;
import org.xyzh.system.utils.LoginUtil;

import java.util.List;

/**
 * @description 操作日志服务实现
 * @filename SysOperationLogServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-30
 */
@Service
public class SysOperationLogServiceImpl implements OperationLogService {

    @Autowired
    private SysOperationLogMapper operationLogMapper;

    @Override
    public ResultDomain<TbSysOperationLog> selectOperationLogPage(TbSysOperationLog operationLog, PageParam pageParam) {
        ResultDomain<TbSysOperationLog> result = new ResultDomain<>();
        
        try {
            // 获取当前用户的部门角色信息（用于权限过滤）
            List<UserDeptRoleVO> userDeptRoles = LoginUtil.getCurrentDeptRole();
            
            // 分页查询操作日志
            List<TbSysOperationLog> logs = operationLogMapper.selectOperationLogPage(operationLog, pageParam, userDeptRoles);
            
            // 统计总数（带权限过滤）
            int count = operationLogMapper.countOperationLog(operationLog, userDeptRoles);
            pageParam.setTotalElements(count);
            pageParam.setTotalPages((int) Math.ceil((double) count / pageParam.getPageSize()));
            
            // 构建分页结果
            PageDomain<TbSysOperationLog> pageDomain = new PageDomain<>();
            pageDomain.setPageParam(pageParam);
            pageDomain.setDataList(logs);
            
            result.success("查询成功", pageDomain);
        } catch (Exception e) {
            result.fail("查询失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public int countOperationLog(TbSysOperationLog operationLog) {
        // 获取当前用户的部门角色信息（用于权限过滤）
        List<UserDeptRoleVO> userDeptRoles = LoginUtil.getCurrentDeptRole();
        return operationLogMapper.countOperationLog(operationLog, userDeptRoles);
    }
}
