package cn.iselab.mooctest.user.service.impl;

import cn.iselab.mooctest.user.configure.ThirdPartyAuthConfiguration;
import cn.iselab.mooctest.user.data.UserInfo;
import cn.iselab.mooctest.user.mapper.UserThirdPartyDao;
import cn.iselab.mooctest.user.model.UserThirdParty;
import cn.iselab.mooctest.user.service.ThirdPartyAuthService;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;


/**
 * @Description: 第三方验证服务
 * @Author: xuexb
 * @CreateDate: 19-1-8$ 上午1:23$
 */
@Service
public class ThirdPartyAuthServiceImpl implements ThirdPartyAuthService {

    Logger logger = LoggerFactory.getLogger(ThirdPartyAuthServiceImpl.class);

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    HttpEntity<String> entity;

    @Autowired
    UserThirdPartyDao userThirdPartyDao;

    @Override
    public String getAccessToken(String url, String code) {
        String result = "";
        try{
            url = url.replace("CODE", code);
            result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
        }catch (Exception e){
            logger.error("获取access_token出错", e);
        }
        JSONObject object = new JSONObject(result);
        String accessToken = object.getString("access_token");
        logger.info("accessToken: "+ accessToken);
        return accessToken;
    }

    @Override
    public UserInfo getGithubUserInfo(String url, String accessToken) {
        url = url.replace("ACCESSTOKEN", accessToken);
        String tmp = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
//        String result = restTemplate.getForObject(url ,String.class);
        JSONObject result = new JSONObject(tmp);
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(result.getString("login"));
        userInfo.setHeadimgurl(result.getString("avatar_url"));
        userInfo.setThirdPartyId(""+result.getLong("id"));
        return userInfo;
    }

    @Override
    public UserThirdParty findByThirdIdAndType(String identity, String type) {
        return userThirdPartyDao.findByThirdPartyIdentityAndType(identity, type);
    }

    @Override
    public UserThirdParty save(UserThirdParty userThirdParty) {
        return userThirdPartyDao.save(userThirdParty);
    }

    @Override
    public List<UserThirdParty> findByUserId(Long userId) {
        return userThirdPartyDao.findByUserId(userId);
    }
}
