package org.cs.mgr.user.ctl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.cs.constants.Constants;
import org.cs.core.ctl.BaseCtl;
import org.cs.mgr.admin.model.Admin;
import org.cs.mgr.admin.service.IAdminService;
import org.cs.mgr.admin.service.IRoleService;
import org.cs.mgr.product.model.MgmProductCategory;
import org.cs.mgr.product.service.IMgmProductCategoryService;
import org.cs.mgr.user.model.Model;
import org.cs.mgr.user.service.impl.MgmUserService;
import org.cs.util.PropUtil;
import org.cs.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

/**
 * 与东旭门户集成单点登录
 * @author DELL
 *
 */
@Controller
@RequestMapping("/oauthCtl")
public class OauthCtl extends BaseCtl{

	private static String LOGIN_SUCCESS = "redirect:/mgr/main.if";
	private static String LOGIN_FAIL = "redirect:/fail.jsp";

	@Autowired 
	private IAdminService adminService;
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private IMgmProductCategoryService mgmProductCategoryService;
	@Autowired
	private MgmUserService mgmUserService;
	
	

  private String client_id="02bd5d75-32cd-4062-9041-78f1cc346423";
private String client_secret="efd80748-a178-4bfe-9ef6-ff906ba93d01";
private String http_server_url="http://dev.dong-xu.com/oneportal/oauth2api";
private String redirect_uri="http://dev.dong-xu.com/yxpt/oauthCtl/pcCallback.if";
private String phone_redirect_uri="http://dev.dong-xu.com/yxpt/oauthCtl/phoneCallback.if";
	
	/**
     * 重定向到服务端获取授权码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("pcOauth2toServer")
    public String oauth2toServer(HttpServletRequest request, HttpServletResponse response, RedirectAttributes attr) throws Exception {
        attr.addAttribute("client_id", client_id);
        attr.addAttribute("response_type", "code");
        attr.addAttribute("redirect_uri",redirect_uri);


        return "redirect:" + http_server_url +"/authorize.if"; //重定向
    }
    
    
    /**
     * 移动端
     * 重定向到服务端获取授权码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("phoneOauth2toServer")
    public String phoneOauth2toServer(HttpServletRequest request, HttpServletResponse response, RedirectAttributes attr) throws Exception {

        attr.addAttribute("client_id",client_id);
        attr.addAttribute("response_type", "code");
        attr.addAttribute("redirect_uri", phone_redirect_uri);
        return "redirect:" + http_server_url +"/authorize.if"; //重定向
    }

    /**
     * 服务端回调服务，获取授权码，授权登录成功，跳转到主页面
     *
     * @param code 服务端回调获取的授权码
     */
    @RequestMapping("pcCallback")
    public String callback(HttpServletRequest request, @ModelAttribute("code") String code) throws Exception {
        System.out.println("client authCode:" + code);
        String loginId = getAccreditByServer(code, redirect_uri);

        //HttpSession session = request.getSession();

       // Oauth2User oauth2User = (Oauth2User) session.getAttribute(Constants.SESSION_ACTIVEUSER_KEY);
       // Admin user = (Admin) this.get(Constants.SESSION_USER);
        
        //如果session中没有用户说明是登录即直接查询，如果有用户说明的已经登录在使用授权
        //if (user == null) {
            //查询
        	Admin user = this.adminService.getByAccount(loginId);
             //oauth2User = oauth2UserService.findUserByServerId(username);
            if (user == null) {//如果查不到用户说明没有授权过，请登录授权
                request.setAttribute("msg", "登录失败，用户没有授权，请登录授权！");
                return LOGIN_FAIL;
            }
            //session.setAttribute(Constants.SESSION_ACTIVEUSER_KEY, oauth2User);
            this.set(Constants.SESSION_USER, user);
        	Map<String, String> map = new HashMap<>();
			map.put("id", user.getCode());
			Map<String, Object> role = this.roleService.findRoleByUserId(map);
			this.set(Constants.USER_ROLE, role);//FOUR_CATEGORY_ID
			if(role.get("ONE_CATEGORY_ID") != null && Integer.valueOf(role.get("ONE_CATEGORY_ID").toString()).intValue()!=0){
				map.put("id", role.get("ONE_CATEGORY_ID").toString());
				this.set(Constants.TWOCATEGORY, this.mgmProductCategoryService.queryShowCategory(map));
			}else{
				this.set(Constants.TWOCATEGORY, new ArrayList<MgmProductCategory>());
			}
			if(role.get("TWO_CATEGORY_ID") != null && Integer.valueOf(role.get("TWO_CATEGORY_ID").toString()).intValue()!=0){
				map = new HashMap<>();
				map.put("id", role.get("TWO_CATEGORY_ID").toString());
				this.set(Constants.THREECATEGORY, this.mgmProductCategoryService.queryShowCategory(map));
			}else{
				this.set(Constants.THREECATEGORY, new ArrayList<MgmProductCategory>());
			}
			if(role.get("THREE_CATEGORY_ID") != null && Integer.valueOf(role.get("THREE_CATEGORY_ID").toString()).intValue()!=0){
				map = new HashMap<>();
				map.put("id", role.get("THREE_CATEGORY_ID").toString());
				this.set(Constants.FOURCATEGORY, this.mgmProductCategoryService.queryShowCategory(map));
			}else{
				this.set(Constants.FOURCATEGORY, new ArrayList<MgmProductCategory>());
			}

			
        //} 

        return LOGIN_SUCCESS;
    }
    
    
   
