package cn.lihongjie.coal.enterprise.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.enterprise.dto.CreateEnterpriseDto;
import cn.lihongjie.coal.enterprise.dto.EnterpriseDto;
import cn.lihongjie.coal.enterprise.dto.UpdateEnterpriseDto;
import cn.lihongjie.coal.enterprise.entity.EnterpriseEntity;
import cn.lihongjie.coal.enterprise.mapper.EnterpriseMapper;
import cn.lihongjie.coal.enterprise.repository.EnterpriseRepository;

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 EnterpriseService extends BaseService<EnterpriseEntity, EnterpriseRepository> {
    @Autowired private EnterpriseRepository repository;

    @Autowired private EnterpriseMapper mapper;

    @Autowired private ConversionService conversionService;

    public EnterpriseDto create(CreateEnterpriseDto request) {
        EnterpriseEntity entity = mapper.toEntity(request);

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

    public EnterpriseDto update(UpdateEnterpriseDto request) {
        EnterpriseEntity 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 EnterpriseDto getById(String id) {
        EnterpriseEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

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

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