var express = require('express');
var app = express();

//require('./clienttmp.js')
const queryString = require("querystring")

//var MongoClient = require('mongodb').MongoClient;
//var dburl = "mongodb://localhost:27017/vr";

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'HS1205',
  database : 'vr'
});
 
connection.connect();

var session = require("express-session");
var cookie = require("cookie-parser");

app.use(cookie());
app.use(session({
	secret: 'secret', // 对session id 相关的cookie 进行签名
	saveUninitialized: true, // 是否保存未初始化的会话
	cookie: { maxAge: 1000 * 60 * 5 },   //过期时间 毫秒为单位
	resave: true,        //每次触发后保存时间
	rolling: true,       // 最后一次触发后计时
}));

app.use(function (req, res, next) {
	var user = req.session.user;
	console.dir(user);
	res.locals.user = req.session.user;
	var err = req.session.error;
	res.locals.message = '';
	if (err) res.locals.message = '<div style="margin-bottom: 20px;color:red;">' + err + '</div>';
	//next();
	console.log(req.path);
	//path模块
	var path = require('path');  /*nodejs自带的模块*/
	var extname = path.extname(req.path);	 //获取文件的后缀名

	console.log(extname);

	var skip = 0;
	if (extname != '.html') {
		skip = 1;
	}
	if (req.path == 'login.html') {
		skip = 1;
	}

	if (skip) {
		next();
		return;
	}

	if (req.path != '/' && !req.session.user)//|| (req.session.user && extname !='.html')))//不是主页  而且没登录或者登录后后缀不是.html的
	{
		// fs.readFile('./practice/login.html', 'utf-8', function (err, data) {
		// 	if (err) {
		// 		throw err;
		// 	}
		// 	res.send(data);

		// })

		//res.redirect(302, '/');

		//window.open('Login.html','_top')

		res.send("<script>window.open('/','_top');</script>")

	}
	else {
		next();
	}
});

var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

var con = require('./conn.js');
const url = require("url")
var fs = require('fs');

app.use(express.static(path.join(__dirname, 'css')));
app.use(express.static(path.join(__dirname, 'practice')));
app.use(express.static(path.join(__dirname, 'node_modules')));
app.use(express.static(path.join(__dirname, 'img')));


app.get('/', function (req, res) {
	console.log("主页 GET 请求");
	//console.log(req.cookies.user);

	var user = req.session.user;
	console.dir(user);


	if (req.session.user) {
		fs.readFile('./views/index.html', 'utf-8', function (err, data) {
			if (err) {
				throw err;
			}
			res.send(data);

		})
	}
	else {
		fs.readFile('./practice/login.html', 'utf-8', function (err, data) {
			if (err) {
				throw err;
			}
			res.send(data);

		})

	}

})

app.get('/logout', function (req, res) {
	console.log("logout")
	console.log("注销用户")
	req.session.destroy();

	fs.readFile('./practice/login.html', 'utf-8', function (err, data) {
		if (err) {
			throw err;
		}
		res.send(data);

	})
})

//  POST 请求
/*
app.post('/', function (req, res) {
	console.log("主页 POST 请求");
	req.rawBody = '';
	var json = {};
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {

		//json=JSON.parse(req.rawBody);
		//res.send(JSON.stringify(json));
		res.send(req.rawBody);
	});

})
*/

app.post('/', function (req, res) {
	console.log("主页 POST 请求");
	req.rawBody = '';

	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		req.rawBody = queryString.parse(req.rawBody)
		var body = req.rawBody;
		//res.send(JSON.stringify(json));
		var a = body.acc;
		var b = body.pwd;

		//console.log(req.cookies.user);

		var user = req.session.user;
		console.dir(user);

		if (a == "admin" && b == "hsvr113" || a == "hs" && b == "111") {
			req.cookies.username = a;
			req.session.user = a;
			fs.readFile('./views/index.html', 'utf-8', function (err, data) {
				if (err) {
					throw err;
				}
				res.send(data);

			})
		}
		else {
			//res.send("账户或密码错误!")
			fs.readFile('./practice/login.html', 'utf-8', function (err, data) {
				if (err) {
					throw err;
				}
				res.send(data);

			})
		}


	});

})

app.post('/dataquery', function (req, res) {
	console.log("dataquery POST 请求");
	req.rawBody = '';
	var json = {};
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		req.rawBody = queryString.parse(req.rawBody)
		var body = req.rawBody;
		var type = body.type;
		var userid = body.userid;
		var begdate = body.begdate;
		begdate = begdate.replace(/T/, " ") + ":00";
		var enddate = body.enddate;
		enddate = enddate.replace(/T/, " ") + ":59";

		var whereStr = { "userid": userid, "monitorTime": { "$gte": begdate, "$lte": enddate } };
		if (!userid) {
			whereStr = {};
		}

		var jsObj = {};
		if (userid) {
			jsObj.userid = userid;
		}
		jsObj.monitorTime = { "$gte": begdate, "$lte": enddate };
		var str = JSON.stringify(jsObj);
		console.log(typeof str);
		var str1 = JSON.parse(str);
		console.log(typeof str1);



		var mysort = { monitorTime: -1 };

		if (type == 'record') {
			var sql = 'SELECT * FROM t_records';
			//查
			connection.query(sql, function (err, result) {
				if (err) {
					console.log('[SELECT ERROR] - ', err.message);
					return;
				}

				console.log('--------------------------SELECT----------------------------');
				console.log(result);
				console.log('------------------------------------------------------------\n\n');

				res.send(result);
			});


		}


		/*
		MongoClient.connect(dburl, { useNewUrlParser: true }, function (err, db) {
			if (err) throw err;

			var dbo = db.db("vr");
			var setname;
			if (type == 'record') {
				setname = 'record';
			}
			else if (type == 'envir') {
				setname = 'envir';
			}
			else if (type == 'warning') {
				setname = 'warning';
			}
			else if (type == 'config') {
				setname = 'config';
			}

			if (setname) {
				//if (setname != 'envir') {
					dbo.collection(setname).find(str1).sort(mysort).toArray(function (err, result) { // 返回集合中所有数据
						if (err) throw err;
						//console.log(result);
						db.close();
						console.log('查询数据库返回');
						res.send(result)
					});
				// }
				// else {
				// 	dbo.collection(setname).find(str1).toArray(function (err, result) { // 返回集合中所有数据
				// 		if (err) throw err;
				// 		//console.log(result);
				// 		db.close();
				// 		console.log('查询数据库返回');
				// 		res.send(result)
				// 	});
				// }
			}

		});
		*/


	});



})


