package cn.lihongjie.coal.warehouseSupplier.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.exception.BizException;
import cn.lihongjie.coal.warehouseSupplier.dto.CreateWarehouseSupplierDto;
import cn.lihongjie.coal.warehouseSupplier.dto.UpdateWarehouseSupplierDto;
import cn.lihongjie.coal.warehouseSupplier.dto.WarehouseSupplierDto;
import cn.lihongjie.coal.warehouseSupplier.entity.WarehouseSupplierEntity;
import cn.lihongjie.coal.warehouseSupplier.mapper.WarehouseSupplierMapper;
import cn.lihongjie.coal.warehouseSupplier.repository.WarehouseSupplierRepository;

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 WarehouseSupplierService
        extends BaseService<WarehouseSupplierEntity, WarehouseSupplierRepository> {
    @Autowired private WarehouseSupplierRepository repository;

    @Autowired private WarehouseSupplierMapper mapper;

    @Autowired private ConversionService conversionService;

    public WarehouseSupplierDto create(CreateWarehouseSupplierDto request) {
        WarehouseSupplierEntity entity = mapper.toEntity(request);

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

    public WarehouseSupplierDto update(UpdateWarehouseSupplierDto request) {
        WarehouseSupplierEntity entity = this.repository.get(request.getId());
        this.mapper.updateEntity(entity, request);

        this.repository.save(entity);

        return getById(entity.getId());
    }

    public void delete(IdRequest request) {

        if (this.repository.isLinked(request.getIds())) {
            throw new BizException("删除失败，该供应商已被使用");
        }


        this.repository.deleteAllById(request.getIds());
    }

    public WarehouseSupplierDto getById(String id) {
        WarehouseSupplierEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

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

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