package com.qianhe.web.controller.system;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qianhe.common.constant.Constants;
import com.qianhe.common.core.domain.AjaxResult;
import com.qianhe.common.core.domain.entity.SysUser;
import com.qianhe.common.utils.DateUtils;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.common.utils.ip.IpUtils;
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.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
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";

                            //集成登录日志
                            SysUser u = userService.selectUserByUserName(login_name);
                            String name = u.getNickName();//姓名
                            String deptFullName = "/中国石化/胜利油田/胜利石油管理局有限公司/供水分公司/管理部门/经营管理部（三基工作办公/";
//                            String orgName = "供水分公司";
//                            String dptName = "管理部门";
//                            if("zhangshy819".equals(uid)) {
//                                deptFullName = "/中国石化/胜利油田/胜利油田分公司/数智化管理服务中心/保障服务系统/软件研发服务部/";
//                                orgName = "数智化管理服务中心";
//                                dptName = "保障服务系统";
//                            }

                            List values = ssoPrincipal.getValueAsList("spOrgNamePath");
                            StringBuffer vbuf = new StringBuffer();

                            for(int j = 0; values != null && j < values.size(); ++j) {
                                Object value = values.get(j);
                                vbuf.append(value.toString());
                                if (j < values.size() - 1) {
                                    vbuf.append(',');
                                }
                            }
                            deptFullName = vbuf.toString(); //获取单位全程
//                            if(StringUtils.isNotEmpty(deptFullName)){
//                                String[] split = deptFullName.split("/");
//                                if(split.length > 3){
//                                    orgName = split[3];
//                                }
//                                if(split.length > 4){
//                                    dptName = split[4];
//                                }
//                            }
                            System.out.println("  == 姓名  ==" + name);
                            System.out.println("  == Uid  ==" + uid);
                            System.out.println("  == 单位  ==" + values);
                            System.out.println("  == 单位  ==" + deptFullName);
                            u.setRemark(deptFullName);
                            userService.updateUserRemark(u);//只更新 备注 存统一单位信息

                            Map<String, Object> map1 = new HashMap<>();
                            map1.put("UserName", name);
                            map1.put("Uid", uid);
//                            map1.put("age", 30);
                            map1.put("DateTime", DateUtils.getTime());
//                            map1.put("OrgName", orgName);
//                            map1.put("DeptName", dptName);
                            map1.put("DeptFullName", deptFullName);
                            map1.put("isStudent", false);
                            map1.put("Type", "登录");
                            map1.put("Status", "成功");
                            try {
                                JsonObject jsonObject = sendSysLog("LoginLog", map1);
                                System.out.println("  == 结果  ==" + jsonObject.getAsJsonObject());
                                //获取日志
                                JsonObject sysLog = getSysLog();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
//                }
//            }

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


    /**
     * 发送日志请求
     * @param tag 日志类型（LoginLog、UserOpeLog、ErrorLog、IServiceLog、ComponentOpeLog、DBOpeLog、BusinessLog）
     * @param map 日志内容
     */
    public JsonObject sendSysLog(String tag, Map<String,Object> map) throws Exception {
        //本地ip
//        String ip = IpUtils.getHostIp();
        //客户端ip
        String ip = IpUtils.getIpAddr();
        String url="http://api.ssco.sinopec.com/PUBService.log.transferLogs?appname=APP_SLYT_SJGLXT&tag="+tag+"&hostname=" + ip;
        Gson gson = new Gson();
        String input = gson.toJson(map);
        URL targetUrl = new URL(url);
        HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setRequestMethod("POST");
        httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8;");
        httpConnection.setRequestProperty("X-Ca-API-Key", "ee8d6cdbda2548f391a4b9389718abf7");
        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(input.getBytes("UTF-8"));
        outputStream.flush();
        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + httpConnection.getResponseCode());
        }
        InputStream inputStream = httpConnection.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        buffer.flush();
        byte[] binaryData = buffer.toByteArray();

        // 将二进制数据转换为字符串（假设是 UTF-8 编码的 JSON）
        String jsonString = new String(binaryData, "UTF-8");

        // 使用 Gson 解析 JSON 字符串
        JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();

        System.out.println(jsonObject);
        httpConnection.disconnect();
        return jsonObject;
    }



    /**
     * 获取日志
     */
    public static JsonObject getSysLog() throws Exception {
        String apiUrl = "http://api.ssco.sinopec.com/api/v2/search/sheets/";
        String query = "appname:APP_SLYT_SJGLXT";
        String timeRange = "-1h,now";
        boolean timeline = false;
        String searchMode = "simple";
        String url = apiUrl + "?query=" + query
                + "&time_range=" + timeRange
                + "&timeline=" + timeline
                + "&searchMode=" + searchMode;
        URL targetUrl = new URL(url);
        HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("X-Ca-API-Key", "ee8d6cdbda2548f391a4b9389718abf7");
        httpConnection.setRequestProperty("Authorization","apikey lih2365:OYeEzLnOZiSPTNlKouAgeEQuTsokAvLA");
        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + httpConnection.getResponseCode());
        }
        InputStream inputStream = httpConnection.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        buffer.flush();
        byte[] binaryData = buffer.toByteArray();

        // 将二进制数据转换为字符串（假设是 UTF-8 编码的 JSON）
        String jsonString = new String(binaryData, "UTF-8");

        // 使用 Gson 解析 JSON 字符串
        JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
        httpConnection.disconnect();
        return jsonObject;
    }



//    @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;
//    }

}
