package com.hzya.frame.bip.v3.v2207.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.bip.v3.v2207.entity.BipTokenVo;
import com.hzya.frame.bip.v3.v2207.service.IBipSsoService;
import com.hzya.frame.iputil.IPUtil;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import nccloud.security.impl.SignatureTookKit;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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


@Service(value = "BipSsoServiceImpl")
public class BipSsoServiceImpl extends BaseService<BipTokenVo, String> implements IBipSsoService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final  String BASEURL = "http://192.168.2.237:8099/seeyon/thirdpartyController.do?ticket=";
    private final  String ESBURL = "http://127.0.0.1:9081/kangarooDataCenterV3/entranceController/externalCallInterface";
    /**
     *
     * @content Bip单点统一认证接口
     * @author laborer
     * @date 2024/5/30 0030 13:45
     *
     */

    @Override
    public String erpSso(HttpServletRequest request,String userCode)throws Exception {
        logger.info("当前IP地址为"+ JSON.toJSONString(IPUtil.getIpAddress(request)));
        String result = "";
        boolean flag = true;
//        logger.info("接收到致远OA认证参数的ticket：{}",ticket);
        //通过ticket获取OA用户信息
//        String userCode  = HttpUtil.get(BASEURL+ticket);
        logger.info("获取到的OA用户信息：{}",userCode);
        String dsname = "ycjf";
        String client_id = "OAREST";//第三方系统id
        StringBuffer sb = new StringBuffer();
        if(StrUtil.isNotEmpty(userCode)){
            try {
                logger.info("开始加密");
                String security = genKey(userCode,userCode  + (System.currentTimeMillis() + "").substring(0, 6));
                logger.info("加密结束：{}",security);
                sb.append("type=type_security&dsname="+dsname+"&usercode="+userCode+"&client_id="+client_id+"&security="+security);
                String baseUrl = "http://10.75.51.78:8899/service/genThirdPartyAccessToken?"+sb.toString();
                logger.info("请求BIPtokenbaseUrl：{}",baseUrl);
                 result = HttpRequest.post(baseUrl)
                        .header("Content-Type", "application/x-www-form-urlencoded")//头信息，多个头信息多次调用此方法即可
                        .header("Content-Length", "10000")//头信息，多个头信息多次调用此方法即可
                        .header("userid", "admin")//头信息，多个头信息多次调用此方法即可
                        .body("{}")//表单内容
                        .timeout(20000)//超时，毫秒
                        .execute().body();
                logger.info("获取到的BIPtoken信息：{}",result);
            } catch (HttpException e) {
                flag=false;
                e.printStackTrace();
            }
        }
        if(flag){
            String indexUR = "http://10.75.51.78:8899/nccloud/resources/uap/rbac/thirdpartylogin/main/index.html?accesstoken="+result+"&redirect_uri=http://10.75.51.78:8899/nccloud/resources/workbench/public/common/main/index.html#";
            logger.info(indexUR);
            return  indexUR;
        }else{
            return "http://10.75.51.78:8899/nccloud/resources/uap/rbac/login/main/index.html";
        }
    }
    /**
     *
     * @content 此方法获取sso动态加密，heade参数动态传入
     * @author laborer
     * @date 2024/5/27 0027 11:38
     *
     */

    @Override
    public SysExtensionApiEntity ssoEncrypt(SysExtensionApiEntity entity) {
        try {
            Map<String, String> headers = entity.getHeaders();
            String userCode = headers.get("usercode");//用户编码
            String dsname = headers.get("dsname");//数据源
            String client_id = headers.get("client_id");//第三方系统id
            StringBuffer sb = new StringBuffer();
            String security = genKey(userCode,userCode  + (System.currentTimeMillis() + "").substring(0, 6));
            StringBuffer querys = new StringBuffer();
            querys.append("type=type_security");
            querys.append("&dsname="+dsname);
            querys.append("&usercode="+userCode);
            querys.append("&client_id="+client_id);
            querys.append("&security="+security);
            entity.setQuerys(querys.toString());
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            headers.put("userid", "admin");
            entity.setHeaders(headers);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }
    /**获取NCC的key*/
    private static String genKey(String userid, String key) throws Exception {
        return new Base64().encodeToString(SignatureTookKit.digestSign(userid.getBytes(), key.getBytes()));
    }

}
