package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.CustomerNewsMapper;
import com.crm.manager.service.CustomNewsService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.custom.news.CustomNewsSearchDto;
import com.crm.rely.backend.core.dto.system.config.SysConfigSearchDto;
import com.crm.rely.backend.core.entity.custom.news.CustomNewsSearchEntity;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.core.pojo.view.CustomNewsView;
import com.crm.rely.backend.exception.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: houn
 * @Date: 2020/8/14 13:54
 * @Description:
 */
@Service
public class CustomNewsServiceImpl implements CustomNewsService {

    @Autowired
    private CustomerNewsMapper customerNewsMapper;

    @Override
    public ResultWithPagerDto<CustomNewsSearchDto> searchPageList(CustomNewsSearchEntity entity) throws ServiceException {
        Integer count = customerNewsMapper.searchPageCount(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<CustomNewsView> customNewsViews = customerNewsMapper.searchPageList(entity);

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

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<CustomNewsSearchDto> customNewsSearchDtos = transform(customNewsViews);

        return ResultWithPagerDto.success(pageDto, customNewsSearchDtos);
    }

    private List<CustomNewsSearchDto> transform(List<CustomNewsView> customNewsViews) {
        if (customNewsViews == null || customNewsViews.size() <= 0) {
            return null;
        }
        List<CustomNewsSearchDto> customNewsSearchDtos = new ArrayList<>(customNewsViews.size());

        for (CustomNewsView customNewsView : customNewsViews) {
            CustomNewsSearchDto sysConfigSearchDto = transform(customNewsView);
            customNewsSearchDtos.add(sysConfigSearchDto);
        }

        return customNewsSearchDtos;
    }

    private CustomNewsSearchDto transform(CustomNewsView customNewsView) {

        CustomNewsSearchDto customNewsSearchDto = new CustomNewsSearchDto();
        BeanUtils.copyProperties(customNewsView, customNewsSearchDto);

        return customNewsSearchDto;
    }
}
