package com.xxfc.platform.order.biz;

import cn.hutool.core.lang.Dict;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.google.common.collect.Maps;
import com.xxfc.platform.order.entity.OrderTemplate;
import com.xxfc.platform.order.mapper.OrderTemplateMapper;
import org.springframework.stereotype.Service;

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

/**
 * 费用明细
 *
 * @author zjw
 * @email nishijjo@qq.com
 * @date 2019-06-04 22:14:33
 */
@Service
public class OrderTemplateBiz extends BaseBiz<OrderTemplateMapper,OrderTemplate> {

    public String result (OrderTemplate orderTemplate, Dict dict) {
        TemplateEngine engine = TemplateUtil.createEngine();
        String result = "";
        Template template;
//        //预处理
//        template = engine.getTemplate(orderTemplate.getTemplate());
//        result = template.render(new Dict(preprocessMap));

        //获取所有模板
        List<OrderTemplate> all = this.selectListAll();
        Map<String, Object> allCodeMap = all.parallelStream().collect(Collectors.toMap(item -> "tem_"+ item.getCode(), OrderTemplate::getTemplate));
        List<String> codes = all.parallelStream().map(OrderTemplate::getCode).collect(Collectors.toList());

        //匹配模板 ParamKey() 判断是否存在别的模板
        List<String> list = Arrays.asList(orderTemplate.getParamKey().split(",")).parallelStream().filter(item -> codes.contains(item)).collect(Collectors.toList());
        if(list.size() > 0) {
            template = engine.getTemplate(orderTemplate.getTemplate());
            result = template.render(new Dict(allCodeMap));
        }

        //匹配参数 填充参数
        template = engine.getTemplate(result);
        result = template.render(dict);

        return result;
    }

    public String result (String templateStr, Map map) {
        TemplateEngine engine = TemplateUtil.createEngine();
        Template template = engine.getTemplate(templateStr);
        return template.render(map);
    }

    public static void main(String[] args) {
        String tempStr = "{\"key\":\"费用明细\", \"val\":\"\", \"consumeAmount\":\"${consumeAmount}\",\"children\":[${children}]}";
        Map map = Maps.newHashMap();
        map.put("consumeAmount", "");
        map.put("children", "{\"test\" : \"1111\" }");

        //匹配参数 填充参数
        TemplateEngine engine = TemplateUtil.createEngine();
        Template template = engine.getTemplate(tempStr);
        String result = template.render(new Dict(map));
        System.out.println(result);
    }

}