package cn.lihongjie.coal.warehouseReceiptDetail.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.warehouseReceiptDetail.dto.CreateWarehouseReceiptDetailDto;
import cn.lihongjie.coal.warehouseReceiptDetail.dto.UpdateWarehouseReceiptDetailDto;
import cn.lihongjie.coal.warehouseReceiptDetail.dto.WarehouseReceiptDetailDto;
import cn.lihongjie.coal.warehouseReceiptDetail.entity.WarehouseReceiptDetailEntity;
import cn.lihongjie.coal.warehouseReceiptDetail.mapper.WarehouseReceiptDetailMapper;
import cn.lihongjie.coal.warehouseReceiptDetail.repository.WarehouseReceiptDetailRepository;

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 WarehouseReceiptDetailService
        extends BaseService<WarehouseReceiptDetailEntity, WarehouseReceiptDetailRepository> {
    @Autowired private WarehouseReceiptDetailRepository repository;

    @Autowired private WarehouseReceiptDetailMapper mapper;

    @Autowired private ConversionService conversionService;

    public WarehouseReceiptDetailDto create(CreateWarehouseReceiptDetailDto request) {
        WarehouseReceiptDetailEntity entity = mapper.toEntity(request);

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

    public WarehouseReceiptDetailDto update(UpdateWarehouseReceiptDetailDto request) {
        WarehouseReceiptDetailEntity 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 WarehouseReceiptDetailDto getById(String id) {
        WarehouseReceiptDetailEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

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

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