package cn.sh.stc.sict.theme.common.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.sh.stc.sict.cloud.common.core.util.NumberUtil;
import cn.sh.stc.sict.theme.common.dao.HphyAttachmentMapper;
import cn.sh.stc.sict.theme.common.dto.ArticleDTO;
import cn.sh.stc.sict.theme.common.model.HphyArticle;
import cn.sh.stc.sict.theme.common.model.HphyAttachment;
import cn.sh.stc.sict.theme.common.service.HphyAttachmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("hphyAttachmentService")
@AllArgsConstructor
public class HphyAttachmentServiceImpl extends ServiceImpl<HphyAttachmentMapper, HphyAttachment> implements HphyAttachmentService {

    private final HphyAttachmentMapper hphyAttachmentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrupdate(Long bizId, List<HphyAttachment> attachmentList) {
        if (CollUtil.isNotEmpty(attachmentList) && NumberUtil.isNotNullOrZero(bizId)) {
            attachmentList.forEach(a -> {
                a.setBizId(bizId);
                this.saveOrUpdate(a);
            });
        }

        return true;
    }

    @Override
    public boolean removeByBizId(Long bizId) {
        return false;
    }

    @Override
    public List<HphyAttachment> getByBizId(Long bizId) {
        return this.list(new LambdaQueryWrapper<HphyAttachment>().eq(HphyAttachment::getBizId, bizId));
    }

    @Override
    public Page<ArticleDTO> getVO(Page<HphyArticle> page) {
        Page<ArticleDTO> dtoPage = new Page<>();
        dtoPage.setPages(page.getPages());
        dtoPage.setTotal(page.getTotal());
        List<ArticleDTO> dtoList = new ArrayList<>();
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<Long> ids = page.getRecords().stream().map(HphyArticle::getId).collect(Collectors.toList());
            List<HphyAttachment> list = this.list(new LambdaQueryWrapper<HphyAttachment>().in(HphyAttachment::getBizId, ids));
            Map<Long, List<HphyAttachment>> collect = list.stream().collect(Collectors.groupingBy(HphyAttachment::getBizId));
            page.getRecords().forEach(i -> {
                ArticleDTO dto = new ArticleDTO();
                dto.setArticle(i);
                dto.setAttachmentList(collect.getOrDefault(i.getId(), null));
                dtoList.add(dto);
            });
        }
        dtoPage.setRecords(dtoList);
        return dtoPage;
    }
}
