package com.lightinit.hsdataplatform.impl.admin;

import com.lightinit.hsdataplatform.common.HttpUtil;
import com.lightinit.hsdataplatform.dictionary.DicPaasApi;
import com.lightinit.hsdataplatform.dictionary.DicResourceMicroappState;
import com.lightinit.hsdataplatform.dictionary.DicResourceState;
import com.lightinit.hsdataplatform.dictionary.DicResourceType;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.mapper.ResourceMapper;
import com.lightinit.hsdataplatform.mapper.ResourceMicroappMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.ResourceDataMicroappDataModel;
import com.lightinit.hsdataplatform.model.admin.ResourceDataRegisterDataModel;
import com.lightinit.hsdataplatform.model.admin.ResourceMicroappRegisterListModel;
import com.lightinit.hsdataplatform.model.admin.ResourceMicroappRegisterSearchModel;
import com.lightinit.hsdataplatform.service.admin.IResourceMicroappRegisterService;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ResourceMicroappRegisterServiceImpl implements IResourceMicroappRegisterService {
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private ResourceMicroappMapper resourceMicroappMapper;


    public List<ResourceMicroappRegisterListModel> queryList(ResourceMicroappRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceMicroappMapper.selectModelList(inputModel);
    }




    public long queryCount(ResourceMicroappRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceMicroappMapper.selectModelListCount(inputModel);
    }

    @Transactional
    public ResultState<Long> add(ResourceDataMicroappDataModel inputModel,String userName) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();

        Resource entity1 = new Resource();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setResourceType(DicResourceType.MICROAPP);
        entity1.setResourceState(StringUtils.isNotEmpty(inputModel.getResourceState()) && inputModel.getResourceState().equals(DicResourceMicroappState.PENDING) ? DicResourceMicroappState.PENDING : DicResourceMicroappState.DRAFT);
        entity1.setCreatedAt(createdAt);
        int sqlResult1 = resourceMapper.insert(entity1);

        ResourceMicroappWithBLOBs entity2 = new ResourceMicroappWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity2);
        entity2.setId(entity1.getId());
        entity2.setCreatedAt(createdAt);
        int sqlResult2 = resourceMicroappMapper.insert(entity2);

        if (!(sqlResult1 > 0 && sqlResult2 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }else {
            if(inputModel.getResourceState().equals(DicResourceState.PENDING)) {
                try {
//                    HashMap<String, String> headers = new HashMap<>();
//                    headers.put("Content-Type", "application/json");
//                    HashMap<String, String> json = new HashMap<>();
//                    json.put("summary", inputModel.getResourceSummary());
//                    json.put("imageName", inputModel.getImageTags());
//                    json.put("submitUser",userName) ;
//                    json.put("name",inputModel.getResourceName()) ;
//                    json.put("lable",inputModel.getServiceTag()) ;
//                    json.put("kindId",inputModel.getAppkinds().substring(0,inputModel.getAppkinds().indexOf("."))) ;
//                    json.put("developerId",inputModel.getDeveloperId().substring(0,inputModel.getDeveloperId().indexOf("."))) ;
//                    json.put("developers",inputModel.getDevelopers()) ;
//                    json.put("img","") ;
//                    json.put("lesseeId","") ;
//                    json.put("classIfcation",inputModel.getClassIfcation()) ;
//                    json.put("versionList","1") ;
//                    json.put("content",inputModel.getContent()) ;
//                    String message = HttpUtil.httpPost(DicPaasApi.NMSPAPP, headers, json); //同步
////                    String message = HttpUtil.httpPost("http://121.17.30.198:8097/microservice-gateway/msgs-server/v1/nmspApp", headers, json); //同步
//                    System.out.println("执行结果"+message);
//                    Map<String,Object> map1= HttpUtil.strToMap(message);
//                    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");
//                        json.put("releaseDate",sdf.format(createdAt)) ;
//                        String str1 = HttpUtil.httpPost(DicPaasApi.NMSPAPPVERSION,null,map3) ;
//                        System.out.println("-------------------"+str1+"------------------------");
//                    }
                }catch (Exception e){
                    resultState.setMsg("数据插入失败");
                }
            }

        }
        resultState.setData(entity1.getId());
        return resultState;
    }

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

        ResourceMicroappExample example2 = new ResourceMicroappExample();
        ResourceMicroappExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andIdEqualTo(id);
        int sqlResult2 = resourceMicroappMapper.deleteByExample(example2);

        ResourceExample example1 = new ResourceExample();
        ResourceExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(id);
        int sqlResult1 = resourceMapper.deleteByExample(example1);

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

    @Override
    public Object queryOne(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceDataMicroappDataModel outputModel = new ResourceDataMicroappDataModel();
        Resource entity1 = resourceMapper.selectByPrimaryKey(id);
        ResourceMicroappWithBLOBs entity2 = resourceMicroappMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(entity2, outputModel);
        BeanUtils.copyProperties(entity1, outputModel);
        return outputModel;
    }

    @Transactional
    public ResultState edit(ResourceDataMicroappDataModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        Resource entity1 = new Resource();
        BeanUtils.copyProperties(inputModel, entity1);
        ResourceExample example1 = new ResourceExample();
        ResourceExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(inputModel.getId());
        int sqlResult1 = resourceMapper.updateByExampleSelective(entity1, example1);

        ResourceMicroappWithBLOBs entity2 = new ResourceMicroappWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity2);
        ResourceMicroappExample example2 = new ResourceMicroappExample();
        ResourceMicroappExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andIdEqualTo(inputModel.getId());
        int sqlResult2 = resourceMicroappMapper.updateByExampleSelective(entity2, example2);

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

    @Override
    public Object detail(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceDataMicroappDataModel outputModel = new ResourceDataMicroappDataModel();
        Resource entity1 = resourceMapper.selectByPrimaryKey(id);
        ResourceMicroappWithBLOBs entity2 = resourceMicroappMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(entity2, outputModel);
        BeanUtils.copyProperties(entity1, outputModel);
        return outputModel;
    }

    public ResourceMicroappRegisterListModel selectDic(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceMicroappRegisterListModel outputModel = new ResourceMicroappRegisterListModel();
         outputModel = resourceMicroappMapper.selectDic(id);
        return outputModel;
    }

    @Transactional
    public ResultState<Long> submit(ResourceDataMicroappDataModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();

        Resource entity1 = new Resource();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setResourceType(DicResourceType.MICROAPP);
        entity1.setResourceState(StringUtils.isNotEmpty(inputModel.getResourceState()) && inputModel.getResourceState().equals(DicResourceMicroappState.DRAFT) ? DicResourceMicroappState.DRAFT : DicResourceMicroappState.PENDING);
        entity1.setCreatedAt(createdAt);
        int sqlResult1 = resourceMapper.insert(entity1);

        ResourceMicroappWithBLOBs entity2 = new ResourceMicroappWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity2);
        entity2.setId(entity1.getId());
        entity2.setCreatedAt(createdAt);
        int sqlResult2 = resourceMicroappMapper.insert(entity2);

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

    //==========================================================================
    @Transactional
    public ResultState<Long> shoreAdd(ResourceDataMicroappDataModel inputModel,String userName) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();

        Resource entity1 = new Resource();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setResourceType(DicResourceType.MICROAPP);
        entity1.setResourceState(StringUtils.isNotEmpty(inputModel.getResourceState()) && inputModel.getResourceState().equals(DicResourceMicroappState.PENDING) ? DicResourceMicroappState.PENDING : DicResourceMicroappState.DRAFT);
        entity1.setCreatedAt(createdAt);
        int sqlResult1 = resourceMapper.insert(entity1);

        ResourceMicroappWithBLOBs entity2 = new ResourceMicroappWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity2);
        entity2.setId(entity1.getId());
        entity2.setCreatedAt(createdAt);
        int sqlResult2 = resourceMicroappMapper.insert(entity2);

        if (!(sqlResult1 > 0 && sqlResult2 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }else {
            if(inputModel.getResourceState().equals(DicResourceState.PENDING)) {
                try {
                    HashMap<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");
                    HashMap<String, String> json = new HashMap<>();
                    json.put("summary", inputModel.getResourceSummary());
                    json.put("imageName", inputModel.getImageTags());
                    json.put("submitUser",userName) ;
                    json.put("name",inputModel.getResourceName()) ;
                    json.put("lable",inputModel.getServiceTag()) ;
                    json.put("kindId",inputModel.getAppkinds().substring(0,inputModel.getAppkinds().indexOf("."))) ;
                    json.put("developerId",inputModel.getDeveloperId().substring(0,inputModel.getDeveloperId().indexOf("."))) ;
                    json.put("developers",inputModel.getDevelopers()) ;
                    json.put("img","") ;
                    json.put("lesseeId","") ;
                    json.put("classIfcation",inputModel.getClassIfcation()) ;
                    json.put("versionList","1") ;
                    json.put("content",inputModel.getContent()) ;
                    String message = HttpUtil.httpPost(DicPaasApi.NMSPAPP, headers, json); //同步
//                    String message = HttpUtil.httpPost("http://121.17.30.198:8097/microservice-gateway/msgs-server/v1/nmspApp", headers, json); //同步
                    System.out.println("执行结果"+message);
                    Map<String,Object> map1= HttpUtil.strToMap(message);
                    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");
                        json.put("releaseDate",sdf.format(createdAt)) ;
                        String str1 = HttpUtil.httpPost(DicPaasApi.NMSPAPPVERSION,null,map3) ;
                        System.out.println("-------------------"+str1+"------------------------");
                    }
                }catch (Exception e){
                    resultState.setMsg("数据插入失败");
                }
            }

        }
        resultState.setData(entity1.getId());
        return resultState;
    }

    @Override
    public ResultState AddService(ResourceDataMicroappDataModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        Resource entity1 = new Resource();
        BeanUtils.copyProperties(inputModel, entity1);
        ResourceExample example1 = new ResourceExample();
        ResourceExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(inputModel.getId());
        int sqlResult1 = resourceMapper.updateByExampleSelective(entity1, example1);

        ResourceMicroappWithBLOBs entity2 = new ResourceMicroappWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity2);
        ResourceMicroappExample example2 = new ResourceMicroappExample();
        ResourceMicroappExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andIdEqualTo(inputModel.getId());
        int sqlResult2 = resourceMicroappMapper.updateByExampleSelective(entity2, example2);

        if (!(sqlResult1 > 0 && sqlResult2 > 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 + inputModel.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("replicas", inputModel.getReplicas());
                map3.put("image", stringBuilder);
                map3.put("cpuLimit", inputModel.getCpuLimit());
                map3.put("memLimit", inputModel.getMemLimit());
                map3.put("containerPort", inputModel.getContainerPort());
                map3.put("hostPort", inputModel.getHostPort());
                map3.put("servicePort", inputModel.getServicePort());
                map3.put("loadBalance", inputModel.isLoadBalance());
                map3.put("clusterIp", inputModel.getClusterIp());
                map3.put("lesseeId", inputModel.getLesseeId().intValue());
                map3.put("contextPath", inputModel.getContextPath());
                map3.put("serviceAuth", inputModel.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")){
//                    //TODO 插入（暂时未完成）
//                    Resource entity2 = new Resource();
//                    entity2.setOutId2(map4.);
//                    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("插入微服务失败");
                e.printStackTrace();
            }
        }
        resultState.setData(inputModel.getId());
        return resultState;
    }
}
