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.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);
    }

}