package cn.lihongjie.coal.employeeHis.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.dbFunctions.DbFunctionService;
import cn.lihongjie.coal.employeeHis.dto.CreateEmployeeHisDto;
import cn.lihongjie.coal.employeeHis.dto.EmployeeHisDto;
import cn.lihongjie.coal.employeeHis.dto.UpdateEmployeeHisDto;
import cn.lihongjie.coal.employeeHis.entity.EmployeeHisEntity;
import cn.lihongjie.coal.employeeHis.mapper.EmployeeHisMapper;
import cn.lihongjie.coal.employeeHis.repository.EmployeeHisRepository;
import cn.lihongjie.coal.exception.BizException;

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 EmployeeHisService extends BaseService<EmployeeHisEntity, EmployeeHisRepository> {
    @Autowired private EmployeeHisRepository repository;

    @Autowired private EmployeeHisMapper mapper;

    @Autowired private ConversionService conversionService;

    @Autowired private DbFunctionService dbFunctionService;

    public EmployeeHisDto create(CreateEmployeeHisDto request) {
        EmployeeHisEntity entity = mapper.toEntity(request);

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

    public EmployeeHisDto update(UpdateEmployeeHisDto request) {
        EmployeeHisEntity entity = this.repository.get(request.getId());
        this.mapper.updateEntity(entity, request);

        this.repository.save(entity);

        return getById(entity.getId());
    }

    public void delete(IdRequest request) {
        boolean linked = this.repository.isLinked(request.getIds());

        if (linked) {
            throw new BizException("数据已被关联，无法删除");
        }

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

    public EmployeeHisDto getById(String id) {
        EmployeeHisEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

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

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