package com.uas.platform.b2b.openapi.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.uas.platform.b2b.model.AccessToken;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.openapi.support.ErrorUtils;
import com.uas.platform.b2b.service.AccessTokenService;
import com.uas.platform.b2b.service.EnterpriseService;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.exception.SystemError;
import com.uas.platform.core.util.AgentUtils;

/**
 * 第三方通过调用该接口获取token，在调用其他接口的时候，通过传入该token进行验证
 * 
 * <pre>
 * 由于设置了token的有效时间，第三方需要每隔2小时重新获取一次
 * </pre>
 * 
 * @author yingp
 *
 */
@SuppressWarnings("deprecation")
@RestController
@RequestMapping("/openapi/access_token")
public class OpenAccessTokenController {

	@Autowired
	private EnterpriseService enterpriseService;

	@Autowired
	private AccessTokenService accessTokenService;

	@Autowired
	private UserService userService;

	@RequestMapping
	public ModelMap getAccessToken(HttpServletRequest request, @RequestParam(value = "id", required = true) Long id,
			@RequestParam(value = "secret", required = true) String secret) {
		ModelMap map = new ModelMap();
		Enterprise enterprise = enterpriseService.findByEnUU(id);
		if (enterprise == null) {
            throw new SystemError(ErrorUtils.EN_ID_NOT_FOUND);
        }
		if (enterprise.getAccessSecret() == null) {
            throw new SystemError(ErrorUtils.EN_IS_NOT_ALLOWED);
        }
		if (!secret.equals(enterprise.getAccessSecret())) {
            throw new SystemError(ErrorUtils.SECRET_IS_ERROR);
        }
		try {
			// 将企业信息、企业管理员信息写入SystemSession
			User user = userService.findUserByUserUU(enterprise.getEnAdminuu());
			if (user != null) {
				user.setEnterprise(enterprise);
				user.setIp(AgentUtils.getIp(request));
				SystemSession.setUser(user);
			} else {
                throw new SystemError(ErrorUtils.EN_NOT_FOUND);
            }
			AccessToken token = accessTokenService.createNew(null, 7200);
			map.put("access_token", token.getId());
			map.put("time", token.getTime());
			map.put("expires_in", token.getExpires_in());
		} finally {
			SystemSession.clear();
		}
		return map;
	}

}
