package com.lightinit.hsdataplatform.impl.admin;

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.IResourceAPIRegisterService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.apache.commons.lang.StringUtils;
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.util.Date;
import java.util.List;

@Service
public class ResourceAPIRegisterServiceImpl implements IResourceAPIRegisterService {

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceApiMapper resourceApiMapper ;

    @Autowired
    private ResourceApiInterfaceMapper resourceApiInterfaceMapper ;

    @Autowired
    private ResourceApiInterfaceInputMapper resourceApiInterfaceInputMapper ;

    @Autowired
    private ResourceApiInterfaceOutputMapper resourceApiInterfaceOutputMapper ;

    @Autowired
    private DictionaryGroupMapper dictionaryGroupMapper ;

    @Autowired
    private AdminRoleMapper adminRoleMapper ;



    @Override
    public List<ResourceAPIRegisterListModel> queryList(ResourceAPIRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
            return resourceApiMapper.queryRegisterApiAllList(inputModel);
    }

    @Override
    public long queryCount(ResourceAPIRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceApiMapper.queryRegisterApiCount(inputModel);
    }

    @Override
    @Transactional
    public ResultState<Long> apiInterface_add_finally(ResourceAPIRegisterAddResourceModel 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("数据插入失败");
        }
        resultState.setData(entity1.getId());
        return resultState;
    }

    @Override
    @Transactional
    public ResultState<Long> delete(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        //判断api下有多少个接口
        List<Long> longs =  resourceApiInterfaceMapper.queryIdByAPIid(id) ;
        if (longs.size()>0){
            for (Long aLong : longs) {
               //删除输入参数
                ResourceApiInterfaceInputExample example1 = new ResourceApiInterfaceInputExample();
                ResourceApiInterfaceInputExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andInterfaceIdEqualTo(aLong);
                int sqlResult1 = resourceApiInterfaceInputMapper.deleteByExample(example1);

                //删除输出参数
                ResourceApiInterfaceOutputExample example2 = new ResourceApiInterfaceOutputExample();
                ResourceApiInterfaceOutputExample.Criteria criteria2 = example2.createCriteria();
                criteria2.andInterfaceIdEqualTo(aLong);
                int sqlResult2 = resourceApiInterfaceOutputMapper.deleteByExample(example2);

               //删除接口
                ResourceApiInterfaceExample example3 = new ResourceApiInterfaceExample();
                ResourceApiInterfaceExample.Criteria criteria3 = example3.createCriteria();
                criteria3.andIdEqualTo(aLong);
                int sqlResult3 = resourceApiInterfaceMapper.deleteByExample(example3);
            }
        }
        //删除resource_api
        ResourceApiExample example4 = new ResourceApiExample();
        ResourceApiExample.Criteria criteria4 = example4.createCriteria();
        criteria4.andIdEqualTo(id);
        int sqlResult4 = resourceApiMapper.deleteByExample(example4);

        //删除resource
        ResourceExample example5 = new ResourceExample();
        ResourceExample.Criteria criteria5 = example5.createCriteria();
        criteria5.andIdEqualTo(id);
        int sqlResult5 = resourceMapper.deleteByExample(example5);

        if (!(sqlResult4 > 0 && sqlResult5 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据不存在");
        }
        resultState.setData(id);
        return resultState;
    }

    @Override
    public Resource queryOneResource(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        Resource resource = resourceMapper.selectByPrimaryKey(id);
        return resource ;
    }

    @Override
    public ResourceApi queryOneResourceAPI(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceApi resourceApi = resourceApiMapper.selectByPrimaryKey(id) ;
        return resourceApi;
    }

    @Override
    public int isAdminFalg(Long userId) {
        return adminRoleMapper.isAdminFalg(userId);
    }

    @Override
    public List<ResourceApiInterfaceWithBLOBs> queryOneResourceAPIInterface(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceList = resourceApiInterfaceMapper.selectByAPIid(id) ;
        return resourceApiInterfaceList;
    }

    @Override
    @Transactional
    public ResultState<Long> apiInterface_edit(ResourceAPIRegisterEditResourceModel editResourceModel,Long userId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();

        //修改Resouse表
        Resource entity1 = new Resource();
        BeanUtils.copyProperties(editResourceModel, entity1);
        ResourceExample example1 = new ResourceExample();
        ResourceExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(editResourceModel.getId());
        int sqlResult1 = resourceMapper.updateByExampleSelective(entity1, example1);

        //更行resouse_api表
        ResourceApi entity2 = new ResourceApi();
        BeanUtils.copyProperties(editResourceModel, entity2);
        ResourceApiExample example2 = new ResourceApiExample();
        ResourceApiExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andIdEqualTo(editResourceModel.getId());
        int sqlResult2 = resourceApiMapper.updateByExampleSelective(entity2, example2);

        //更新resource_api_interface表
        //1。判断是否有删除接口
        if (editResourceModel.getResourceApiInterfaceIds()!=null) {
            if (editResourceModel.getResourceApiInterfaceIds().size() > 0) {
                for (Long aLong : editResourceModel.getResourceApiInterfaceIds()) {
                    //删除输入参数表
                    int sqlResult3 = resourceApiInterfaceInputMapper.deleteByApiInterfaceId(aLong);
                    //删除输出参数表
                    int sqlResult4 = resourceApiInterfaceOutputMapper.deleteByApiInterfaceId(aLong);
                    //删除接口
                    ResourceApiInterfaceExample example3 = new ResourceApiInterfaceExample();
                    ResourceApiInterfaceExample.Criteria criteria3 = example3.createCriteria();
                    criteria3.andIdEqualTo(aLong);
                    int sqlResult5 = resourceApiInterfaceMapper.deleteByExample(example3);
                }
            }
        }

        //插入resource_api_interface
        if (editResourceModel.getAddAPIInterfaceModelList()!=null) {
            List<ResourceAPIRegisterAddAPIInterfaceModel> addAPIInterfaceModels = editResourceModel.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(editResourceModel.getId());
                        entity3.setCreatedBy(userId);
                        entity3.setCreatedAt(createdAt);
                        int sqlResult6 = 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 sqlResult7 = 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 sqlResult8 = resourceApiInterfaceOutputMapper.insert(entity5);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (!(sqlResult1 > 0 && sqlResult2 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据更新失败");
        }
        resultState.setData(editResourceModel.getId());
        return resultState;
    }

    @Override
    public ResourceAPIRegisterViewResourceModel queryOneViewResource(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceMapper.queryOneViewResource(id) ;
    }

    @Override
    public ResourceApiInterfaceWithBLOBs queryOneViewResourceAPI(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceApiInterfaceWithBLOBs entity = resourceApiInterfaceMapper.selectByPrimaryKey(id);
        return entity;
    }

    @Override
    public List<ResourceApiInterfaceInput> queryOneViewResourceAPIInterfaceInput(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        List<ResourceApiInterfaceInput> resourceApiInterfaceInputList = resourceApiInterfaceInputMapper.queryOneViewResourceAPIInterfaceInput(id);
        return resourceApiInterfaceInputList;
    }

    @Override
    public List<ResourceApiInterfaceOutput> queryOneViewResourceAPIInterfaceOutput(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        List<ResourceApiInterfaceOutput> resourceApiInterfaceOutputList = resourceApiInterfaceOutputMapper.queryOneViewResourceAPIInterfaceOutput(id);
        return resourceApiInterfaceOutputList;
    }

    @Override
    public ResultState<Long> audit(ResourceAPIRegisterAuditModel resourceAPIRegisterAuditModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        Resource entity1 = new Resource();
        BeanUtils.copyProperties(resourceAPIRegisterAuditModel, entity1);
        ResourceExample example1 = new ResourceExample();
        ResourceExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(resourceAPIRegisterAuditModel.getId());
        int sqlResult1 = resourceMapper.updateByExampleSelective(entity1, example1);
        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("审核数据失败");
            //添加到应用商店
//            if (resourceAPIRegisterAuditModel.getResourceState().equals(DicResourceState.APPROVED)){
//                List<VolumeInfoModel> volumeInfoModels = resourceAPIRegisterAuditModel.getVolumes() ;
//                Map<String,Object> map = new HashMap<>() ;
//                map.put("serviceName",resourceAPIRegisterAuditModel.getServiceName()) ;
//                map.put("namespace",resourceAPIRegisterAuditModel.getNamespace()) ;
//                map.put("publishName",resourceAPIRegisterAuditModel.getPublishName()) ;
//                map.put("turbineCluster",resourceAPIRegisterAuditModel.getTurbineCluster()) ;
//                map.put("replicas",resourceAPIRegisterAuditModel.getReplicas()) ;
//                map.put("image",resourceAPIRegisterAuditModel.getImage()) ;
//                map.put("cpuLimit",resourceAPIRegisterAuditModel.getCpuLimit()) ;
//                map.put("memLimit",resourceAPIRegisterAuditModel.getMemLimit()) ;
//                map.put("containerPort",resourceAPIRegisterAuditModel.getContainerPort()) ;
//                map.put("hostPort",resourceAPIRegisterAuditModel.getHostPort()) ;
//                map.put("servicePort",resourceAPIRegisterAuditModel.getServicePort()) ;
//                map.put("loadBalance",resourceAPIRegisterAuditModel.getLoadBalance()) ;
//                map.put("clusterIp",resourceAPIRegisterAuditModel.getClusterIp()) ;
//                map.put("lesseeId",resourceAPIRegisterAuditModel.getLesseeId()) ;
//                map.put("contextPath",resourceAPIRegisterAuditModel.getContextPath()) ;
//                map.put("serviceAuth",resourceAPIRegisterAuditModel.getServiceAuth()) ;
//                map.put("volumes",resourceAPIRegisterAuditModel.getVolumes()) ;
//                try {
//                    String str = HttpUtil.httpPost(DicPaasApi.PUBLISHSERVICE,null,map) ;
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                    Map<String,Object> map1= HttpUtil.strToMap(str) ;
//                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()) ;
//                    }
//                    System.out.println("-------------------"+str+"------------------------");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
        }
        resultState.setData(resourceAPIRegisterAuditModel.getId());
        return resultState;
    }

    @Override
    public List<APIServiceTypeModel> getApiServiceTypes(String fuwutype) {
        return dictionaryGroupMapper.getApiServiceTypes(fuwutype);
    }


}
