package cn.lihongjie.coal.deliveryInformation.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.deliveryInformation.dto.CreateDeliveryInformationDto;
import cn.lihongjie.coal.deliveryInformation.dto.DeliveryInformationDto;
import cn.lihongjie.coal.deliveryInformation.dto.UpdateDeliveryInformationDto;
import cn.lihongjie.coal.deliveryInformation.entity.DeliveryInformationEntity;
import cn.lihongjie.coal.deliveryInformation.mapper.DeliveryInformationMapper;
import cn.lihongjie.coal.deliveryInformation.repository.DeliveryInformationRepository;

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 DeliveryInformationService
        extends BaseService<DeliveryInformationEntity, DeliveryInformationRepository> {
    @Autowired private DeliveryInformationRepository repository;

    @Autowired private DeliveryInformationMapper mapper;

    @Autowired private ConversionService conversionService;

    public DeliveryInformationDto create(CreateDeliveryInformationDto request) {
        DeliveryInformationEntity entity = mapper.toEntity(request);

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

    public DeliveryInformationDto update(UpdateDeliveryInformationDto request) {
        DeliveryInformationEntity 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 DeliveryInformationDto getById(String id) {
        DeliveryInformationEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

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

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