package com.weaver.seconddev.cussso.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.common.hrm.domain.organization.HrmConditionResultType;
import com.weaver.common.hrm.domain.organization.HrmOrgEmpCondition;
import com.weaver.common.hrm.entity.employee.HrmEmployee;
import com.weaver.common.hrm.remote.HrmRemoteEmployeeService;
import com.weaver.ebuilder.datasource.api.enums.SourceType;
import com.weaver.ebuilder.datasource.api.service.DataSetService;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.teams.api.remote.RemotePassportService;
import com.weaver.teams.domain.user.SimpleEmployee;
import com.weaver.teams.passport.entity.ThirdSSOLoginRequest;
import com.weaver.teams.passport.entity.ThirdSSOLoginResponse;
import com.weaver.teams.security.cas.IpUtil;
import org.apache.axis.client.Call;
import org.apache.axis.transport.http.HTTPConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.encoding.XMLType;
import java.util.*;

@Service
public class CusSSOServiceImpl {

    private static final Logger log = LoggerFactory.getLogger(CusSSOServiceImpl.class);

    @RpcReference
    private RemotePassportService remotePassportService;

    @RpcReference
    private HrmRemoteEmployeeService hrmRemoteEmployeeService;

    @Autowired
    private DataSetService dataSetService;

    @Autowired
    private CusVarModule cusVarModule;

    public Map<String, String> login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> loginMap = new HashMap();
        String redirectUrl = request.getParameter("redirectUrl");
        log.error("sd6=>redirectUrl:" + java.net.URLDecoder.decode(redirectUrl, "utf-8"));
        String ltpaToken = "123";
        Cookie[] cks = request.getCookies();
        if (cks != null) {
            for (int i = 0; i < cks.length; i++) {
                Cookie ck = cks[i];
                if (ck.getName().equalsIgnoreCase("LtpaToken")) {
                    ltpaToken = ck.getValue();
                }
            }
        }
        log.error("sd6=>ltpaToken:" + ltpaToken);
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String systemId = "SYS006";
        String targetNamespace = "http://hengtong.com/CRM/HTPortalSSO";
        String typeNamespace = "http://webservice.ht_sso_webservice.com";
// webservice路径
        String endpoint = "http://sappop.htgd.com.cn:50000/XISOAPAdapter/MessageServlet?senderParty=&senderService=BS_CRM_POP&receiverParty=&receiverService=&interface=SI_HTPortalSSO_OUT&interfaceNamespace=http%3A%2F%2Fhengtong.com%2FCRM%2FHTPortalSSO";
// 定义service对象
        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
// 创建一个call对象
        Call call = (Call) service.createCall();
//设置6000秒等待
        call.setTimeout(300000);
// 设置目标地址，即webservice路径
        call.setTargetEndpointAddress(endpoint);
// 设置操作名称，即方法名称

