package com.cool.bang.core.freemarker;

import com.cool.bang.modules.system.domain.po.DictItem;
import com.cool.bang.modules.system.service.IDictItemService;
import com.google.common.collect.Lists;
import freemarker.core.Environment;
import freemarker.template.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *  Freemarker System Dictionary (系统字典标签)
 *
 *  @author PeiZhi Guo
 *  2020-6-30 9:10
 */
@Component
public class SystemDictionary extends BaseDirective implements TemplateDirectiveModel {

    @Autowired
    private IDictItemService dictItemService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        Iterator iterator = map.entrySet().iterator();

        List<DictItem> dictList = Lists.newArrayList();

        while (iterator.hasNext()) {
            Map.Entry<String, TemplateModel> param = (Map.Entry<String, TemplateModel>) iterator.next();
            String paramName = param.getKey();
            TemplateModel paramValue = param.getValue();

            if ("type".equalsIgnoreCase(paramName)) {
                String type = getString(paramValue);
                if (StringUtils.isBlank(type)) {
                    throw new TemplateModelException("字典类型不正确");
                } else {
                    dictList = dictItemService.queryDictByType(type);

                }
            }
        }

        if( dictList.size() <= 0) {
            throw new TemplateModelException("返回值为空");
        }

        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);
        environment.setVariable("result", builder.build().wrap(dictList));
        templateDirectiveBody.render(environment.getOut());
    }
}