app.post('/getuser', function (req, res) {
	console.log("getuser POST 请求");
	req.rawBody = '';
	var json = {};
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		var a = req.rawBody
		res.send(req.session.user);
	})
})


//模板
app.post('/dbinterface/setname', function (req, res) {
	console.log(" dbinterface setname POST 请求");
	req.rawBody = '';
	var json = {};
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		var body = req.rawBody
		var action = body.action;

		if (action == 'get') {
		}
		else if (action == 'add') {
		}
		else if (action == 'update') {
		}
		else if (action == 'delete') {
		}
	})
})

app.post('/dbinterface/stationinfo', function (req, res) {
	req.rawBody = '';
	var json = {};
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		var body = JSON.parse(req.rawBody);
		var action = body.action;

		console.log(req.path + " " + action + " 请求");
		if (action == 'get') {
			/*
						MongoClient.connect(dburl, { useNewUrlParser: true }, function (err, db) {
							if (err) throw err;
							var dbo = db.db("vr");
							dbo.collection('stationinfo').find({}).toArray(function (err, result) {
								if (err) throw err;
								console.log(result);
								db.close();
								res.send(result)
							});
						});
			*/
		}
		else if (action == 'add') {
			/*
						MongoClient.connect(dburl, { useNewUrlParser: true }, function (err, db) {
							if (err) throw err;
			
							var dbo = db.db("vr");
							var myobj = body.info;
							dbo.collection("stationinfo").insertOne(myobj, function (err, res) {
								if (err) throw err;
								console.log("站点信息插入成功");
								db.close();
							});
			
						});
						*/
		}
		else if (action == 'update') {

		}
		else if (action == 'delete') {


		}



	})
})


//api 模板
app.post('/api/get', function (req, res) {
	console.log(req.path + " 请求");
	req.rawBody = '';
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		var body = JSON.parse(req.rawBody);

		var json = {};
		json['code'] = 200;
		json['message'] = "请求成功"

		json['success'] = 'true'
		json['data'] = {};
		res.send(json);

	})
})




app.post('/api/getallstation', function (req, res) {
	console.log(req.path + " 请求");
	req.rawBody = '';
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		var body = JSON.parse(req.rawBody);

		var json = {};
		json['code'] = 200;
		json['massage'] = "请求成功"

		/*
				MongoClient.connect(dburl, { useNewUrlParser: true }, function (err, db) {
					if (err) throw err;
					var dbo = db.db("vr");
					dbo.collection('stationinfo').find({}).toArray(function (err, result) {
						if (err) throw err;
						//console.log(result);
						db.close();
		
						json['success'] = 'true'
						json['data'] = result;
						res.send(json)
					});
				});
				*/

	})
})

app.post('/api/getstation/:id', function (req, res) {
	console.log(req.path + " 请求");
	req.rawBody = '';
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		var body = JSON.parse(req.rawBody);

		var json = {};
		json['code'] = 200;
		json['massage'] = "请求成功"


		var id = req.params.id;
		var whereStr = { "id": id }

		/*
		MongoClient.connect(dburl, { useNewUrlParser: true }, function (err, db) {
			if (err) throw err;
			var dbo = db.db("vr");
			dbo.collection('stationinfo').find(whereStr).toArray(function (err, result) {
				if (err) throw err;
				console.log(result);
				db.close();

				json['success'] = 'true'
				json['data'] = result;
				res.send(json)
			});
		});
		*/

	})
})

app.post('/api/addstation', function (req, res) {
	console.log(req.path + " 请求");
	req.rawBody = '';
	req.setEncoding('utf8');
	req.on('data', function (chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function () {
		var body = JSON.parse(req.rawBody);

		var json = {};
		json['code'] = 200;
		json['message'] = "请求成功"

		/*
		MongoClient.connect(dburl, { useNewUrlParser: true }, function (err, db) {
			if (err) throw err;

			var dbo = db.db("vr");
			var myobj = body.data;
			dbo.collection("stationinfo").insertOne(myobj, function (err, result) {
				if (err) throw err;
				console.log("站点信息插入成功");

				db.close();

				json['success'] = 'true'
				json['data'] = {};
				res.send(json);
			});

		});
		*/


	})
})






//  login
// app.get('/login', function (req, res) {
// 	console.log("/login 响应  请求");
// 	res.send('login');
// })


var server = app.listen(8081, function () {

	var host = server.address().address
	var port = server.address().port

	console.log("应用实例,访问地址为 http://%s:%s", host, port)

})