package cn.com.countrygarden.bi.main.controller;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.service.ModuleService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.RedisCacheUtils;
import cn.com.countrygarden.bi.main.util.ServerUri;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;


@Controller("ModuleController")
@RequestMapping("/api/biapp/module")
public class ModuleController {

    @Autowired
    private ModuleService moduleService;
    @Resource
    private TbSysUserService tbSysUserService;

    @RequestMapping(value = "/main", produces = "application/json;charset=utf-8")
    public @ResponseBody
    Object getMainModule(@RequestParam(value = "limit", required = true, defaultValue = "8") String limit, HttpServletRequest request) {
        Map<String, String> param = new HashMap<String, String>() {{
            put("limit", limit);
        }};
        Function<Map<String, String>, List<Map<String, String>>> function = p -> moduleService.getMainModule(p);

        List<Map<String, String>> modules = RedisCacheUtils.rememberList(
                "biapp:module:main",
                900 /* 15 * 60 */,
                param,
                function
        );

        if (!modules.isEmpty()) {
            String basePath = ServerUri.getServerPath(request);
            for (Map<String, String> module : modules) {
                String url = module.getOrDefault("url", "");
                if (url != "" && !url.equals("") && url != null) {
                    url = tbSysUserService.suffixAccesstoken(url);
                    if (url.length() > 6 && !url.substring(0, 6).equals("http://")) {
                        module.put("url", basePath + url.trim());
                    }
                }

                String image = module.getOrDefault("image", "");
                if (image != "" && !image.equals("") && image != null && image.length() > 6
                        && !image.substring(0, 6).equals("http://")) {
                    module.put("image", basePath + image.trim());
                }
            }
        }
        return Response.response(modules);
    }
}
