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

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.service.BannerService;
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("bannerController")
@RequestMapping("/api/biapp/banner")
public class BannerController {

    @Autowired
    private BannerService bannerService;
    @Resource
    private TbSysUserService tbSysUserService;

    @RequestMapping(value = "/main", produces = "application/json;charset=utf-8")
    public @ResponseBody
    Object getMainBanner(@RequestParam(value = "limit", required = true, defaultValue = "5") 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 -> bannerService.getMainBanner(p);

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

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

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