package com.crm.globex.service.impl;

import com.crm.globex.dao.repository.CustomLoginAssetManagementRepository;
import com.crm.globex.service.CustomLoginAssetManagementService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.StatusConstants;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.entity.custom.login.asset.management.CustomLoginAssetManagementAddEntity;
import com.crm.rely.backend.model.pojo.table.CustomLoginAssetManagementTable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description:
 * @author: houn
 * @create: 2020-07-31 23:03
 **/
@Service
public class CustomLoginAssetManagementServiceImpl implements CustomLoginAssetManagementService {

    @Autowired
    private CustomLoginAssetManagementRepository customLoginAssetManagementRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(CustomLoginAssetManagementAddEntity entity) throws ServiceException {
        existLogin(entity);
        CustomLoginAssetManagementTable customLoginAssetManagementTable = new CustomLoginAssetManagementTable();
        BeanUtils.copyProperties(entity, customLoginAssetManagementTable);
        customLoginAssetManagementTable.setStatus(StatusConstants.APPLY_PENDING_STATUS);
        customLoginAssetManagementRepository.save(customLoginAssetManagementTable);
    }

    @Override
    public CustomLoginAssetManagementTable getByCustomIdAndLogin(Long customId, Long login) throws ServiceException {
        return customLoginAssetManagementRepository.getFirstByCustomIdAndLogin(customId, login);
    }

    @Override
    public boolean existByCustomIdAndLogin(Long customId, Long login) throws ServiceException {
        return customLoginAssetManagementRepository.existsByCustomIdAndLogin(customId, login);
    }


    private void existLogin(CustomLoginAssetManagementAddEntity entity) throws ServiceException {
        boolean bl = customLoginAssetManagementRepository.existsByLogin(entity.getLogin());
        if (bl) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
    }
}
