package com.hs.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.hs.api.model.SysUser;
import com.hs.api.model.respmodel.LoginInfo;
import com.hs.api.service.LoginService;
import com.hs.api.service.UserService;
import com.hs.common.utils.HttpUtil;
import com.hs.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.models.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

@RestController
@RequestMapping("/page")
@Api(tags = {"登录"})
public class SsoController {
    static final Logger log = LoggerFactory.getLogger(SsoController.class);

    @Value("${indexUri}")
    private String indexUri;

    @Value("${sso.checkUri}")
    private String ssoCheckUri;

    @Value("${sso.loginUri}")
    private String ssoLoginUri;

    @Autowired
    private LoginService loginService;
    @Autowired
    private UserService userService;

    @GetMapping("/index")
    public String Login(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = request.getParameter("Token");
        if (StringUtil.isNullOrEmpty(token)) {
            token = request.getParameter("token");
        }
        //验证token是否有效,有效，则跳转至首页
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response);
        JSONObject jsonObject = checkSsoToken(ssoCheckUri,token);
        if(jsonObject==null){ //不通过，Token无效，跳转sso登录页，并且传参首页地址
            wrapper.sendRedirect(ssoLoginUri + "?URL=" + URLEncoder.encode( indexUri, "UTF-8" ));
        }else{
            //sso的token验证通过，则去匹配系统用户
            String Identity = jsonObject.getString("Identity");
            String UserCode = jsonObject.getString("UserCode");
            Long useId = 0L;
            if(!StringUtil.isNullOrEmpty(Identity)){
                useId  = userService.findUserIdFromDicUser(Identity);
                if(useId==null||useId==0){
                    useId  = userService.findUserIdFromDicUser(UserCode);
                }
            }
            SysUser sysUser = userService.findById(useId);
            if(sysUser==null){//未开通权限
                wrapper.sendRedirect("/ind/error.html");
            }else{//通过,则调登陆接口,将本系统的token传给前端
                String ip = HttpUtil.getIP(request);
                LoginInfo loginInfo = loginService.login(sysUser.getUserCode(), sysUser.getPassword(), sysUser.getMacAddress(), ip);
                wrapper.sendRedirect(indexUri + "?token=" + loginInfo.getToken());
            }
        }
        return "";
    }

    @GetMapping("/403")
    public String to403() {
        return "error";
    }
    /**
     * 校验token
     * @param token
     * @return
     */
    public JSONObject checkSsoToken(String uri, String token) {
        JSONObject jsonObject =  null;
        if (StringUtil.isNullOrEmpty(token)) {
            return null;
        }
        String url = uri + "?token=" + token;
        String result = "" ;
        try{
            result = doGet(url);
            log.info("checkSsoToken result={}",result);
            jsonObject = JSONObject.parseObject(result);
        }catch (Exception e){
            e.printStackTrace();
        }

        return jsonObject;
    }

    //发送http的get请求
    public static String doGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlstring = url;
            URL realurl = new URL(urlstring);
            System.out.println("请求的服务器主机域名：" + realurl.getHost().toString());
            //打开与此URL的连接
            URLConnection connection = realurl.openConnection();
            //设置请求连接时间和读取数据时间
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(7000);
            //建立实际的连接
            connection.connect();
            //读取获取的数据
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                System.out.println("关闭请求流出现异常！" + e2);
                e2.printStackTrace();
            }
        }
        return result;
    }

}
