package com.qianhe.web.controller.system;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.qianhe.common.constant.Constants;
import com.qianhe.common.core.domain.AjaxResult;
import com.qianhe.framework.web.service.SysLoginService;
import com.qianhe.system.mapper.SysUserMapper;
import com.qianhe.system.service.ISysUserService;
import com.sinopec.siam.agent.common.ContextHolder;
import com.sinopec.siam.agent.common.SSOPrincipal;
import com.sinopec.siam.agent.common.SamlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一认证登录
 *
 */
@Controller
public class SiamloginController {


//    private static final String VUEHOST = "https://jd.osgc.sinopec.com:249";
    private static final String VUEHOST = "http://ydsj.slof.com:9034";


    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysLoginService loginService;

    @RequestMapping("/siamlogin")
    public String login() {
        System.out.println("1.1.0:");
        SamlSession SamlSession = ContextHolder.getContext();
        System.out.println("1.1.0:SamlSession"+SamlSession);
        System.out.println("1.1.0:SamlSession"+SamlSession);
        SSOPrincipal ssoPrincipal = ((SSOPrincipal)SamlSession.getAttribute(SSOPrincipal.NAME_OF_SESSION_ATTR));
        System.out.println("1.1.0:ssoPrincipal"+ssoPrincipal);

        String tzlx = "0";  // 0跳转到无权限界面   1跳转到首页
        System.out.println("1.1.1:tzlx"+tzlx);
        String JwtToken =null;
        if(null !=ssoPrincipal){
//            String[] appAcount = ssoPrincipal.getAppAccount();
//            System.out.println("\n 1.1.1_2 :tzlx"+appAcount);
//            //应用账号（getappaccount）是否为空
//            if(appAcount != null && appAcount.length > 0) {
//                //应用账号（getappaccount）是否是本应用
//                if (Arrays.binarySearch(appAcount, "地球物理节点数据处理与质控系统") > 0) {
                    String uid = ssoPrincipal.getUid();
                    System.out.println("1.1.2:uid"+uid);
                    String adAccountName = ssoPrincipal.getSingleValue("ADAccountName");
                    System.out.println("1.1.3:adAccountName"+adAccountName);
                    Map map = new HashMap();
                    map.put("uid", uid);//不带后缀 sl-npp
                    map.put("adAccountName", adAccountName);//带后缀 sl-npp.osgc
//                     JwtToken = loginService.loginSam("admin","ydzk@#2024");
//            tzlx="1";
                    if (null !=uid) {
                        //查询当前账号是否存在于本系统库
                        String login_name = userMapper.selectUserBySiam(map);
                        System.out.println("1.1.4:login_name"+login_name);
                        if(null!=login_name&&!"".equals(login_name)){
                            //伪登录
                            JwtToken = loginService.loginSam(login_name,"gfjsmm3@5");

                            tzlx="1";
                        }
                    }
//                }
//            }

        }
        System.out.println(tzlx);
        if(tzlx.equals("0")){
            return "redirect:"+VUEHOST+"/noaccess";
            //无权限
        }else {
            return "redirect:"+VUEHOST+"/remotelogin?token="+JwtToken;
        }
    }





//    @GetMapping("/jwtLogin")
//    @ResponseBody
//    public AjaxResult jwtLogin(JwtLoginInfo jwtLoginInfo, HttpServletRequest request) {
//        //获取ip
//        String xfHeader = request.getHeader("X-Forwarded-For");
//        if (xfHeader == null) {
//            xfHeader = request.getHeader("X-Real-IP");
//        }
//        String ip="";
//        if(xfHeader!=null){
//            // 通常情况下，"X-Forwarded-For" 头字段可能包含多个IP地址，
//            // 第一个IP地址是客户端的真实IP地址
//            String[] xfAddr = xfHeader.split(",");
//            ip=xfAddr[0].trim();
//        }else {
//            ip="10.249.139.249";
//        }
//        String username = jwtLoginInfo.getUsername();
//        System.out.println("=====username"+username);
//        String password = jwtLoginInfo.getPassword();
////        password ="pcitc@#2020";
//        System.out.println("=====password"+password);
//        //加密链接账号和密码
//        String ljzhEncoded = base64("dqwl_7683_01", "encoded");
//        //加密用户名
//        String userNameEncoded = base64(username, "encoded");
//
//        System.out.println("=====userNameEncoded"+userNameEncoded);
//        //加密密码
//        String pwEncoded = base64(password, "encoded");
//        System.out.println("=====pwEncoded"+pwEncoded);
//        //测试
////        String ceurl="https://jwt2.uat.siam.sinopec.com/jwt2/jwtauth";
//        //        HashMap<String, Object> paramMap = new HashMap<>();
////        paramMap.put("username", userNameEncoded);
////        paramMap.put("password", pwEncoded);
////        paramMap.put("appId", "7683");
////        paramMap.put("clientIp", ip);
////        paramMap.put("isencryption", "1");
////        System.out.println("===url"+ceurl);
////        System.out.println("===paramMap"+paramMap.toString());
//        //正式
//        String url="https://jwt.siam.sinopec.com/jwt2/jwtauth";
//        HashMap<String, Object> paramMap = new HashMap<>();
//        paramMap.put("username", userNameEncoded);
//        paramMap.put("password", pwEncoded);
//        paramMap.put("appId", "203935");
//        paramMap.put("clientIp", ip);
//        paramMap.put("isencryption", "1");
//        System.out.println("===url"+url);
//        System.out.println("===paramMap"+paramMap.toString());
//        //链式构建请求
//        String result2 = HttpRequest.post(url)
//                .header("Content-Type", "application/x-www-form-urlencoded")
//                .header("Authorization", "Bearer ZHF3bF8yMDM5MzVfMDE=:SlRXY21fOHczaHI=")
//                .form(paramMap)//表单内容
//                .timeout(20000)//超时，毫秒
//                .execute().body();
//
//        System.out.println("=========请求结果"+result2);
//        JSONObject object = JSONObject.parseObject(result2);
//        System.out.println("=========转换结果"+object);
//        String result = object.get("result").toString();
//
//        if(result.equals("1")){
//            String jwttoken = object.get("jwttoken").toString();
//            System.out.println("======jwttoken"+jwttoken);
//            String[] chunks = jwttoken.split("\\.");
//            Base64.Decoder decoder = Base64.getUrlDecoder();
////            String header = new String(decoder.decode(chunks[0]));
//            String payload = new String(decoder.decode(chunks[1]));
//            System.out.println("payload======"+payload);
//            JSONObject objectinfo = JSONObject.parseObject(payload);
//            System.out.println("======objectinfo"+objectinfo);
//            String uid = objectinfo.get("uid").toString();
//            System.out.println("======uid"+uid);
//            JSONArray accountidArr = objectinfo.getJSONArray("accountid");
//            String accountid="";
//            if(accountidArr.size()>0){
//                accountid=accountidArr.get(0).toString();
//            }else{
//                return AjaxResult.error("您无权限访问系统，请联系管理员！");
//            }
//            System.out.println("======accountid"+accountidArr);
//            Map map = new HashMap();
//            map.put("uid", uid);//不带后缀 sl-npp
//            map.put("adAccountName", accountid);//带后缀 sl-npp.osgc
//            String login_name = userMapper.selectUserBySiam(map);
//            System.out.println("1.1.4:login_name"+login_name);
//            if(null!=login_name&&!"".equals(login_name)){
//                //伪登录
//                String  JwtToken = loginService.loginSam(login_name,"ydzk@#2024");
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put(Constants.TOKEN, JwtToken);
//                return ajax;
//            }else {
//                return AjaxResult.error("未在系统内查询到相关账号，请联系管理员！");
//            }
//
//        }else {
//            return AjaxResult.error(object.get("message").toString());
//        }
//
//    }
//
//
//    public static void main(String[] args) {
////        String token="eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJ1aWQiOiJuaWVzaHNoMjYiLCJvdSI6IuaWsOS4muWKoeS6i-S4mumDqCIsInNwb3JnbmFtZXBhdGgiOiIv5Lit5Zu955-z5YyWL-efs-ayueW3peeoi-WFrOWPuC_lnLDnkIPniannkIblhazlj7gv5Y2O5YyX5YiG5YWs5Y-4L-aWsOS4muWKoeS6i-S4mumDqC8iLCJjbiI6IuiBguaymeaymSIsImFwcGFjY291bnQiOltdLCJhY2NvdW50aWQiOltdLCJlbXBsb3llZW51bWJlciI6IjAwMjg3NzU1Iiwic2FtbGlkcHRva2VuIjoiTVRBdU1qUTVMakV6T1M0eU5EayUzRCU3Q05UYzFZbVE0TlRaa05UUXlPVFE0WlRKbE9UVXpNVFpqT1RReE9XVTNabUkwTVdJMlltVTBZMlptTjJJeU9XUTJNRFUyTXpVek16QXhNRGMxWVRrME1BJTNEJTNEJTdDeFNxNjhYR1I1aXJZdkhDZHZCaUtlJTJCOWl5b3MlM0QiLCJpc3MiOiJTSUFNIiwic3ViIjoibmllc2hzaDI2IiwiYXVkIjoiNzY4MyIsImlhdCI6MTczODgxMjUwNSwiZXhwIjoxNzM4ODQxMzA1LCJqdGkiOiI4MjM1NTIifQ.MGnRqv3iHWndlTGNyi-GwrCh_tWUOy2wNmMEWF_9KXk";
////        String split = ss.substring(ss.indexOf(".")+1,ss.lastIndexOf("."));
////        System.out.println("======split"+split);
////        Base64.Decoder decoder = Base64.getDecoder();
////        byte[] decodedBytes = decoder.decode(split);
////        String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);
////        String[] chunks = token.split("\\.");
////        Base64.Decoder decoder = Base64.getUrlDecoder();
////
////        String header = new String(decoder.decode(chunks[0]));
////        String payload = new String(decoder.decode(chunks[1]));
////        System.out.println(header);
////        System.out.println(payload);
////        JSONObject objectinfo = JSONObject.parseObject(payload);
////        System.out.println("======objectinfo"+objectinfo);
////        String uid = objectinfo.get("uid").toString();
////        System.out.println("======uid"+uid);
////        JSONArray accountid = objectinfo.getJSONArray("accountid");
////        accountid.get(0);
////        System.out.println("======accountid"+accountid);
//
//// 输出解码后的字符串
//
////设置需要解析的jwt
////        String s = base64("dqwl_203935_01", "encoded");
////        System.out.println(s);
////
////        String s1 = base64("JTWcm_8w3hr", "encoded");
////        System.out.println(s1);
//    }
//    public  String base64(String str, String flag) {
//        byte[] bytes = str.getBytes();
//        if (flag.equals("encoded")) {
//            //Base64 加密
//            String encoded = Base64.getEncoder().encodeToString(bytes);
////            System.out.println("Base 64 加密后：" + encoded);
//            return encoded;
//        }
//        if (flag.equals("decoded")) {
//            byte[] decoded = Base64.getDecoder().decode(str);
//
//            String decodeStr = new String(decoded);
////            System.out.println("Base 64 解密后：" + decodeStr);
//            return decodeStr;
//        }
//        return str;
//    }

}
