package com.keyware.shandan;

import com.keyware.shandan.common.util.StringUtils;
import com.keyware.shandan.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

/**
 * @author Administrator
 */
@EnableAsync(proxyTargetClass = true)
@SpringBootApplication
public class OauthApplication {
    public static void main(String[] args) {
        SpringApplication.run(OauthApplication.class, args);
    }

    @Controller
    @RequestMapping
    static class IndexController {

        @Autowired
        private DictService dictService;

        @GetMapping("/index")
        public ModelAndView index(Principal principal, HttpServletResponse response) {
            ModelAndView modelAndView = new ModelAndView("index");
            modelAndView.addObject("principal", principal);
            String desktopUrl = dictService.getDesktopUrl();
            modelAndView.addObject("desktopAddress", desktopUrl);
            if(StringUtils.isNotBlank(desktopUrl)){
                try {
                    response.sendRedirect(desktopUrl);
                } catch (IOException e) {
                    return modelAndView;
                }
            }
            return modelAndView;
        }

        @RequestMapping(value = "/login", method = {RequestMethod.GET})
        public ModelAndView login(ModelAndView mav) {
            mav.setViewName("login");
            String sysName = dictService.getSysName();
            mav.addObject("logoName", StringUtils.isEmpty(sysName) ? "统一认证服务" : sysName);
            return mav;
        }

        @GetMapping("/logout/r")
        public ModelAndView logout(ModelAndView mav){
            mav.setViewName("logout");
            return mav;
        }
    }
}
