package cn.lihongjie.coal.coalPrice.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.coalPrice.dto.CoalPriceDto;
import cn.lihongjie.coal.coalPrice.dto.CreateCoalPriceDto;
import cn.lihongjie.coal.coalPrice.dto.UpdateCoalPriceDto;
import cn.lihongjie.coal.coalPrice.entity.CoalPriceEntity;
import cn.lihongjie.coal.coalPrice.mapper.CoalPriceMapper;
import cn.lihongjie.coal.coalPrice.repository.CoalPriceRepository;

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 CoalPriceService extends BaseService<CoalPriceEntity, CoalPriceRepository> {
    @Autowired private CoalPriceRepository repository;

    @Autowired private CoalPriceMapper mapper;

    @Autowired private ConversionService conversionService;

    public CoalPriceDto create(CreateCoalPriceDto request) {
        CoalPriceEntity entity = mapper.toEntity(request);

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

    public CoalPriceDto update(UpdateCoalPriceDto request) {
        CoalPriceEntity 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 CoalPriceDto getById(String id) {
        CoalPriceEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

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

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