    /**
     * 移动端
     * 服务端回调服务，获取授权码，授权登录成功，跳转到移动端主页面
     * @param request
     * @param code
     * @return
     * @throws Exception
     */
    @RequestMapping("phoneCallback")
    public String phoneCallback(HttpServletRequest request, @ModelAttribute("code") String code) throws Exception {
    	   System.out.println("client authCode:" + code);

           String loginId = getAccreditByServer(code, phone_redirect_uri);
           JSONObject json = mgmUserService.checkUser(loginId);
           if (json.getIntValue("ret") == 1){
				Map<String, String> user = getMapFromJson(json.getJSONObject("data").toString());
				request.getSession().setAttribute(Constants.SESSION_WEB_USER, user);
				  
		           String type = user.get("type")+"";
		           String id = user.get("id")+"";
				   String phone = user.get("phone")+"";
		           if("0".equals(type)){
		        	   //集团用户
		        	   String firstLogin = user.get("firstLogin")+"";
		        	   if("0".equals(firstLogin)){//第一次登陆
		        		return "redirect:/web/mgmUserCtl/phone_bang.if?userId="+id+"&phone="+phone;
		        	   }else{
		        		return "redirect:/web/mgmUserCtl/index.if?userId="+id;
		        	   }
		           }else{
		        	   //非集团用户
		        	   String idnumber = user.get("idnumber")+"";
		        	   if(StringUtil.isNotBlank(idnumber)){
		        		   return "redirect:/web/mgmUserCtl/info_personal.if?userId="+id+"&phone="+phone;
		        	   }else{
		        		   return "redirect:/web/mgmUserCtl/index.if?userId="+id;
		        	   }
		           }
			}else{
				  request.setAttribute("msg", "登录失败，用户没有授权，请登录授权！");
	               return LOGIN_FAIL;
			}
         
        
           
           
    }
    
    
    public String getAccreditByServer(String authCode,String redirect_url) {


		//http://localhost:8080/web-oauth2-server/accessToken?client_id=c1ebe466-1cdc-4bd3-ab69-77c3561b9dee&client_secret=d8346ea2-6017-43ed-ad68-19c0f971738b&grant_type=authorization_code&code=12545716af0a62d4918d5a245d62b030&redirect_uri=http://test.dgtis.com:8080/web-base/system/MainCtr/initMain
		String accessTokenUrl = http_server_url+"/accessToken.if";
		OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
		OAuthResourceResponse resourceResponse = null;

		try {
			//使用授权码获取accessToken
			OAuthClientRequest accessTokenRequest = OAuthClientRequest
					.tokenLocation(accessTokenUrl)
					.setGrantType(GrantType.AUTHORIZATION_CODE)
					.setClientId(client_id)
					.setClientSecret(client_secret)
					.setCode(authCode)
					.setRedirectURI(redirect_url)
					.buildBodyMessage();
			OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST);

			String accessToken = oAuthResponse.getAccessToken();
			Long expiresIn = oAuthResponse.getExpiresIn();

			System.out.println("AccessToken Client : "+accessToken);

			//使用accessToken获取用户信息
			//http://test.dgtis.com:8080/web-base/userInfo?access_token=7921a463132b857e8d929061fb7b6902
			String userInfoUrl = http_server_url +"/userInfo.if";
			OAuthClientRequest userInfoRequest = new OAuthBearerClientRequest(userInfoUrl).setAccessToken(accessToken).buildQueryMessage();

			resourceResponse = oAuthClient.resource(userInfoRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);

		}catch (Exception e){
			e.printStackTrace();
		}

		String userInfoRes = resourceResponse.getBody();
		System.out.println("UserInfo Client : "+userInfoRes);

		Gson gson = new Gson();
		Map<String,String> userInfo  = gson.fromJson(userInfoRes, Map.class);

		return userInfo.get("loginId");
	}


}
