package com.bcxin.tenant.domain.services.impls;

import com.bcxin.Infrastructures.TenantContext;
import com.bcxin.Infrastructures.TenantUserContext;
import com.bcxin.Infrastructures.exceptions.ForbidTenantException;
import com.bcxin.api.interfaces.tenants.requests.organizationType.OrganizationTypeCreateRequest;
import com.bcxin.api.interfaces.tenants.requests.organizationType.OrganizationTypeUpdateRequest;
import com.bcxin.tenant.domain.entities.OrganizationTypeEntity;
import com.bcxin.tenant.domain.repositories.OrganizationTypeRepository;
import com.bcxin.tenant.domain.services.OrganizationTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class OrganizationTypeServiceImpl implements OrganizationTypeService {

    private final Logger logger = LoggerFactory.getLogger(OrganizationTypeServiceImpl.class);

    private OrganizationTypeRepository organizationTypeRepository;

    public OrganizationTypeServiceImpl(OrganizationTypeRepository organizationTypeRepository) {
        this.organizationTypeRepository = organizationTypeRepository;
    }


    @Override
    public void save(OrganizationTypeCreateRequest request) {
        /**
         * 当前操作者, 可以为当前用户/也可以是固定后台用户
         */
        TenantUserContext.UserModel currentUser = TenantContext.getInstance().getUserContext().get();
        if (currentUser == null) {
            throw new ForbidTenantException("必须有人来操作离职");
        }
        OrganizationTypeEntity tenantOrganizationTypeEntity =
                OrganizationTypeEntity.create(request.getName(), request.getNote(), request.getOrganizationId(),
                        currentUser.getId(), currentUser.getId());
        organizationTypeRepository.save(tenantOrganizationTypeEntity);
    }

    @Override
    public void delete(long id) {
        organizationTypeRepository.deleteById(id);
    }

    @Override
    public void update(OrganizationTypeUpdateRequest organizationTypeUpdateRequest) {
        OrganizationTypeEntity tenantOrganizationTypeEntity=organizationTypeRepository.findById(organizationTypeUpdateRequest.getId());
        tenantOrganizationTypeEntity.change(organizationTypeUpdateRequest.getName(),
                    organizationTypeUpdateRequest.getNote(),
                    organizationTypeUpdateRequest.getOrganizationId());
        organizationTypeRepository.save(tenantOrganizationTypeEntity);
    }

    @Override
    public OrganizationTypeEntity findById(long id) {
        return organizationTypeRepository.findById(id);
    }

    @Override
    public Collection<OrganizationTypeEntity> findByOrganizationId(String organizationId) {
        return organizationTypeRepository.findByOrganizationId(organizationId);
    }
}
