package com.crm.ucard.service.impl;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.system.reasons.refusal.SysReasonsRefusalSearchDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.system.reasons.refusal.SysReasonsRefusalSearchEntity;
import com.crm.rely.backend.core.pojo.table.SysReasonsRefusalTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.ucard.dao.mapper.SysReasonsRefusalMapper;
import com.crm.ucard.dao.repository.SysReasonsRefusalRepository;
import com.crm.ucard.service.SysReasonsRefusalService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysReasonsRefusalServiceImpl implements SysReasonsRefusalService {

    @Autowired
    private SysReasonsRefusalRepository sysReasonsRefusalRepository;

    @Autowired
    private SysReasonsRefusalMapper sysReasonsRefusalMapper;

    @Override
    public SysReasonsRefusalSearchDto searchSingle(SingleLongEntity entity) throws ServiceException {
        SysReasonsRefusalTable sysReasonsRefusalTable = sysReasonsRefusalRepository.getFirstById(entity.getId());

        if (sysReasonsRefusalTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        return transform(sysReasonsRefusalTable);
    }

    @Override
    public BaseResultDto<Map<String, SysReasonsRefusalSearchDto>> searchList(SysReasonsRefusalSearchEntity entity) throws ServiceException {
        List<SysReasonsRefusalTable> sysReasonsRefusalTables = sysReasonsRefusalMapper.searchList(entity);

        if (sysReasonsRefusalTables == null || sysReasonsRefusalTables.size() <= 0) {

            return ResultWithPagerDto.success();
        }
        Map<String, SysReasonsRefusalSearchDto> sysReasonsRefusalSearchDtos =
                new HashMap<>(sysReasonsRefusalTables.size());

        for (SysReasonsRefusalTable sysReasonsRefusalTable : sysReasonsRefusalTables) {
            SysReasonsRefusalSearchDto sysReasonsRefusalSearchDto = transform(sysReasonsRefusalTable);
            sysReasonsRefusalSearchDtos.put(String.valueOf(sysReasonsRefusalSearchDto.getId()),
                    sysReasonsRefusalSearchDto);
        }

        return BaseResultDto.success(sysReasonsRefusalSearchDtos);
    }


    private SysReasonsRefusalSearchDto transform(SysReasonsRefusalTable sysReasonsRefusalTable) {
        SysReasonsRefusalSearchDto sysReasonsRefusalSearchDto = new SysReasonsRefusalSearchDto();
        BeanUtils.copyProperties(sysReasonsRefusalTable, sysReasonsRefusalSearchDto);
        return sysReasonsRefusalSearchDto;
    }
}
