package com.duiba.tuia.youtui.web.tool;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;

/**
 * 中奖公示构造模板工具类
 * Created by Administrator on 2017/12/15.
 */
public class WinPublicTool {

    private WinPublicTool() {
    }

    /***
     * @Description: buildWinString
     * 循环替换template中的参数
     * 模板中占位符未[{i}]格式，i>=1;
     * @Param: [template, params]
     * @Return: java.lang.String
     * @throws:
     * @author: youhaijun
     * @Date: 2017/12/15
     */
    public static String buildWinString(String template, String... params) {
        String temp = template;
        for (int i = 0; i < params.length; i++) {
            String param = params[i];
            String s = temp.replaceFirst("\\[\\{" + i + "\\}\\]", Matcher.quoteReplacement(param));
            temp = s;
        }
        return temp;
    }

    /***
     * @Description: getTemplateList
     * 获取List<template></>
     * 获取到的list数量和 【list】相等
     * @Param: [template模板, lists 替换参数源, functions，需要替换的参数获取操作列表]
     * @Return: java.util.List<java.lang.String>
     * @throws:
     * @author: youhaijun
     * @Date: 2017/12/15
     */
    public static <T, R> List<String> getTemplateList(String template, List<T> lists, Function<T, R>... functions) {

        List<String> rsp = new ArrayList<>(lists.size());

        for (T t : lists) {
            String[] params = new String[functions.length];
            for (int i = 0; i < functions.length; i++) {
                R apply = functions[i].apply(t);
                params[i] = apply.toString();
            }
            try {
                String temp = buildWinString(template, params);
                rsp.add(temp);
            }catch(Exception e){
                continue;
            }
        }
        return rsp;
    }
}
