package quant.rich.emoney.controller.manage;

import java.util.HashMap;
import java.util.Map;

import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import quant.rich.emoney.controller.common.BaseController;
import quant.rich.emoney.entity.config.IndexInfoConfig;
import quant.rich.emoney.pojo.dto.LayPageResp;
import quant.rich.emoney.pojo.dto.R;
import quant.rich.emoney.service.IndexDetailService;

@Controller
@RequestMapping("/admin/v1/manage/indexInfo")
public class IndexInfoControllerV1 extends BaseController {
    
    @Autowired
    IndexInfoConfig indexInfoConfig;
    
    @Autowired
    IndexDetailService indexDetailService;

    @GetMapping({"", "/", "/index"})
    public String index() {
        return "/admin/v1/manage/indexInfo/index";
    }
    
    /**
     * 获取指标详情解释
     * @param indexCode
     * @return
     */
    @GetMapping("/getIndexDetail")
    @ResponseBody
    public R<?> getIndexDetail(String indexCode) {
        return 
            R.judge(() -> 
                indexDetailService.getIndexDetail(indexCode));
    }
    
    /**
     * 强制刷新并获取指标详情解释
     * @param indexCode
     * @return
     */
    @GetMapping("/forceRefreshAndGetIndexDetail")
    @ResponseBody
    public R<?> forceRefreshAndGetIndexDetail(String indexCode) {
        return 
            R.judge(() -> 
                indexDetailService.forceRefreshAndGetIndexDetail(indexCode));
    }

    @GetMapping("/getFields")
    @ResponseBody
    public R<?> getFields(@RequestParam("fields") String[] fields) {
        if (fields == null || fields.length == 0) {
            return R.ok(indexInfoConfig);
        }
        Object indexInfoConfigWithoutProxy = AopProxyUtils.getSingletonTarget(indexInfoConfig);
        ObjectNode indexInfoJson = new ObjectMapper().valueToTree(indexInfoConfigWithoutProxy);
        Map<String, Object> map = new HashMap<>();
        for (String field : fields) {
            map.put(field, indexInfoJson.get(field));
        }
        return R.ok(map);
    }
    
    /**
     * 根据给定 url 获取在线指标配置
     * @param url
     * @return
     */
    @GetMapping("/getConfigIndOnlineByUrl")
    @ResponseBody
    public R<?> getConfigOnlineByUrl(String url) {
        return R.judge(() -> indexInfoConfig.getOnlineConfigByUrl(url));
    }
    
    @GetMapping("/getIndexInfoConfig")
    @ResponseBody
    public R<?> getIndexInfoConfig() {
        return R.ok(indexInfoConfig);
    }
    
    @GetMapping("/list")
    @ResponseBody
    public LayPageResp<?> list() {
        return null;
    }
}
