package com.uas.account;

import org.junit.Assert;
import org.springframework.ui.ModelMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.account.entity.User;
import com.uas.sso.common.util.HttpUtil;
import com.uas.sso.common.util.HttpUtil.ResponseWrap;

public class LoginTest {

	private String getAccessToken(User user) throws Exception {
		JSONObject formData = JSON.parseObject(JSON.toJSONString(user));
		formData.put("_operate", "getToken");
		ResponseWrap res = HttpUtil.doGet("http://127.0.0.1:8080/api/user", formData);
		if (!res.isSuccess())
			throw new Exception(res.getContent());
		else {
			ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
			if (!result.isSuccess())
				throw new Exception(result.getErrMsg());
			else
				return String.valueOf(result.getContent());
		}
	}

	private User checkAccessToken(String token, String appId) throws Exception {
		ResponseWrap res = HttpUtil.doGet("http://127.0.0.1:8080/api/user",
				new ModelMap("_operate", "checkToken").addAttribute("token", token).addAttribute("appId", appId));
		if (!res.isSuccess())
			throw new Exception(res.getContent());
		else {
			ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
			if (!result.isSuccess())
				throw new Exception(result.getErrMsg());
			else
				return JSON.parseObject(JSON.toJSONString(result.getContent()), User.class);
		}
	}

	// @Test
	public void loginByToken() throws Exception {
		// 用户账户信息
		User user = new User();
		user.setAppId("uas");
		user.setName("应鹏");
		user.setUid("13798490565");
		user.setPassword("111111");
		user.setSpaceUID("8888888888");
		String token = getAccessToken(user);
		Assert.assertNotNull(token);
		System.out.println(token);
		User user2 = checkAccessToken(token, "mall");
		Assert.assertNotNull(user2);
		System.out.println(user2);
	}

}
