package com.jsc.oscm.service;

import com.jsc.oscm.dao.DataPackageLogRepository;
import com.jsc.oscm.dao.DataPackageRepository;
import com.jsc.oscm.entity.DataPackage;
import com.jsc.oscm.entity.DataPackageLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class DataPackageService {
    @Resource
    private DataPackageRepository dataPackageRepository;

    @Resource
    private DataPackageLogRepository dataPackageLogRepository;

    public Page<DataPackage> getPackageList(Pageable pageable) {
        return dataPackageRepository.findAll(pageable);
    }

    public Page<DataPackageLog> getLogList(Pageable pageable) {
        return dataPackageLogRepository.findAll(pageable);
    }

    public void addPackage(DataPackage dataPackage) {
        dataPackage.setCreateTime(LocalDateTime.now());
        dataPackageRepository.save(dataPackage);
    }

    public void addLog(String packageName, String operationType, HttpServletRequest request) {
        DataPackageLog log = new DataPackageLog();
        log.setPackageName(packageName);
        log.setOperationType(operationType);
        log.setOperationTime(LocalDateTime.now());
        log.setUserIp(request.getRemoteAddr());
        log.setUserAgent(request.getHeader("User-Agent"));
        // 可以从SecurityContext中获取当前用户
        // Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // log.setUserName(authentication.getName());
        dataPackageLogRepository.save(log);
    }

    public DataPackage getPackageById(Integer id) {
        return dataPackageRepository.findById(id).orElse(null);
    }
}