package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import shop.alien.entity.storePlatform.StorePlatformOperationLog;
import shop.alien.mapper.StorePlatformOperationLogMapper;
import shop.alien.storeplatform.service.PlatformOperationLogService;
import shop.alien.storeplatform.util.LoginUserUtil;

import java.util.Date;
import java.util.Collections;

/**
 * 平台操作记录服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PlatformOperationLogServiceImpl implements PlatformOperationLogService {

    private final StorePlatformOperationLogMapper storePlatformOperationLogMapper;

    @Override
    public void save(StorePlatformOperationLog logRecord) {
        try {
            storePlatformOperationLogMapper.insert(logRecord);
        } catch (Exception e) {
            log.warn("保存平台操作记录失败: {}", e.getMessage(), e);
        }
    }

    @Override
    public IPage<StorePlatformOperationLog> getOperationLogPage(int page, int size, String module, String account, Date startTime, Date endTime) {
        Page<StorePlatformOperationLog> pageInfo = new Page<>(page, size);
        Integer storeId = LoginUserUtil.getCurrentStoreId();
        if (storeId == null) {
            pageInfo.setRecords(Collections.emptyList());
            pageInfo.setTotal(0);
            return pageInfo;
        }
        LambdaQueryWrapper<StorePlatformOperationLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StorePlatformOperationLog::getStoreId, storeId);
        if (StringUtils.hasText(module)) {
            wrapper.eq(StorePlatformOperationLog::getOperationModule, module);
        }
        if (StringUtils.hasText(account)) {
            wrapper.like(StorePlatformOperationLog::getOperatorAccount, account);
        }
        if (startTime != null) {
            wrapper.ge(StorePlatformOperationLog::getOperationTime, startTime);
        }
        if (endTime != null) {
            wrapper.le(StorePlatformOperationLog::getOperationTime, endTime);
        }
        wrapper.orderByDesc(StorePlatformOperationLog::getOperationTime);
        return storePlatformOperationLogMapper.selectPage(pageInfo, wrapper);
    }
}
