package com.erp.print.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.print.dto.request.PrintRecordQueryRequest;
import com.erp.common.core.model.PageResponse;
import com.erp.print.dto.response.PrintStatisticsResponse;
import com.erp.print.entity.PrintRecord;
import com.erp.print.repository.PrintRecordRepository;
import com.erp.print.service.PrintRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class PrintRecordServiceImpl implements PrintRecordService {

    private final PrintRecordRepository recordRepository;

    @Override
    public PageResponse<PrintRecord> listRecords(Integer page, Integer limit, PrintRecordQueryRequest request) {
        Page<PrintRecord> p = new Page<>(page, limit);
        IPage<PrintRecord> result = recordRepository.selectRecordPage(p,
                request.getDocumentType(), request.getDocumentNo(),
                request.getPrintStatus(), request.getUserId(),
                request.getStartDate(), request.getEndDate());
        return PageResponse.of(result.getTotal(), page, limit, result.getRecords());
    }

    @Override
    public PrintRecord getRecordById(Long id) {
        return recordRepository.selectById(id);
    }

    @Override
    public PrintRecord getRecordByRecordNo(String recordNo) {
        return recordRepository.selectByRecordNo(recordNo);
    }

    @Override
    public PrintStatisticsResponse getStatistics() {
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDate.now().atTime(LocalTime.MAX);

        Long successCount = recordRepository.countSuccessByDate(todayStart);
        Long failedCount = recordRepository.countFailedByDate(todayStart);
        Long totalCount = successCount + failedCount;

        Double successRate = totalCount > 0 ? (double) successCount / totalCount * 100 : 0.0;

        return PrintStatisticsResponse.builder()
                .todaySuccessCount(successCount)
                .todayFailedCount(failedCount)
                .todayTotalCount(totalCount)
                .successRate(Math.round(successRate * 100.0) / 100.0)
                .avgDuration(0L)
                .pendingTaskCount(0L)
                .processingTaskCount(0L)
                .build();
    }

    @Override
    @Transactional
    public void createRecord(PrintRecord record) {
        recordRepository.insert(record);
    }
}
