package com.sunxung.factoring.component.tag;

import java.util.List;

import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IAttribute;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import com.sunxung.factoring.component.util.SpringUtil;
import com.sunxung.factoring.component.util.StringUtil;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.service.sys.DictionaryService;

/**
 * HTML中option tag标签
 */
public class OptionTag extends AbstractAttributeTagProcessor {

    private static String ATTR_NAME = "option";
    private static int PRECEDENCE = 10000;
    private static DictionaryService dictionaryService;

    public OptionTag(final String dialectPrefix){
        super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true);
    }

    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName,
            String attributeValue, IElementTagStructureHandler structureHandler) {
        StringBuffer sb = new StringBuffer("<option value=''>请选择</option>");
        IAttribute defultValue = tag.getAttribute("value");
        List<Dictionary> dictionarys = getDictionaryService().findByParentCode(attributeValue);
        if (dictionarys != null) {
            for (Dictionary dict : dictionarys) {
                if (defultValue != null && StringUtil.isNotEmpty(defultValue.getValue())
                        && dict.getId().equals(Long.parseLong(defultValue.getValue()))) {
                    sb.append("<option code='" + dict.getCode() + "' value='" + dict.getId() + "' selected>"
                            + dict.getName() + "</option>");
                } else {
                    sb.append("<option code='" + dict.getCode() + "' value='" + dict.getId() + "'>" + dict.getName()
                            + "</option>");
                }
            }
        }
        structureHandler.setBody(sb.toString(), false);
    }

    private DictionaryService getDictionaryService() {
        if (dictionaryService == null) {
            dictionaryService = SpringUtil.getBeanByType(DictionaryService.class);
        }
        return dictionaryService;
    }
}