        call.setOperationName(new QName(typeNamespace, "allInter"));
        call.addParameter(new QName(typeNamespace, "ltpaToken"), XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter(new QName(typeNamespace, "systemID"), XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter(new QName(typeNamespace, "ipAddress"), XMLType.XSD_STRING, ParameterMode.IN);

//call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
//call.setReturnClass(String[].class);

        call.setReturnClass(java.lang.String.class);
        call.setReturnQName(new QName(typeNamespace, "allInterReturn"));

        call.setUseSOAPAction(true);
        call.setSOAPActionURI("http://sap.com/xi/WebService/soap1.1");


        Hashtable<String, String> headers = (Hashtable<String, String>) call.getProperty(HTTPConstants.REQUEST_HEADERS);
        if (headers == null) {
            headers = new Hashtable<String, String>();
            call.setProperty(HTTPConstants.REQUEST_HEADERS, headers);
        }
        headers.put("Authorization", "Basic cG91c2VyOmh0anRfMjAxOA==");
        try {

            String usn = "";

            Object[] val = new Object[3];
            val[0] = decodeBase64(ltpaToken);
            val[1] = systemId;
            val[2] = ip;
//log.error(val[0]);
//log.error(val[1]);
//log.error(val[2]);

            String workcode = (String) call.invoke(val);
            log.error("sd6=>" + ltpaToken + "单点返回：" + workcode);
//workcode ="message=success;outid=2018030694;validityDate=2018-08-16-20:48:00 CST;htgroup_mail=;htgd_mail=xiejin@htgd.com.cn";
            if (workcode.indexOf("success", 0) != -1) {
                //log.error("sd6=>get workcode:"+workcode);
                usn = workcode.substring(workcode.indexOf("outid=", 0) + 6, workcode.indexOf(";", workcode.indexOf("outid=", 0) + 6));
                log.error("sd6=>workcode:" + usn);
            }

            log.error("sd6=>login by test:" + request.getParameter("cus_action"));
            if ("test".equals(request.getParameter("cus_action"))) {
                log.error("sd6=>login by test");
                usn = "2022050353";
            }

            if ("".equals(usn)) {
                //response.sendRedirect("/wui/index.html");
                loginMap.put("redirectUrl", "/");
                loginMap.put("msg", "workcode解析为空");
                return loginMap;
            }

            String loginid = usn;

            String tk = null;

            String error_code = "0";
            if (error_code.equals("0")) {//这里是老代码 看起无用
                log.error("sd6=>loginid:" + usn);
                //主管级租户
                String maintk = cusVarModule.getTenantkey();
                //查用户信息
                SimpleEmployee simpleEmployee = remotePassportService.findEmployeeByLoginName(loginid, maintk);
                log.error("sd6=> findEmployeeByLoginName：{}", JSONUtil.toJsonStr(simpleEmployee));
                if (simpleEmployee == null) {
                    throw new RuntimeException("登录失败，获取用户信息失败。登录账户:" + loginid);
                }
                JSONObject useInfo = getUser(simpleEmployee.getEmployeeId());
                String filed3 = useInfo.getString("field3");//获取租户的标识
                //查需要登录得租户
//                HrmEmployee hrmEmployee = getLoginTk(employeeByLoginName.getEmployeeId(), maintk);
//                tk = hrmEmployee.getTenantKey();

                tk = getLoginTk(filed3);
                log.error("sd6=> ssologin tk：" + tk);
                //再用子租户查一次
                if (tk != null && !"".equals(tk)) {
                    SimpleEmployee subSimpleEmployee = remotePassportService.findEmployeeByLoginName(loginid, tk);
                    log.error("sd6=> finduser by subTenantKey：{}", JSONUtil.toJsonStr(subSimpleEmployee));
                    if (subSimpleEmployee != null) {
                        simpleEmployee = subSimpleEmployee;
                    }else{
                        throw new RuntimeException("登录失败，租户["+tk+"]登录账户["+loginid+"]没有对应的人员");
                    }
                } else {
                    //默认主租户
                    tk = maintk;
                }

                //登录
                ThirdSSOLoginRequest ssoLoginRequest = new ThirdSSOLoginRequest();
                ssoLoginRequest.setLoginChannel("cussso");
                ssoLoginRequest.setIp(IpUtil.getRemoteHost(request));
                ssoLoginRequest.setTenantKey(tk);

//                String id = Objects.toString(employeeByLoginName.getEmployeeId(), "-1");
//                String user_id = Objects.toString(employeeByLoginName.getUserId(), "-1");

                ssoLoginRequest.setUserId(simpleEmployee.getUserId());
                ssoLoginRequest.setEmployeeId(simpleEmployee.getEmployeeId());
//                log.error("sd6=> ssoLoginRequest {},{},{},{}", tk, id, user_id);
                log.error("sd6=> ssoLoginRequest param {}", JSONUtil.toJsonStr(ssoLoginRequest));
                WeaResult<ThirdSSOLoginResponse> thirdSSOLoginResponseWeaResult = remotePassportService.thirdSSOLogin(ssoLoginRequest);
                log.error("sd6=> ssoLoginRequest res {}", thirdSSOLoginResponseWeaResult.getData());

                Cookie eteamsidCk = new Cookie("ETEAMSID", thirdSSOLoginResponseWeaResult.getData().getEteamsId());
                eteamsidCk.setPath("/");
                response.addCookie(eteamsidCk);

//                Cookie eteamsidCk1 = new Cookie("ETEAMSID", thirdSSOLoginResponseWeaResult.getData().getEteamsId());
//                log.error("sd6=> login cookie domain1:"+host.getHost());
//                String domain = getDomain(host.getHost());
//                log.error("sd6=> login cookie domain2:"+domain);
//                eteamsidCk1.setDomain(domain);
//                eteamsidCk1.setPath("/");
//                httpServletResponse.addCookie(eteamsidCk1);
                loginMap.put("redirectUrl", redirectUrl);
                loginMap.put("msg", "未查询到用户");
                return loginMap;
            } else {//失败
                //跳转到错误页面
                loginMap.put("redirectUrl", "/");
                loginMap.put("msg", "未查询到用户");
                return loginMap;
            }
        } catch (Exception e) {
            loginMap.put("redirectUrl", "/");
            loginMap.put("msg", e.getMessage());
            log.error("sd6=>" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    private String getLoginTk(String filed3) throws Exception {
        log.error("sd6=> getLoginTkByFiled3() start zhbs：" + filed3);
        String sql = "select zzkey from uf_tenant_mt where zhbs='" + filed3 + "'";

        Map<String, Object> exeMap = dataSetService.executeSql(SourceType.LOGIC, "weaver-ebuilder-form-service", sql, "", new Object[]{});
        log.error("sd6=> getUser resMap:" + JSON.toJSONString(exeMap));
        if (exeMap == null || !exeMap.containsKey("records")) {
            //throw new Exception("获取租户失败 zhbs：" + filed3);
            return null;
        }

        Object records = exeMap.get("records");
        if (records != null) {
            JSONArray dataArr = JSONArray.parseArray(JSON.toJSONString(records));
            if (dataArr != null && dataArr.size() > 0) {
                return dataArr.getJSONObject(0).getString("zzkey");
            }
        }

        return null;
    }

    private HrmEmployee getLoginTk(Long employeeId, String maintk) {
        //通过rpc查 直接查数据表
        HrmOrgEmpCondition condition = new HrmOrgEmpCondition();
        condition.setContainExtra(true);
        condition.setIds(Arrays.asList(employeeId));
        condition.setTenantKey(maintk);

        List<HrmEmployee> objects = hrmRemoteEmployeeService.queryEmpsByCondidtion(condition, HrmConditionResultType.BEAN.name());
        if (objects == null || objects.size() == 0) {
            throw new RuntimeException("未查用户的登录租户 employeeId：" + employeeId + ",tenantKey=" + maintk);
        }
        HrmEmployee hrmEmployee = objects.get(0);

        log.error("sd6=> getHrmInfo {}", hrmEmployee);
        return hrmEmployee;
    }

    private JSONObject getUser(Long employeeId) throws Exception {
        log.error("sd6=> getUser() start employeeId：" + employeeId);
        String sql = "select emp.id,emp.user_id,b.field3 from {$publicdb}.employee emp inner join {$publicdb}.hrmemployeedefined b on emp.formdata = b.FORM_DATA_ID where emp.id=" + employeeId;

        Map<String, Object> exeMap = dataSetService.executeSql(SourceType.LOGIC, "weaver-ebuilder-form-service", sql, "", new Object[]{});
        log.error("sd6=> getUser resMap:" + JSON.toJSONString(exeMap));
        if (exeMap == null || !exeMap.containsKey("records")) {
            throw new Exception("未匹配到单点登录用户,call by " + Thread.currentThread().getStackTrace()[2].getClassName() + "." + Thread.currentThread().getStackTrace()[2].getMethodName());
        }

        Object records = exeMap.get("records");
        if (records != null) {
            JSONArray dataArr = JSONArray.parseArray(JSON.toJSONString(records));
            return dataArr.getJSONObject(0);
        }

        throw new Exception("未匹配到单点登录用户,call by " + Thread.currentThread().getStackTrace()[2].getClassName() + "." + Thread.currentThread().getStackTrace()[2].getMethodName());

    }


    public String decodeBase64(String s) {
        switch (s.length() % 4) {
            case 3:
                s += "===";
                break;
            case 2:
                s += "==";
                break;
            case 1:
                s += "=";
                break;
            default:
        }
        return s;
    }
}
