package com.hzya.frame.webapp.entrance.service.impl;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.hzya.frame.sys.entity.EsbReturnEntity;
import com.hzya.frame.sys.file.download.entity.FileDownloadEntity;
import com.hzya.frame.sys.file.download.service.IFileDownloadService;
import com.hzya.frame.sys.file.upload.entity.FileResultEntity;
import com.hzya.frame.sys.file.upload.entity.FileUploadDto;
import com.hzya.frame.sys.file.upload.entity.FileUploadEntity;
import com.hzya.frame.sys.file.upload.service.IFileUploadService;
import com.hzya.frame.web.action.ApplicationContextUtil;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import com.hzya.frame.webapp.entrance.service.IEntranceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

/**
 * @Content统一根据请求服务处理相关业务service
 * @Author 👻👻👻👻👻👻👻👻👻👻 gjh
 * @Date 2022-12-07 8:47
 * @Version 1.0
 */
@Service(value = "entranceServiceImpl")
public class EntranceServiceImpl implements IEntranceService {

    private final Logger logger = LoggerFactory.getLogger(EntranceServiceImpl.class);
    @Autowired
    private IFileUploadService fileUploadService;
    @Autowired
    private IFileDownloadService fileDownloadService;

    @Override
    @DSTransactional()
    public JsonResultEntity doBusiness(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //tailuo 要访问的Bean名称
        String service = request.getHeader("tl");
        //bean方法
        String serviceMethod = request.getHeader("dj");
        String body = ServletUtil.getBody(servletRequest);
        //获取类
        Object object = null;
        if(service == null || "".equals(service) || serviceMethod == null || "".equals(serviceMethod)){
            return BaseResult.getFailureMessageEntity("非法请求，请检查");
        }
        try {
            object = ApplicationContextUtil.getBeanByName(service);
        } catch (SecurityException e) {
            return BaseResult.getFailureMessageEntity(service + "未找到");
        }
        //获取类下面的方法
        Method[] methods = object.getClass().getMethods();
        if (methods == null || methods.length == 0) {
            logger.error("当前service:" + service + "serviceMethod = " + serviceMethod+"未找到");
            return BaseResult.getFailureMessageEntity(service + "未找到" + serviceMethod + "方法");
        }
        for (Method m : methods) {
            if (null != m) {
                if (m.getName().equals(serviceMethod.trim())) {
                    if (m.getName().startsWith("thirdInterface")) {//TODO 后续可能要加强校验规则
                        logger.info("第三方接口，不校验是否登陆");
                    }else if (!"doLogin".equals(m.getName())&& !"appDoLogin".equals(m.getName())  ) {
                        try {
                            StpUtil.checkLogin();
                            //校验当前登陆人是否有权限
                            // 接口权限验证  开始
                            //boolean flag = false;
                            //String userId =  StpUtil.getLoginIdAsString();
                            ////获取接口
                            //SysInterfaceEntity sysInterfaceEntity = (SysInterfaceEntity) interfaceCache.get("6","beanName"+service+"interfacName"+serviceMethod);
                            //if(sysInterfaceEntity == null || sysInterfaceEntity.getId() == null){
                            //    return BaseResult.getFailureMessageEntity("用户无访问权限，请联系管理员");
                            //}
                            ////查询用户权限
                            //if(!flag){
                            //    SysPopedomInterfaceEntity userPopedomInterfaceEntity = (SysPopedomInterfaceEntity) interfaceCache.get("4","userId"+userId+"interfaceId"+sysInterfaceEntity.getId());
                            //    if(userPopedomInterfaceEntity != null && userPopedomInterfaceEntity.getId() != null ){
                            //        flag = true;
                            //    }
                            //}
                            ////查询用户角色的权限
                            //if(!flag){
                            //    List<SysUserRolesEntity> userRoleMap = (List<SysUserRolesEntity>) interfaceCache.get("3",null);
                            //    if(userRoleMap != null && userRoleMap.size() > 0){
                            //        for (SysUserRolesEntity sysUserRolesEntity : userRoleMap) {
                            //            if(sysUserRolesEntity.getUserId().equals(userId)){
                            //                SysPopedomInterfaceEntity sysPopedomInterfaceEntity = (SysPopedomInterfaceEntity) interfaceCache.get("5","roleId"+sysUserRolesEntity.getRoleId()+"interfaceId"+sysInterfaceEntity.getId());
                            //                if(sysPopedomInterfaceEntity != null && sysPopedomInterfaceEntity.getId() != null ){
                            //                    flag = true;
                            //                    break;
                            //                }
                            //            }
                            //        }
                            //    }
                            //}
                            //if(!flag){
                            //    return BaseResult.getFailureMessageEntity("用户无访问权限，请联系管理员");
                            //}
                            // 接口权限验证  结束
                        } catch (NotLoginException e) {
                            logger.error("zt-token无效");
                            return BaseResult.getFailureMessageEntity("zt-token无效");
                        }
                    }
                    JSONObject jsonObject = new JSONObject();
                    if (!ObjectUtils.isEmpty(body)) {
                        jsonObject.put("jsonStr", body);
                    }
                    JsonResultEntity jsonResultEntity;
                    try {
                        logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>请求的参数：jsonObject：" + jsonObject.toJSONString());
                        jsonResultEntity = (JsonResultEntity) m.invoke(object, jsonObject);
                        logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        return jsonResultEntity;
                    } catch (Exception e) {
                        logger.error("METHOD doBusiness invokeException{}", e.getMessage());
                        if (e instanceof InvocationTargetException) {
                            Throwable targetException = ((InvocationTargetException) e).getTargetException();
                            if (targetException instanceof BaseSystemException) {
                                throw new BaseSystemException(targetException.getMessage());
                            } else {
                                logger.info("METHOD doBusiness :{}", e.getMessage());
                                throw e;
                            }
                        } else {
                            throw e;
                        }
                    }
                }
            }
        }
        return BaseResult.getFailureMessageEntity(service + "未找到" + serviceMethod + "方法");
    }


