package cn.com.capcloud.api;

import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.cache.BaseConfigStaticCache;
import cn.com.capcloud.core.system.security.JwtTokenProvider;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@CrossOrigin//支持跨域请求
@RestController
@RequestMapping("/api/data")
public class ApiOtherController {

    @Autowired
    private ApiService apiService;
    @Autowired
    private JwtTokenProvider jwtTokenProvider;


    //检查是否有token再返回一些重要的资源
    @RequestMapping("/checkAcl")
    public ResponseEntity<String> checkAcl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Cookie[] cookies = request.getCookies();
        String frontPath= String.valueOf(BaseConfigStaticCache.get("system.settings.context.front.path"));
        if(!frontPath.equals("none")){
            frontPath=frontPath+"-";
        }
        boolean isLogin=false;
        if(cookies!=null&&cookies.length>0) {
            for (int i = 0; i < cookies.length; i++) {
                String key=cookies[i].getName();
                if (key.equals(frontPath+"token")) {
                    String token=cookies[i].getValue();
                    try {
                        isLogin=jwtTokenProvider.validateToken(token);
                    } catch (Exception e) {
                    }
                }
            }
        }
        if(isLogin) {
            System.out.println("有效token");
            return new ResponseEntity<>("get front res success", HttpStatus.OK);
        }else {
            System.out.println("无效token，或没有token");
            return new ResponseEntity<>("get front res error,please login system", HttpStatus.UNAUTHORIZED);
        }

    }

    //心跳接口
    @RequestMapping("/health")
    public KHCResponseEntity health(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,Object> retMap=apiService.getReturnDataByCode("ok");
        retMap.put("message","服务正在运行");
        String str= JackJSONObject.fromObject(retMap).toString();
        return JackJSON.parseObject(str,KHCResponseEntity.class);
    }

}
