package com.keyware.shandan.mark.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keyware.shandan.mark.mapper.MarkRecordMapper;
import com.keyware.shandan.mark.pojo.MarkRecord;
import com.keyware.shandan.mark.services.MarkRecordService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author GuoXin
 * @date 2022-05-13
 */
@Service
public class MarkRecordServiceImpl extends ServiceImpl<MarkRecordMapper, MarkRecord> implements MarkRecordService {
    @Override
    public Boolean removeByEntityIds(Collection<? extends Serializable> entityIdList) {
        QueryWrapper<MarkRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("ENTITY_ID", entityIdList);
        return remove(queryWrapper);
    }

    @Override
    public Boolean removeByEntityId(Serializable entityId) {
        QueryWrapper<MarkRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ENTITY_ID", entityId);
        return remove(queryWrapper);
    }

    @Override
    public List<MarkRecord> listByEntityId(Serializable entityId) {
        QueryWrapper<MarkRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ENTITY_ID", entityId);
        return list(queryWrapper);
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<MarkRecord> entityList) {
        if (entityList != null && !entityList.isEmpty()) {
            Set<String> entityIds = entityList.stream().map(MarkRecord::getEntityId).collect(Collectors.toSet());
            removeByEntityIds(entityIds);
            return super.saveOrUpdateBatch(mergeMarkRecordsByMd5(entityList));
        }
        return false;
    }

    /**
     * 根据计算的md5值合并标签列表
     * 相同类型、相同表单、相同实体的标签值用逗号拼接
     *
     * @param records 标签集合
     * @return 标签集合
     */
    private Collection<MarkRecord> mergeMarkRecordsByMd5(Collection<MarkRecord> records) {
        Map<String, MarkRecord> markMap = new HashMap<>();
        for (MarkRecord mark : records) {
            MarkRecord temp = markMap.get(mark.md5());
            if (temp == null) {
                mark.setId(mark.md5());
                markMap.put(mark.md5(), mark);
            } else {
                temp.setMarkValue(temp.getMarkValue() + "," + mark.getMarkValue());
            }
        }
        return markMap.values();
    }
}
