package com.tuoheng.miniprogram.utils;

import com.tuoheng.common.core.config.common.CommonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author chenyukun
 */
public class CommonUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtils.class);

    /**
     * 获取到图片域名的地址
     *
     * @param imageUrl
     * @return
     */
    public static String getImageURL(String imageUrl) {
        return CommonConfig.imageURL + imageUrl;
    }

    /**
     * 正则匹配富文本图片
     *
     * @param htmlStr 富文本内容
     * @return
     */
    public static List<String> getImgStr(String htmlStr) {
        Pattern p_image = Pattern.compile("<img.*src\\s*=\\s*(.*?)[^>]*?>", Pattern.CASE_INSENSITIVE);
        Pattern r_image = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)");
        List<String> list = new ArrayList<>();
        Matcher m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            String img = m_image.group();
            System.out.println(img);
            // 匹配<img>中的src数据
            Matcher m = r_image.matcher(img);
            while (m.find()) {
                list.add(m.group(1));
            }
        }
        return list;
    }

    /**
     * 批量处理方法
     *
     * @param operater 回调方法，有入参无返回值
     * @param sourceList 批量处理list对象
     * @param threshold 阀值，比如有5000个对象，阀值设置1000，就是1000执行一次
     * @param <T> 对象类型
     */
    public static <T> void batchOperate(Consumer<List<T>> operater, List<T> sourceList, Integer threshold) {
        if(CollectionUtils.isEmpty(sourceList)){
            return;
        }
        int size = sourceList.size();
        int fromIndex = 0;
        List<T> list = null;
        while (size > fromIndex){
            try {
                list = sourceList.stream().skip(fromIndex).limit(threshold).collect(Collectors.toList());
                operater.accept(list);
                fromIndex += threshold;
            } catch (Exception e) {
                LOGGER.error("", e);
                throw e;
            }
        }
    }
}
