package cn.gov.customs.wxjy.demo.service.impl;

import cn.gov.customs.cacp.enhance.audit.dao.AuditLogDao;
import cn.gov.customs.cacp.enhance.audit.service.AuditLogService;
import cn.gov.customs.cacp.sdks.audit.AuditLog;
import cn.gov.customs.cacp.sdks.audit.BaseAuditLogWriter;
import cn.gov.customs.cacp.sdks.core.config.CacpAppProperties;
import cn.gov.customs.cacp.sdks.hgid.HgidGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.Executor;

@Service
@ConditionalOnProperty(
        name = {"cacp.proxy.audit.enabled"},
        havingValue = "true"
)
public class AuditLogServiceImpl extends BaseAuditLogWriter implements AuditLogService {
    private final AuditLogDao dao;
    private final HgidGenerator idGenerator;

    public AuditLogServiceImpl(RetryTemplate retryTemplate, @Qualifier("auditExecutor") Executor auditExecutor, CacpAppProperties appProperties, AuditLogDao dao, HgidGenerator idGenerator) {
        super(retryTemplate, auditExecutor, appProperties);
        this.dao = dao;
        this.idGenerator = idGenerator;
    }

    protected String innerWrite(AuditLog auditLog) {
        String logId = this.idGenerator.nextId();
        auditLog.setLogId(logId);
        this.dao.insert(auditLog);
        return logId;
    }

    public PageInfo<AuditLog> getPageList(String appCode, LocalDate begDate, LocalDate endDate, String keyword, int pageSize, int pageIndex) {
        PageHelper.startPage(pageIndex, pageSize);
        endDate = endDate.plusDays(1L);
        List<AuditLog> list = this.dao.getList(appCode, begDate, endDate, keyword);
        return PageInfo.of(list);
    }

    public AuditLog get(String logId) {
        return this.dao.get(logId);
    }
}