    @Override
    @DSTransactional()
    public EsbReturnEntity doESbBusiness(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //tailuo 要访问的Bean名称
        String service = request.getHeader("tl");
        //bean方法
        String serviceMethod = request.getHeader("dj");
        String body = ServletUtil.getBody(servletRequest);
        //获取类
        Object object = null;
        try {
            object = ApplicationContextUtil.getBeanByName(service);
        } catch (SecurityException e) {
            throw new BaseSystemException(service + "未找到");
        }
        //获取类下面的方法
        Method[] methods = object.getClass().getMethods();
        logger.info("methodsLength:" + methods.length);
        if (methods == null || methods.length == 0) {
            logger.error("当前methods:" + methods + "methodsLength = " + methods.length);
            throw new BaseSystemException(service + "未找到" + serviceMethod + "方法");
        } else {
            logger.info("当前methods:" + methods + "methodsLength = " + methods.length);
        }
        for (Method m : methods) {
            //logger.info("当前mnAME:" + m.getName() + "   :serviceMethod = " + serviceMethod.trim());
            if (null != m) {
                if (m.getName().equals(serviceMethod.trim())) {
                    JSONObject jsonObject = new JSONObject();
                    if (!ObjectUtils.isEmpty(body)) {
                        jsonObject.put("jsonStr", body);
                    }
                    EsbReturnEntity esbReturnEntity;
                    try {
                        logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        logger.info("请求的参数：jsonObject：" + jsonObject.toJSONString());
                        esbReturnEntity = (EsbReturnEntity) m.invoke(object, jsonObject);
                        logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        return esbReturnEntity;
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("METHOD doESbBusiness invokeException", e);
                        if (e instanceof InvocationTargetException) {
                            Throwable targetException = ((InvocationTargetException) e).getTargetException();
                            if (targetException instanceof BaseSystemException) {
                                throw new BaseSystemException(targetException.getMessage());
                            } else {
                                logger.info("METHOD doESbBusiness invokeException", e);
                                throw e;
                            }
                        } else {
                            throw e;
                        }
                    }
                }
            }
        }
        throw new BaseSystemException(service + "未找到" + serviceMethod + "方法");
    }

    @Override
    public JsonResultEntity fileUpload(MultipartFile file, FileUploadDto entity, ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        StpUtil.checkLogin();
        FileUploadEntity fileUploadEntity = fileUploadService.fileUpload(file,entity);
        return  BaseResult.getSuccessMessageEntity("附件上传成功",fileUploadEntity);
    }

    @Override
    public JsonResultEntity pluginfileUpload(MultipartFile file, FileUploadDto entity,String pluginPackageName, ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        StpUtil.checkLogin();
        FileUploadEntity fileUploadEntity = fileUploadService.pluginfileUpload(file,entity,pluginPackageName);
        return  BaseResult.getSuccessMessageEntity("附件上传成功",fileUploadEntity);
    }

