package com.huigou.uasp.bmp.opm.controller;

import com.huigou.uasp.annotation.ControllerMapping;
import com.huigou.uasp.bmp.common.easysearch.EasySearch;
import com.huigou.uasp.bmp.common.easysearch.domain.model.EasySearchParse;
import com.huigou.uasp.bmp.common.easysearch.domain.model.QuerySchemeField;
import com.huigou.uasp.bmp.opm.application.CssIconParser;
import com.huigou.uasp.bmp.opm.application.MemEasySearcher;
import com.huigou.uasp.bmp.opm.domain.model.resource.Icon;
import com.huigou.uasp.client.CommonController;
import com.huigou.util.SDO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.huigou.util.Constants.EASY_SEARCH_DATA;

/**
 * 图标。
 *
 * @author yonghuan
 */
@ControllerMapping("icon")
@Controller
public class IconController extends CommonController implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware {

    private final static Logger LOG = LoggerFactory.getLogger(IconController.class);
    @Autowired
    private CssIconParser cssIconParser;
    @Autowired
    private MemEasySearcher<Icon> memEasySearcher;
    private List<String> iconCssFiles = Collections.emptyList();
    private Collection<Icon> icons = Collections.emptyList();
    private ServletContext servletContext;

    @Value("${icon.cssFile}")
    public void setIconCssFile(String iconCssFile) {
        iconCssFiles = Arrays.asList(StringUtils.split(iconCssFile, ","));
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        syncIconsInternal();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        servletContext = ((WebApplicationContext) applicationContext).getServletContext();
    }

    /**
     * 手工同步图标
     */
    public String syncIcons() {
        syncIconsInternal();
        return success();
    }

    /**
     * 搜索图标。
     */
    @Deprecated
    public String easySearch() {
        SDO sdo = getSDO();
        Object model = executeEasySearch(sdo);
        putAttribute(EASY_SEARCH_DATA, model);
        return forward("/common/easySearch.jsp");
    }

    @EasySearch(queryName = "icon")
    public Object executeEasySearch(SDO sdo) {
        Integer intPage = sdo.getInteger("intPage", 1);
        Integer pageSize = sdo.getInteger("pageSize");
        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
        String paramValue = sdo.getString("paramValue");
        List<QuerySchemeField> fields = Arrays.asList(new QuerySchemeField("图标", "html", "string", 50L),
                new QuerySchemeField("编码", "code", "string", 100L));
        EasySearchParse easySearchParse = new EasySearchParse();
        easySearchParse.setFields(fields);
        easySearchParse.setWidth(200L);
        return memEasySearcher.search(icons, easySearchParse, pageRequest, (icon -> StringUtils.isBlank(paramValue) || icon.getCode().contains(paramValue)));
    }

    private void syncIconsInternal() {
        long startTimeMillis = System.currentTimeMillis();
        icons = iconCssFiles.stream()
                .map(servletContext::getRealPath)
                .filter(cssIconParser::supports)
                .flatMap(iconCssFile -> {
                    try {
                        return cssIconParser.parse(iconCssFile).stream();
                    } catch (IOException e) {
                        LOG.error(String.format("解析css文件 %s 出错", iconCssFile), e);
                        return Collections.<Icon>emptyList().stream();
                    }
                }).collect(Collectors.toList());
        LOG.info("同步图标完成，消耗 {} 毫秒", System.currentTimeMillis() - startTimeMillis);
    }
}
