package com.bcxin.platform.web.controller.oauth;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.bcxin.platform.common.constant.Constants;
import com.bcxin.platform.common.utils.Result;
import com.bcxin.platform.common.utils.StringUtils;
import com.bcxin.platform.domain.company.PerBaseInfo;
import com.bcxin.platform.dto.oauth.AccessToken;
import com.bcxin.platform.service.company.PerBaseInfoService;
import com.bcxin.platform.service.oauth.OAuthService;
import com.bcxin.platform.service.system.ISysConfigService;
import com.bcxin.platform.util.AESUtil;
import com.bcxin.platform.util.constants.CommonConst;
import com.bcxin.platform.web.controller.base.BaseController;
import com.github.pagehelper.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 客户端OAuth2.0登陆
 *
 * @author zhangye
 */
@RestController
@RequestMapping(value = "/oauth")
public class OauthTokenController extends BaseController {

    @Resource
    private OAuthService oAuthService;

    @Autowired
    private PerBaseInfoService perBaseInfoService;

    @Autowired
    private ISysConfigService sysConfigService;

    @RequestMapping("v5/accesstoken")
    public Result authorizeWebV5(HttpServletRequest request, HttpServletResponse response)throws Exception{
        try {
            String token = request.getParameter("token");
            if(StrUtil.isEmpty(token)){
                return Result.fail("token缺失");
            }
            String tlkId = AESUtil.decode(token);
            PerBaseInfo perBaseInfo = perBaseInfoService.selectPerBaseInfoByTlkId(tlkId);
            if(perBaseInfo == null){
                return Result.fail("用户不存在："+tlkId);
            }
            AccessToken accessToken = oAuthService.getAccessToken(CommonConst.CLIENTTYPE_WEB,perBaseInfo);

            return Result.success("获取accesstoken成功",accessToken).setBack(request);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("token错误");
        }
    }

    /**
     * WEB段登陆验证
     *
     * @throws Exception
     */
    @PostMapping(value = "web/accesstoken")
    public Result authorizeWeb(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // WEB客户端
        String clientType = CommonConst.CLIENTTYPE_WEB;
        // 获取操作权限
        return oAuthService.saveDispatch(req, resp, clientType).setBack(getRequest());
    }

    /**
     * 管理后台段登陆验证
     *
     * @throws Exception
     */
    @PostMapping(value = "manage/accesstoken")
    public Result authorizeManage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String user_token = req.getParameter("token");
        String username = AESUtil.decode(user_token);
        UsernamePasswordToken token = new UsernamePasswordToken(username, username, true);
        token.setHost(Constants.MANAGE_V5);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            Session session = subject.getSession();
            req.setAttribute("sid",session.getId());
            req.getSession().setAttribute("sid",session.getId());
            return Result.success("",session.getId());
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return Result.fail(msg);
        }
    }

    /**
     * 手机端登陆验证
     *
     * @throws Exception
     */
    @RequestMapping("mobile/accesstoken")
    public Result authorizeMobile(HttpServletRequest request, HttpServletResponse response)throws Exception{
        try {
            String v5Url = sysConfigService.selectConfigByKey(Constants.V5_URL);
            if(StringUtil.isEmpty(v5Url)){
                return Result.fail("V5地址未配置");
            }
            String tlkAccessToken = request.getParameter("token");

            v5Url += "?accessToken=" + tlkAccessToken;

            String result = HttpUtil.get(v5Url);
            Result tlkResult = JSON.parseObject(result, Result.class);
            Map resultMap = JSON.parseObject(tlkResult.getData().toString(), Map.class);
            String tlkUserId = !ObjectUtil.isNull(resultMap.get("id")) ? resultMap.get("id").toString() : "";
            PerBaseInfo perBaseInfo = perBaseInfoService.selectPerBaseInfoByTlkId(tlkUserId);
            AccessToken accessToken = oAuthService.getAccessToken(CommonConst.CLIENTTYPE_MOBILE,perBaseInfo);
            return Result.success("获取accesstoken成功",accessToken).setBack(request);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("token错误");
        }
    }

    public static void main(String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTYyNzA0MzEwNywidXNlcm5hbWUiOiJfX0NBeVA4YnhhWWZlM29PdXE4ZG4ifQ.yI4O_HH4fC1Jel6Iq-Gx49qwekuXRnv5tHZ2oriphpA";
        String v5Url = "http://117.78.35.63:8080/obpm/runtime/users/myprofile?accessToken=" + token;

        String result = HttpUtil.get(v5Url);
        System.out.println(result);


    }

}
