const mongoose = require('mongoose');

function getListAttr(projects, attr) {
	var list = [];
	for (var i = 0; i < projects.length; i++) {
			list.push(projects[i][attr])
	}
	return list.join(" ");
}

function getProjectAttr(projects,pName, pAttr) {

	if (typeof projects[pName] == "undefined") {
		return ""
	} else {
			var attrs = pAttr.split("/");
			if (attrs.length == 0) {
				return ""
			}
			var list = [];
			for (var j = 0; j < attrs.length; j++) {
				if(projects[pName][attrs[j]]){
					list.push(projects[pName][attrs[j]].split(" ").join("^"));
				}else{
					list.push(" ");
				}
			}
			return list.join("|")
	}
}
	
function getProjectsAttrs(projects, attr, attr2) {
	var attrs = attr.split("/");
	if (attrs.length == 0) {
		return
	}
	var list = [];
	//attr2 专有参数，用来表示是否要取带有对外域名的服务
	if(attr2 == "true"){
		for (var i = 0; i < projects.length; i++) {
			if(projects[i].url != ""){
				var li = [projects[i]["name"]];
				for (var j = 0; j < attrs.length; j++) {
					li.push(projects[i][attrs[j]]);
				}
				list.push(li.join("|"));
			}
		}
	}else{
		for (var i = 0; i < projects.length; i++) {
				var li = [projects[i]["name"]];
				for (var j = 0; j < attrs.length; j++) {
					li.push(projects[i][attrs[j]]);
				}
				list.push(li.join("|"));
		}
	}
	return list.join(" ");
}

function  db2db(pro){
	let temp = {
		project_group: "",
		name: pro["project_name"],
		type: pro["type"],
		url: pro["host_name"].replace(".xyqb.com", "").replace(".quantgroup.cn", ""),
		www: pro["host_name"],
		git_path: pro["git_path"],
		log_name: pro["log_path"],
		config_file: pro["config_path"],
		command: "",
		command_: "",
		command2: "",
		node_version: "",
		port: `${pro["port"]}`,
		desc: pro["des"],
		is_active: pro["is_active"],
		auth: pro["auth"],
		target_path: ""
	}
	if(pro["type"] == "java"){
		temp.node_version = pro["command1"];
		temp.target_path = pro["jar_path"];
		temp.command2 = pro["build_command"];
		temp.command = pro["start_command"];
	}else if(pro["type"] == "ui"){
		temp.command =	pro["build_command"]
	}else if(pro["type"] == "node"){
		temp.command =	pro["start_command"]
		temp.command2 =	pro["stop_command"]
	}else if(pro["type"] == "python"){

	}
	return temp
}

function controller(param){
	//链接数据库
	mongoose.connect('mongodb://172.30.220.22:27017/qaHome')
	mongoose.model("ProConfig",new mongoose.Schema({})).find({}).exec().then(res=>{
		// 定义数据
		let _res = JSON.parse(JSON.stringify(res));
		var project_name, project_attr, projects = {},
			java_projects = [],
			node_projects = [],
			python_projects = [],
			ui_projects = []
			hosts = {};

		projects = {}
		for (let pro of _res) {
			let temp = db2db(pro);
				projects[temp.name] = temp;
				hosts[temp.name] = temp.www;
		    switch (pro['type']) {
		        case "java":
		            java_projects.push(temp);
		            break;
		        case "node":
		            node_projects.push(temp);
		            break;
		        case "ui":
		            ui_projects.push(temp);
		            break;
		        case "python":
		            python_projects.push(temp);
		            break;
		    }
		}

		//定义方法
		if (param["type"] == "") {
			let str = getProjectAttr(projects,param["name"], param["attr"]);
			console.log(str);
		} else if (param["type"] == "multi") {
			var str = "";
			str += getProjectsAttrs(java_projects, param["attr"], param["attr2"]);
			str += " " + getProjectsAttrs(ui_projects, param["attr"], param["attr2"]);
			str += " " + getProjectsAttrs(python_projects, param["attr"], param["attr2"]);
			str += " " + getProjectsAttrs(node_projects, param["attr"], param["attr2"]);
			console.log(str)
		} else if (param["type"] == "hosts") {
			console.log(JSON.stringify(hosts));
		} else {
			switch (param["type"]) {
				case "java":
					console.log(getListAttr(java_projects, param["attr"]));
					break;
				case "ui":
					console.log(getListAttr(ui_projects, param["attr"]));
					break;
				case "python":
					console.log(getListAttr(python_projects, param["attr"]));
					break;
				case "node":
					console.log(getListAttr(node_projects, param["attr"]));
					break;
			}
		}
		
		//关闭连接
		mongoose.connection.close()
	}).catch((err) => {
		//关闭链接
		console.log(err)
		mongoose.connection.close()
  });	
}


function main(){
	var param = {
		type: "",
		name: "",
		attr: ""
	}
	//获取请求参数
	var temp = "";
	process.argv.forEach(function(val, index, array) {
		if (index >= 2) {
			if (index % 2 == 0) {
				temp = val.replace(/\-/, "");
				param[temp] = "";
			} else {
				param[temp] = val;
			}
		}
	});
	controller(param)
	//这里区分使用那个方法，需要注意的是，这里不在提供输出结果，结果在mongo链接中输出
}
try {
	main()
} catch (e) {
		console.log("")
}