package cn.com.poc.knowledge.service.impl;

import cn.com.poc.knowledge.convert.KnowledgeTrainLogConvert;
import cn.com.poc.knowledge.entity.BizKnowledgeTrainLogEntity;
import cn.com.poc.knowledge.model.BizKnowledgeTrainLogModel;
import cn.com.poc.knowledge.repository.BizKnowledgeTrainLogRepository;
import cn.com.poc.knowledge.service.BizKnowledgeTrainLogService;
import cn.com.yict.framemax.core.service.impl.BaseServiceImpl;
import cn.com.yict.framemax.core.utils.BeanUtils;
import cn.com.yict.framemax.data.model.PagingInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BizKnowledgeTrainLogServiceImpl extends BaseServiceImpl
        implements BizKnowledgeTrainLogService {

    @Resource
    private BizKnowledgeTrainLogRepository repository;

    @Override
    public BizKnowledgeTrainLogEntity get(Integer id) throws Exception {
        BizKnowledgeTrainLogModel bizKnowledgeTrainLogModel = this.repository.get(id);
        return KnowledgeTrainLogConvert.modelToEntity(bizKnowledgeTrainLogModel);
    }

    @Override
    public List<BizKnowledgeTrainLogEntity> findByExample(BizKnowledgeTrainLogEntity entity, PagingInfo pagingInfo) throws Exception {
        List<BizKnowledgeTrainLogEntity> result = new ArrayList<>();
        BizKnowledgeTrainLogModel bizKnowledgeTrainLogModel = KnowledgeTrainLogConvert.entityToModel(entity);
        List<BizKnowledgeTrainLogModel> models = this.repository.findByExample(bizKnowledgeTrainLogModel, pagingInfo);
        if (CollectionUtils.isNotEmpty(models)) {
            result = models.stream().map(KnowledgeTrainLogConvert::modelToEntity).collect(Collectors.toList());
        }
        return result;
    }

    @Override
    public BizKnowledgeTrainLogEntity save(BizKnowledgeTrainLogEntity entity) throws Exception {
        BizKnowledgeTrainLogModel saveModel = new BizKnowledgeTrainLogModel();
        if (entity.getId() != null) {
            saveModel = this.repository.get(entity.getId());
            BeanUtil.copyProperties(entity, saveModel,new CopyOptions().ignoreNullValue());
        }
        else{
            saveModel = KnowledgeTrainLogConvert.entityToModel(entity);
        }
        return KnowledgeTrainLogConvert.modelToEntity(this.repository.save(saveModel));
    }
}