package com.nbport.zgwl.contractlog.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbport.zgwl.common.PageResult;
import com.nbport.zgwl.contractlog.dto.ContractLogDto;
import com.nbport.zgwl.contractlog.dto.ContractLogQueryDto;
import com.nbport.zgwl.contractlog.mapper.ContractLogMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ContractLogServiceImpl implements ContractLogService {

    private final ContractLogMapper contractLogMapper;

    @Override
    public PageResult<ContractLogDto> queryPage(ContractLogQueryDto queryDto) {
        Page<ContractLogDto> page = new Page<>(queryDto.getPageNo(), queryDto.getPageSize());
        Page<ContractLogDto> resultPage = (Page<ContractLogDto>) contractLogMapper.selectLogPage(page, queryDto);
        return new PageResult<>(resultPage);
    }

    @Override
    public List<ContractLogDto> queryList(ContractLogQueryDto queryDto) {
        return contractLogMapper.selectLogList(queryDto);
    }

    @Override
    public byte[] exportExcel(ContractLogQueryDto queryDto) {
        List<ContractLogDto> list = queryList(queryDto);
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            EasyExcel.write(outputStream, ContractLogDto.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("合同日志")
                    .doWrite(list);
            return outputStream.toByteArray();
        } catch (Exception ex) {
            throw new RuntimeException("导出日志失败", ex);
        }
    }
}
