package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.CustomLoginSpecialCalcMapper;
import com.crm.manager.dao.repository.CustomLoginSpecialCalcRepository;
import com.crm.manager.service.CustomLoginSpecialCalcService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.*;
import com.crm.rely.backend.core.dto.custom.login.special.CustomLoginSpecialCalcDto;
import com.crm.rely.backend.core.entity.custom.login.special.CustomLoginSpecialCalcAddEntity;
import com.crm.rely.backend.core.entity.custom.login.special.CustomLoginSpecialCalcListEntity;
import com.crm.rely.backend.core.entity.custom.login.special.CustomLoginSpecialCalcUpdateEntity;
import com.crm.rely.backend.core.pojo.table.CustomLoginSpecialCalcTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.BeanUtilPlus;
import com.crm.rely.backend.util.FormatPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CustomLoginSpecialCalcServiceImpl implements CustomLoginSpecialCalcService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CustomLoginSpecialCalcMapper customLoginSpecialCalcMapper;
    @Autowired
    private CustomLoginSpecialCalcRepository customLoginSpecialCalcRepository;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<Object> add(CustomLoginSpecialCalcAddEntity entity) throws ServiceException {
        try {
            Integer eCount = customLoginSpecialCalcMapper.countByLogin(entity.getLogin());
            if (Optional.ofNullable(eCount).orElse(0) >= 1) {
                return BaseResultDto.error(Constants.RECORD_EXISTS);
            }

            CustomLoginSpecialCalcTable table = CustomLoginSpecialCalcTable.getInstance();
            BeanUtilPlus.copyPropertiesIgnoreNull(entity, table);
            customLoginSpecialCalcRepository.save(table);

            return BaseResultDto.success();

        } catch (Exception e) {
            logger.error("CustomLoginSpecialCalcService add error: {}", e.getMessage(), e);
            throw ServiceException.exception(e.getMessage());
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<Object> updateById(CustomLoginSpecialCalcUpdateEntity entity) throws ServiceException {
        try {

            CustomLoginSpecialCalcTable table = customLoginSpecialCalcMapper.getOne(entity.getId());
            if (table == null) {
                return BaseResultDto.error(Constants.INFO_NOT_FOUND);
            }

            if (!table.getLogin().equals(entity.getLogin())) {
                Integer eCount = customLoginSpecialCalcMapper.countByLogin(entity.getLogin());
                if (Optional.ofNullable(eCount).orElse(0) >= 1) {
                    return BaseResultDto.error(Constants.RECORD_EXISTS);
                }
            }

            BeanUtilPlus.copyPropertiesIgnoreNull(entity, table);
            customLoginSpecialCalcRepository.save(table);
            return BaseResultDto.success();

        } catch (Exception e) {
            logger.error("CustomLoginSpecialCalcService updateById error: {}", e.getMessage(), e);
            throw ServiceException.exception(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto<Object> deleteById(Long id) throws ServiceException {
        try {

            CustomLoginSpecialCalcTable table = customLoginSpecialCalcMapper.getOne(id);
            if (table == null) {
                return BaseResultDto.error(Constants.INFO_NOT_FOUND);
            }

            customLoginSpecialCalcRepository.delete(id);
            return BaseResultDto.success();

        } catch (Exception e) {
            logger.error("CustomLoginSpecialCalcService deleteById error: {}", e.getMessage(), e);
            throw ServiceException.exception(e.getMessage());
        }
    }

    @Override
    public BaseResultDto<CustomLoginSpecialCalcDto> searchSingle(Long id) throws ServiceException {
        try {
            CustomLoginSpecialCalcTable table = customLoginSpecialCalcMapper.getOne(id);
            if (table == null) {
                return BaseResultDto.error(Constants.INFO_NOT_FOUND);
            }

            CustomLoginSpecialCalcDto dto = new CustomLoginSpecialCalcDto();
            BeanUtils.copyProperties(table, dto);
            return BaseResultDto.success(dto);

        } catch (Exception e) {
            logger.error("CustomLoginSpecialCalcService searchSingle error: {}", e.getMessage(), e);
            throw ServiceException.exception(e.getMessage());
        }
    }

    @Override
    public BaseResultWithPagerDto<List<CustomLoginSpecialCalcDto>> searchList(CustomLoginSpecialCalcListEntity entity) throws ServiceException {
        try {
            Integer count = customLoginSpecialCalcMapper.countSearch(entity);
            PageDto pageDto = FormatPage.format(entity.getPage(), count);
            if (Optional.ofNullable(count).orElse(0) <= 0) {
                return new BaseResultWithPagerDto<>(Constants.SUCCESS_CODE, Constants.SEARCH_SUCCESS, pageDto);
            }

            List<CustomLoginSpecialCalcDto> dtos = Optional.ofNullable(customLoginSpecialCalcMapper.listSearch(entity)).orElse(new ArrayList<>())
                    .stream().map(k -> {
                        CustomLoginSpecialCalcDto dto = new CustomLoginSpecialCalcDto();
                        BeanUtils.copyProperties(k, dto);
                        return dto;
                    }).collect(Collectors.toList());

            return new BaseResultWithPagerDto(Constants.SUCCESS_CODE, Constants.SEARCH_SUCCESS, pageDto, dtos);

        } catch (Exception e) {
            logger.error("CustomLoginSpecialCalcService searchSingle error: {}", e.getMessage(), e);
            throw ServiceException.exception(e.getMessage());
        }
    }
}
