package com.lightinit.hsdataplatform.impl.admin;

import com.google.gson.internal.LinkedTreeMap;
import com.lightinit.hsdataplatform.common.HttpUtil;
import com.lightinit.hsdataplatform.common.TokenUntils;
import com.lightinit.hsdataplatform.dictionary.DicNewGateway;
import com.lightinit.hsdataplatform.dictionary.DicPaasApi;
import com.lightinit.hsdataplatform.dictionary.DicResourceState;
import com.lightinit.hsdataplatform.dictionary.DicResourceType;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.mapper.*;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IPaasService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import com.lightinit.hsdataplatform.tasks.logger.FluxJob;
import com.lightinit.hsdataplatform.tasks.logger.StateJob;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.LogManager;
import org.slf4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PaasServiceImpl implements IPaasService {

    org.apache.log4j.Logger log = LogManager.getLogger(FluxJob.class);

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceApiMapper resourceApiMapper;

    @Autowired
    private ResourceApiInterfaceMapper resourceApiInterfaceMapper;

    @Autowired
    private ResourceApiInterfaceInputMapper resourceApiInterfaceInputMapper;

    @Autowired
    private ResourceApiInterfaceOutputMapper resourceApiInterfaceOutputMapper;

    @Autowired
    private PublishInfoMapper publishInfoMapper;

    @Override
    @Transactional
    public ResultState<Long> apiInterface_add_finally(PaasShoreModel addResourceModel, Long userId, String userName) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();
        //插入Resouse表
        Resource entity1 = new Resource();
        BeanUtils.copyProperties(addResourceModel, entity1);
        entity1.setResourceType(DicResourceType.API);
        entity1.setCreatedAt(createdAt);
        entity1.setCreatedBy(userId);
        int sqlResult1 = resourceMapper.insert(entity1);

        //插入resouse_api表
        ResourceApi entity2 = new ResourceApi();
        BeanUtils.copyProperties(addResourceModel, entity2);
        entity2.setId(entity1.getId());
        entity2.setCreatedAt(createdAt);
        entity2.setCreatedBy(userId);
        int sqlResult2 = resourceApiMapper.insert(entity2);

        if (addResourceModel.getAddAPIInterfaceModelList() != null) {
            List<ResourceAPIRegisterAddAPIInterfaceModel> addAPIInterfaceModels = addResourceModel.getAddAPIInterfaceModelList();
            //判断接口是否为空
            if (!addAPIInterfaceModels.isEmpty() && addAPIInterfaceModels.size() > 0) {
                for (ResourceAPIRegisterAddAPIInterfaceModel addAPIInterfaceModel : addAPIInterfaceModels) {
                    if (StringUtils.isNotEmpty(addAPIInterfaceModel.getInterfaceName())) {
                        //插入resouse_interface表
                        ResourceApiInterfaceWithBLOBs entity3 = new ResourceApiInterfaceWithBLOBs();
                        BeanUtils.copyProperties(addAPIInterfaceModel, entity3);
                        entity3.setApiId(entity1.getId());
                        entity3.setCreatedAt(createdAt);
                        entity3.setCreatedBy(userId);
                        int sqlResult3 = resourceApiInterfaceMapper.insert(entity3);
                        //取得输入接口输入参数
                        if (addAPIInterfaceModel.getInterfaceInputModelList() != null) {
                            List<ResourceAPIRegisterAddAPIInterfaceInputModel> addAPIInterfaceInputModelList = addAPIInterfaceModel.getInterfaceInputModelList();
                            if (!addAPIInterfaceInputModelList.isEmpty()) {
                                for (ResourceAPIRegisterAddAPIInterfaceInputModel resourceAPIRegisterAddAPIInterfaceInputModel : addAPIInterfaceInputModelList) {
                                    if (StringUtils.isNotEmpty(resourceAPIRegisterAddAPIInterfaceInputModel.getIsRequired()) &&
                                            !(resourceAPIRegisterAddAPIInterfaceInputModel.getIsRequired().equals("undefined"))) {
                                        //插入resouse_api_interface_input
                                        ResourceApiInterfaceInput entity4 = new ResourceApiInterfaceInput();
                                        entity4.setParamName(resourceAPIRegisterAddAPIInterfaceInputModel.getParamName());
                                        entity4.setIsRequired(new Byte(resourceAPIRegisterAddAPIInterfaceInputModel.getIsRequired()));
                                        entity4.setDataType(resourceAPIRegisterAddAPIInterfaceInputModel.getDataType());
                                        entity4.setDescription(resourceAPIRegisterAddAPIInterfaceInputModel.getDescription());
                                        entity4.setInterfaceId(entity3.getId());
                                        entity4.setCreatedAt(createdAt);
                                        entity4.setCreatedBy(userId);
                                        int sqlResult4 = resourceApiInterfaceInputMapper.insert(entity4);
                                    }
                                }
                            }
                        }
                        //取得输出接口输出参数
                        if (addAPIInterfaceModel.getInterfaceOutputModelList() != null) {
                            List<ResourceAPIRegisterAddAPIInterfaceOutputModel> addAPIInterfaceOutputModels = addAPIInterfaceModel.getInterfaceOutputModelList();
                            if (!addAPIInterfaceOutputModels.isEmpty()) {
                                for (ResourceAPIRegisterAddAPIInterfaceOutputModel resourceAPIRegisterAddAPIInterfaceOutputModel : addAPIInterfaceOutputModels) {
                                    if (StringUtils.isNotEmpty(resourceAPIRegisterAddAPIInterfaceOutputModel.getParamName()) &&
                                            !(resourceAPIRegisterAddAPIInterfaceOutputModel.getParamName().equals("undefined"))) {
                                        //插入resouse_api_interface_output
                                        ResourceApiInterfaceOutput entity5 = new ResourceApiInterfaceOutput();
                                        BeanUtils.copyProperties(resourceAPIRegisterAddAPIInterfaceOutputModel, entity5);
                                        entity5.setInterfaceId(entity3.getId());
                                        entity5.setCreatedAt(createdAt);
                                        entity5.setCreatedBy(userId);
                                        int sqlResult5 = resourceApiInterfaceOutputMapper.insert(entity5);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!(sqlResult1 > 0 && sqlResult2 > 0)) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }
        //添加到应用商店
        if (addResourceModel.getResourceState().equals(DicResourceState.PENDING)) {
            Map<String, String> map = new HashMap<>();
            map.put("name", addResourceModel.getResourceName());
            map.put("lable", addResourceModel.getServiceTag());
            map.put("kindId", addResourceModel.getAppkinds().substring(0, addResourceModel.getAppkinds().indexOf(".")));
            map.put("developerId", addResourceModel.getDeveloperId().substring(0, addResourceModel.getDeveloperId().indexOf(".")));
            map.put("developers", addResourceModel.getDevelopers());
            map.put("img", "");
            map.put("lesseeId", "40");
            map.put("imageName", addResourceModel.getImagetags());
            map.put("classIfcation", addResourceModel.getClassIfcation());
            map.put("summary", addResourceModel.getResourceSummary());
            map.put("submitUser", userName);
            map.put("versionList", "1");
            map.put("content", addResourceModel.getContent());
            try {
                String str = HttpUtil.httpPost(DicPaasApi.NMSPAPP, null, map);
                Map<String, Object> map1 = HttpUtil.strToMap(str);
                if ((boolean) map1.get("success")) {
                    Map<String, Object> map2 = (Map<String, Object>) map1.get("data");
                    Double outId = (Double) map2.get("id");
                    resourceMapper.insertOutId(outId.intValue(), entity1.getId());
                    //保存应用版本
                    Map<String, String> map3 = new HashMap<>();
                    map3.put("appId", String.valueOf(outId.intValue()));
                    map3.put("image", "");
                    map3.put("version", "0.0.1");
                    map3.put("submitUser", userName);
                    map3.put("updateContent", "更新内容");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    map.put("releaseDate", sdf.format(createdAt));
                    String str1 = HttpUtil.httpPost(DicPaasApi.NMSPAPPVERSION, null, map3);
                    System.out.println("-------------------" + str1 + "------------------------");
                }
                System.out.println("-------------------" + str + "------------------------");
            } catch (Exception e) {
                log.error(new Date()+"增加到应用商店异常！");
            }
        }
        resultState.setData(entity1.getId());
        return resultState;
    }

    @Override
    @Transactional
    public ResultState<Long> auditAddService(AuditAddServiceModel auditAddServiceModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        Resource entity1 = new Resource();
        BeanUtils.copyProperties(auditAddServiceModel, entity1);
        ResourceExample example1 = new ResourceExample();
        ResourceExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(auditAddServiceModel.getId());
        int sqlResult1 = resourceMapper.updateByExampleSelective(entity1, example1);
        if (!(sqlResult1 > 0)) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("审核数据失败");
        }
        if (auditAddServiceModel.getResourceState().equals(DicResourceState.APPROVED)) {
            try {
//                List<VolumeInfoModel> volumeInfoModels = auditAddServiceModel.getVolumes();
                StringBuilder stringBuilder = new StringBuilder();
                String str = HttpUtil.httpGet(DicPaasApi.GETAPPVERSION + auditAddServiceModel.getOutId1(), null, null);
                Map<String, Object> map1 = HttpUtil.strToMap(str);
                List list = (List) map1.get("data");
                Map map = (Map) list.get(0);
                Map map2 = (Map) map.get("nmspApp");
                stringBuilder.append(map2.get("imageName")).append(":").append(map.get("version"));
                Map<String, Object> map3 = new HashMap<>();
                map3.put("serviceName", auditAddServiceModel.getServiceName());
                map3.put("namespace", auditAddServiceModel.getNamespace());
                map3.put("publishName", auditAddServiceModel.getPublishName());
                map3.put("turbineCluster", auditAddServiceModel.getTurbineCluster());
                map3.put("replicas", auditAddServiceModel.getReplicas());
                map3.put("image", stringBuilder);
                map3.put("cpuLimit", auditAddServiceModel.getCpuLimit());
                map3.put("memLimit", auditAddServiceModel.getMemLimit());
                map3.put("containerPort", auditAddServiceModel.getContainerPort());
                map3.put("hostPort", auditAddServiceModel.getHostPort());
                map3.put("servicePort", auditAddServiceModel.getServicePort());
                map3.put("loadBalance", auditAddServiceModel.isLoadBalance());
                map3.put("clusterIp", auditAddServiceModel.getClusterIp());
                map3.put("lesseeId", auditAddServiceModel.getLesseeId().intValue());
                map3.put("contextPath", auditAddServiceModel.getContextPath());
                map3.put("serviceAuth", auditAddServiceModel.getServiceAuth());
                map3.put("volumes", auditAddServiceModel.getVolumes());
                String str2 = HttpUtil.httpPost(DicPaasApi.PUBLISHSERVICE, null, map3);
                Map<String, Object> map4 = HttpUtil.strToMap(str2);
                if ((boolean) map4.get("success")) {
                    Resource entity2 = new Resource();
                    entity2.setOutId2((String) map4.get("id"));
                    ResourceExample example2 = new ResourceExample();
                    ResourceExample.Criteria criteria2 = example2.createCriteria();
                    criteria2.andIdEqualTo(auditAddServiceModel.getId());
                    int sqlResult2 = resourceMapper.updateByExampleSelective(entity2, example2);
                }
            } catch (Exception e) {
                resultState.setStateCode(ResultStateCode.INVALID_DATA);
                resultState.setMsg("插入微服务失败");
                log.error(new Date()+"插入微服务异常！");
            }
        }
        return resultState;
    }

    @Override
    @Transactional
    //===========================添加路由规则=========================
    public ResultState<Long> toExamine(RouteAddInputModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        //审核publish_info表
        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setAuditedAt(new Date());
        PublishInfoExample example1 = new PublishInfoExample();
        PublishInfoExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(inputModel.getId());
        int sqlResult1 = publishInfoMapper.updateByExampleSelective(entity1, example1);
        if (!(sqlResult1 > 0)) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据失败");
        }
        //插入权限
        Map<String, Object> sysAuthority = new HashMap<>();
        sysAuthority.put("name", inputModel.getGatewayRouteId());
        sysAuthority.put("value", inputModel.getAppName());
        //---------------------------------------------
        String lesseeId = inputModel.getLesseeId();
        Map<String, Object> map = new HashMap<>();
        map.put("id", inputModel.getGatewayRouteId());
        map.put("path", inputModel.getPath());
        map.put("serviceId", inputModel.getServiceId());
        map.put("appName", inputModel.getAppName());
        map.put("refreshInterval", inputModel.getRefreshInterval());
        map.put("policyLimit", inputModel.getPolicyLimit());
        map.put("policyQuota", inputModel.getPolicyQuota());
        map.put("lesseeId", Integer.parseInt(lesseeId.substring(0, lesseeId.indexOf("."))));
        map.put("stripPrefix", inputModel.isStripPrefix());
        map.put("retryable", inputModel.isRetryable());
        map.put("enabled", inputModel.isEnabled());
        map.put("url", inputModel.getServiceUrl());
        Map<String, String> heads = new HashMap<>();
        heads.put("Authorization", TokenUntils.getToken());
        heads.put("Content-Type", "application/json");
        try {
            String str1 = HttpUtil.httpPost(DicPaasApi.ADDAUTHORITIES, TokenUntils.getHead(), sysAuthority);
            Map<String, Object> map3 = HttpUtil.strToMap(str1);
            if ((boolean) map3.get("success")) {
                LinkedTreeMap linkedTreeMap3 = (LinkedTreeMap) map3.get("data");
                String name = (String) linkedTreeMap3.get("name");
                map.put("authWrite", name);
                map.put("authRead", name);
                String str = HttpUtil.httpPost(DicPaasApi.ROUTE_ADD, heads, map);
                Map<String, Object> map1 = HttpUtil.strToMap(str);
                if ((boolean) map1.get("success")) {
                    Map<String, Object> map2 = (Map<String, Object>) map1.get("data");
                    String outId = (String) map2.get("id");
                    String authId = (String) map3.get("id");
                    publishInfoMapper.insertOutIdTwo(outId, inputModel.getId(), authId);
                }
                System.out.println("-------------------" + str + "------------------------");
            }
        } catch (Exception e) {
            log.error(new Date()+"添加路由异常！");
        }
        //增加新路由
        Map<String, String> params = new HashMap<>();
        params.put("routeName", inputModel.getGatewayRouteId());
        params.put("routeStatus", DicNewGateway.QIYONG);
        params.put("contextPath", inputModel.getPath());
        params.put("mappingUrl", DicNewGateway.NEWGATEWAYPATH + inputModel.getPath());
        params.put("remark", inputModel.getAppName());
        try {
            String str = HttpUtil.httpPost(DicNewGateway.GATEWAYADD, null, params);
            Map<String, Object> map1 = HttpUtil.strToMap(str);
            if (map1.get("status").equals("success")) {
                PublishInfoWithBLOBs entity2 = new PublishInfoWithBLOBs();
                entity2.setOutId1(map1.get("result").toString());
                PublishInfoExample example2 = new PublishInfoExample();
                PublishInfoExample.Criteria criteria2 = example2.createCriteria();
                criteria2.andIdEqualTo(inputModel.getId());
                publishInfoMapper.updateByExampleSelective(entity2, example2);
            }
            System.out.println("=================" + map1 + "==========================");
        } catch (Exception e) {
//            log.error(new Date()+"增加新路由异常！");
        }
        resultState.setData(inputModel.getId());
        return resultState;
//        return null ;
    }

    @Override
    @Transactional
    public ResultState<Long> addRouteServicePost(AddRouteServiceModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        Resource entity1 = new Resource();
        entity1.setResourceState(inputModel.getResourceState());
        ResourceExample example1 = new ResourceExample();
        ResourceExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(inputModel.getId());
        int sqlResult1 = resourceMapper.updateByExampleSelective(entity1, example1);
        if (!(sqlResult1 > 0)) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("审核数据失败");
            //添加到应用商店
        }
        if (inputModel.getResourceState().equals(DicResourceState.APPROVED)) {
            try {
//                List<VolumeInfoModel> volumeInfoModels = auditAddServiceModel.getVolumes();
//                StringBuilder stringBuilder = new StringBuilder();
//                String str = HttpUtil.httpGet(DicPaasApi.GETAPPVERSION + auditAddServiceModel.getOutId1(), null, null);
//                Map<String, Object> map1 = HttpUtil.strToMap(str);
//                List list = (List) map1.get("data");
//                Map map = (Map) list.get(0);
//                Map map2 = (Map) map.get("nmspApp");
//                stringBuilder.append(map2.get("imageName")).append(":").append(map.get("version"));
                Map<String, Object> map3 = new HashMap<>();
                map3.put("serviceName", inputModel.getServiceName());
                map3.put("namespace", inputModel.getNamespace());
                map3.put("publishName", inputModel.getPublishName());
                map3.put("turbineCluster", inputModel.getTurbineCluster());
                map3.put("contextPath", inputModel.getContextPath());
                map3.put("serviceAuth", inputModel.getServiceAuth());
                map3.put("lesseeId", inputModel.getLesseeId().intValue());
                String str2 = HttpUtil.httpPost(DicPaasApi.OUTROUTESERVICE + "?namespace=" + inputModel.getNamespace() + "&name=" + inputModel.getName(), null, map3);
                Map<String, Object> map4 = HttpUtil.strToMap(str2);
                if ((boolean) map4.get("success")) {
                    Resource entity2 = new Resource();
                    Map<String, Object> map5 = (Map<String, Object>) map4.get("data");
                    Double id = (Double) map5.get("id");
                    entity2.setOutId2(String.valueOf(id.intValue()));
                    ResourceExample example2 = new ResourceExample();
                    ResourceExample.Criteria criteria2 = example2.createCriteria();
                    criteria2.andIdEqualTo(inputModel.getId());
                    int sqlResult2 = resourceMapper.updateByExampleSelective(entity2, example2);
                }
            } catch (Exception e) {
                resultState.setStateCode(ResultStateCode.INVALID_DATA);
                resultState.setMsg("插入三方服务失败");
                log.error(new Date()+"添加到应用商店异常！");
            }
        }
        return resultState;
    }

    @Override
    @Transactional
    public ResultState<Long> outRouteView(OutRouteAddInputModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        //审核publish_info表
        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        entity1.setPublishState(inputModel.getPublishState());
        entity1.setAuditedAt(new Date());
        PublishInfoExample example1 = new PublishInfoExample();
        PublishInfoExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(inputModel.getId());
        int sqlResult1 = publishInfoMapper.updateByExampleSelective(entity1, example1);
        if (!(sqlResult1 > 0)) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据失败");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("serviceId", inputModel.getOutId2());
        map.put("instanceIp", inputModel.getInstanceIp());
        map.put("instancePort", inputModel.getInstancePort());
        map.put("enableHealthCheck", inputModel.isEnableHealthCheck());
        map.put("instanceStatus", inputModel.getInstanceStatus());
//        map.put("healthCheckUrl",) ;
        Map<String, String> heads = new HashMap<>();
        heads.put("Authorization", TokenUntils.getToken());
        heads.put("Content-Type", "application/json");
        try {
            String str = HttpUtil.httpPost(DicPaasApi.OUTROUTEVIEW + inputModel.getOutId2() + "/instances", heads, map);
            Map<String, Object> map1 = HttpUtil.strToMap(str);
            if ((boolean) map1.get("success")) {
                Map<String, Object> map2 = (Map<String, Object>) map1.get("data");
                Double outId = (Double) map2.get("id");
                publishInfoMapper.insertOutId(String.valueOf(outId), inputModel.getId());
            }
            System.out.println("-------------------" + str + "------------------------");
        } catch (Exception e) {
            log.error(new Date()+"审核publish_info表异常！");
        }
        resultState.setData(inputModel.getId());
        return resultState;
    }
}
