package cn.lihongjie.coal.excelGeneratorSheetInfo.service;

import cn.lihongjie.coal.base.dto.CommonQuery;
import cn.lihongjie.coal.base.dto.IdRequest;
import cn.lihongjie.coal.base.service.BaseService;
import cn.lihongjie.coal.excelGeneratorSheetInfo.dto.CreateExcelGeneratorSheetInfoDto;
import cn.lihongjie.coal.excelGeneratorSheetInfo.dto.ExcelGeneratorSheetInfoDto;
import cn.lihongjie.coal.excelGeneratorSheetInfo.dto.UpdateExcelGeneratorSheetInfoDto;
import cn.lihongjie.coal.excelGeneratorSheetInfo.entity.ExcelGeneratorSheetInfoEntity;
import cn.lihongjie.coal.excelGeneratorSheetInfo.mapper.ExcelGeneratorSheetInfoMapper;
import cn.lihongjie.coal.excelGeneratorSheetInfo.repository.ExcelGeneratorSheetInfoRepository;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class ExcelGeneratorSheetInfoService
        extends BaseService<ExcelGeneratorSheetInfoEntity, ExcelGeneratorSheetInfoRepository> {
    @Autowired private ExcelGeneratorSheetInfoRepository repository;

    @Autowired private ExcelGeneratorSheetInfoMapper mapper;

    @Autowired private ConversionService conversionService;

    public ExcelGeneratorSheetInfoDto create(CreateExcelGeneratorSheetInfoDto request) {
        ExcelGeneratorSheetInfoEntity entity = mapper.toEntity(request);

        this.repository.save(entity);
        return getById(entity.getId());
    }

    public ExcelGeneratorSheetInfoDto update(UpdateExcelGeneratorSheetInfoDto request) {
        ExcelGeneratorSheetInfoEntity entity = this.repository.get(request.getId());
        this.mapper.updateEntity(entity, request);

        this.repository.save(entity);

        return getById(entity.getId());
    }

    public void delete(IdRequest request) {
        this.repository.deleteAllById(request.getIds());
    }

    public ExcelGeneratorSheetInfoDto getById(String id) {
        ExcelGeneratorSheetInfoEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

    public Page<ExcelGeneratorSheetInfoDto> list(CommonQuery query) {
        Page<ExcelGeneratorSheetInfoEntity> page =
                repository.findAll(
                        query.specification(conversionService),
                        PageRequest.of(
                                query.getPageNo(),
                                query.getPageSize(),
                                Sort.by(query.getOrders())));

        return page.map(this.mapper::toDto);
    }
}
