package com.uas.sso.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.uas.account.AccountConfig;
import com.uas.account.entity.App;
import com.uas.account.service.AppService;
import com.uas.account.service.AssetService;
import com.uas.account.viewmodel.AssetView;
import com.uas.account.web.BaseController;
import com.uas.sso.SSOConfig;
import com.uas.sso.SSOHelper;
import com.uas.sso.Token;
import com.uas.sso.common.util.HttpUtil;
import com.uas.sso.web.waf.request.WafRequestWrapper;

@Controller
public class IndexController extends BaseController {

	@Autowired
	private AssetService assetService;
	@Autowired
	private AppService appService;

	/**
	 * 登录界面
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView loginPage(ModelMap model) throws Exception {
		/**
		 * 正常登录 需要过滤sql及脚本注入
		 */
		WafRequestWrapper wr = new WafRequestWrapper(request);
		String returnUrl = wr.getParameter(SSOConfig.ReturnURLParam);
		Token token = SSOHelper.getToken(request);
		if (token == null) {
			String appId = wr.getParameter(AccountConfig.AppIdParam);
			// 指定登录的app
			if (StringUtils.isEmpty(appId)) {
				appId = AccountConfig.ACCOUNT_CENTER;
			}
			model.addAttribute("appId", appId);
			if (!StringUtils.isEmpty(returnUrl)) {
				model.addAttribute("returnUrl", returnUrl);
			}
			List<AssetView> assets = assetService.findByApp(appId);
			if (CollectionUtils.isEmpty(assets)) {
				App app = appService.findOne(appId);
				if (app != null && !StringUtils.isEmpty(app.getUserControl())) {
					assets = assetService.findByApp(app.getUserControl());
				}
			}
			if (CollectionUtils.isEmpty(assets)) {
				assets = assetService.findByApp(AccountConfig.ACCOUNT_CENTER);
			}
			model.addAttribute("assets", assets);
			return new ModelAndView("sso/login", model);
		} else {
			if (StringUtils.isEmpty(returnUrl)) {
				return new ModelAndView("user/info", model);
			}
			return new ModelAndView("redirect:" + HttpUtil.decodeURL(returnUrl));
		}
	}

}