    public JsonResultEntity pluginZipUpate(FileUploadDto fileUploadDto) throws Exception{
        StpUtil.checkLogin();
        FileDownloadEntity fileDownloadEntity = fileDownloadService.pluginZipUpate(fileUploadDto);
        return  BaseResult.getSuccessMessageEntity("插件更新成功",fileDownloadEntity);
    }
    @Override
    public JsonResultEntity fileUpload(MultipartFile file, FileResultEntity entity, ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        entity = fileUploadService.fileUpload(file,entity);
        return  BaseResult.getSuccessMessageEntity("附件上传成功",entity);
    }

    @Override
    public Object platformInterface(ServletRequest servletRequest, ServletResponse servletResponse) throws InvocationTargetException, IllegalAccessException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //tailuo 要访问的Bean名称
        String service = request.getHeader("yatl");
        //bean方法
        String serviceMethod = request.getHeader("yadj");
        String body = ServletUtil.getBody(servletRequest);
        //获取类
        Object object = null;
        if(service == null || "".equals(service) || serviceMethod == null || "".equals(serviceMethod)){
            return BaseResult.getFailureMessageEntity("非法请求，请检查");
        }
        try {
            object = ApplicationContextUtil.getBeanByName(service);
        } catch (SecurityException e) {
            return BaseResult.getFailureMessageEntity(service + "未找到");
        }
        //获取类下面的方法
        Method[] methods = object.getClass().getMethods();
        logger.info("methodsLength:" + methods.length);
        if (methods == null || methods.length == 0) {
            logger.error("当前methods:" + methods + "methodsLength = " + methods.length);
            return BaseResult.getFailureMessageEntity(service + "未找到" + serviceMethod + "方法");
        } else {
            logger.info("当前methods:" + methods + "methodsLength = " + methods.length);
        }
        for (Method m : methods) {
            //logger.info("当前mnAME:" + m.getName() + "   :serviceMethod = " + serviceMethod.trim());
            if (null != m) {
                if (m.getName().equals(serviceMethod.trim())) {
                    logger.info("m.getNameEquals成功");
                    JSONObject jsonObject = new JSONObject();
                    if (!ObjectUtils.isEmpty(body)) {
                        jsonObject.put("jsonStr", body);
                    }
                    try {
                        logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        logger.info("请求的参数：jsonObject：" + jsonObject.toJSONString());
                        Object result =   m.invoke(object, jsonObject);
                        logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        return result;
                    } catch (Exception e) {
                        logger.error("METHOD doBusiness invokeException{}", e.getMessage());
                        if (e instanceof InvocationTargetException) {
                            Throwable targetException = ((InvocationTargetException) e).getTargetException();
                            if (targetException instanceof BaseSystemException) {
                                throw new BaseSystemException(targetException.getMessage());
                            } else {
                                logger.info("METHOD doBusiness :{}", e.getMessage());
                                throw e;
                            }
                        } else {
                            throw e;
                        }
                    }
                }
            }
        }
        throw new BaseSystemException( service + "未找到" + serviceMethod + "方法") ;
    }


    @Override
    @DSTransactional()
    public EsbReturnEntity doTstsBusiness(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        JSONObject re = new JSONObject();
        JSONObject head = new JSONObject();
        // 获取请求消息中的所有头字段
        Enumeration headerNames = request.getHeaderNames();
        //用循环遍历所有请求头，并通过 getHeader() 方法获取一个指定名称的头字段
        List<String> a = Arrays.asList(new String[]{"x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});

        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            if (!a.contains(headerName)) {
                head.put(headerName, request.getHeader(headerName));
            }
        }
        String querys = request.getQueryString();
        String[] strings = querys.split("&");
        JSONObject qu = new JSONObject();
        for (int i = 0; i < strings.length; i++) {
            String[] c = strings[i].split("=");
            qu.put(c[0], c[1]);
        }
        String body = ServletUtil.getBody(servletRequest);
        re.put("header", head);
        re.put("query", qu);
        re.put("body", JSONObject.parseObject(body));
        StpUtil.checkLogin();
        EsbReturnEntity esbReturnEntity = new EsbReturnEntity();
        esbReturnEntity.setTargetData("{}");
        esbReturnEntity.setReturnData(re.toString());
        esbReturnEntity.setStatus(true);
        esbReturnEntity.setRemark("处理成功");
        return esbReturnEntity;
    }
}
