package com.yeejoin.amos.fas.business.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.fas.business.service.intfc.ITopographyLineService;
import com.yeejoin.amos.fas.business.service.intfc.ITopographyNodeService;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import com.yeejoin.amos.fas.dao.entity.TopographyLine;
import com.yeejoin.amos.fas.dao.entity.TopographyNode;
import com.yeejoin.amos.fas.dao.entity.TopographyNodeDetail;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "/api/Topography")
@Api(tags="Topography API")
public class TopographyController {
	
	@Autowired
	private ITopographyNodeService nodeService;
	
	@Autowired
	private ITopographyLineService lineService;
	
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "根据appId查询节点及线", notes = "根据appID查询节点及线")
    @GetMapping(value = "/query/{type}/{appId}")
    public CommonResponse getTextPlanByIdAndType(@PathVariable(value = "appId") String appId,@PathVariable(value = "type") String type) {
		List<TopographyNode> nodes = nodeService.getNodesByAppIdAndType(appId,type);
    	List<TopographyLine> links = lineService.getLinesByAppIdAndType(appId,type);
    	Map<String,Object> results = new HashMap<>();
    	results.put("nodeData", nodes);
    	results.put("linkData", links);
    	return CommonResponseUtil.success(results);
    }
	
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "根据type查询节点及线", notes = "根据type查询节点及线")
    @GetMapping(value = "/query/{type}")
    public CommonResponse getTextPlanByType(@PathVariable(value = "type") String type) {
		List<TopographyNode> nodes = nodeService.getNodesByType(type);
    	List<TopographyLine> links = lineService.getLinesByType(type);
    	Map<String,Object> results = new HashMap<>();
    	results.put("nodeData", nodes);
    	results.put("linkData", links);
    	return CommonResponseUtil.success(results);
    }
	
	/**
     * 保存拓扑图
     *
     * @return 
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/updateTopo", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "保存拓扑图", notes = "保存拓扑图")
    public CommonResponse savedonghuanNodes(@ApiParam(value = "", required = false) @RequestBody JSONObject topographyParam) {
    	synchronized (TopographyController.class) {
    		
	    	String appId = topographyParam.getString("appId") != null ? topographyParam.getString("appId") : null;
	    	String type = topographyParam.getString("type");
	    	//节点
	    	JSONArray nodes = topographyParam.getJSONArray("nodeData");
	    	List<TopographyNode> nodeData = JSON.parseArray(JSON.toJSONString(nodes), TopographyNode.class);
	    	HashMap<String, String> convertKeyMap = new HashMap<>();
	    	int curSize = nodeService.queryMaxKeyByAppIdAndType(appId,type);
	    	for(TopographyNode e:nodeData){
	    		if(Integer.valueOf(e.getKey()) < 0) {
	    			curSize = curSize + 1 ;
	    			String newKey = String.format("%05d", curSize);
	    			convertKeyMap.put(e.getKey(), newKey);
	    			e.setKey(newKey);
	    			e.setType(type);
	    			e.setAppId(appId);
	    			if(e.getGroup() == null) {
	    				e.setGroup("");
	    			}else if(Integer.valueOf(e.getGroup()) < 0){//修改新节点组
	    				e.setGroup(convertKeyMap.get(e.getGroup()));
	    			}
	    		}
	    	};
	    	//线
	    	JSONArray links = topographyParam.getJSONArray("linkData");
	    	List<TopographyLine> lineData = JSON.parseArray(JSON.toJSONString(links), TopographyLine.class);
	    	lineData.forEach(l -> {//修改新增节点之间线的连接
	    		if(Integer.parseInt(l.getFrom()) < 0) {
	    			l.setFrom(convertKeyMap.get(l.getFrom()));
	    		}
	    		if(Integer.parseInt(l.getTo()) < 0) {
	    			l.setTo(convertKeyMap.get(l.getTo()));
	    		}
	    		if(l.getCategory() == null) {
					l.setCategory("");
				}
	    		if(l.getAppId() == null) {
	    			l.setAppId(appId);
	    			l.setType(type);
	    		}
	    	});
	    	
	    	nodeService.saveNodes(nodeData);
	    	lineService.saveLines(lineData);
	    	
	    	//节点详情
	    	
    		JSONObject nodeDetailJson = topographyParam.getJSONObject("nodeDetail");
        	if(nodeDetailJson != null) {
        		TopographyNodeDetail nodeDetail = JSON.parseObject(JSON.toJSONString(nodeDetailJson), TopographyNodeDetail.class);
        		String nodekey = nodeDetail.getNodekey();
        		if(nodekey != null && Integer.parseInt(nodekey) < 0) {
        			TopographyNode node = nodeService.queryByKeyAndAppIdAndType(convertKeyMap.get(nodekey),appId,type);
        			nodeDetail.setNodeid(node.getId());
        		}
        		nodeService.saveNodeDetail(nodeDetail);
        	}
	    	//返回保存后的数据
	    	List<TopographyNode> newNodes = nodeService.getNodesByAppIdAndType(appId,type);
	    	List<TopographyLine> newLinks = lineService.getLinesByAppIdAndType(appId,type);
	    	
	    	Map<String,Object> results = new HashMap<>();
	    	results.put("nodeData", newNodes);
	    	results.put("linkData", newLinks);
	    	return CommonResponseUtil.success(results);
    	}
    }

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "根据nodeid查询节点详情", notes = "根据nodeid查询节点详情")
    @GetMapping(value = "/detail/{nodeid}")
    public CommonResponse getNodeDatilByNodeId(@PathVariable(value = "nodeid") String nodeid) {
    	TopographyNodeDetail detail = nodeService.getNodeDetailById(nodeid);
    	if(detail != null) {
//    		String items = detail.getNodeDetail();
    		return CommonResponseUtil.success(detail);
    	}
    	return CommonResponseUtil.success();
    }
    
	@TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "保存节点详情", notes = "保存节点详情")
    @PostMapping(value = "/detail")
    public CommonResponse saveNodeDatil(@RequestBody TopographyNodeDetail nodeDetail) {
    	if(nodeDetail.getNodeid() !=null) {
    		TopographyNodeDetail saveNodeDetail = nodeService.saveNodeDetail(nodeDetail);
    		return CommonResponseUtil.success(saveNodeDetail);
    	}else {
    		return CommonResponseUtil.failure("请选择节点！");
    	}
    }
    
	@TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "删除节点/线", notes = "删除节点/线")
    @DeleteMapping(value = "/{type}/{id}")
    public CommonResponse deleteTopo(@PathVariable("type") String type,@PathVariable("id") String id) {
    	if("Link".equals(type)) {
    		lineService.deleteLine(id);
    	}else {
    		TopographyNode node = nodeService.queryById(id);
    		nodeService.deleteNode(node);
    	}
		return CommonResponseUtil.success();
    }
    
}
