var fs = require("fs"); 
var bodyParser = require('body-parser'); // 这个模块是获取post请求传过来的数据。
var multer  = require('multer'); //multer - node.js 中间件，用于处理 enctype="multipart/form-data"（设置表单的MIME编码）的表单数据。
var  express=require('express');
var  app=express();
var mysql=require('mysql');
var execSync = require("child_process").execSync;
var fs = require("fs");
/**
 * 配置MySql
 */
var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'root',
    password : 'xwdjzwy5252',
    database : 'test',
    port:'3306'
});
connection.connect();
app.use('/public', express.static('public')); // 设置静态文件的中间件
app.use(bodyParser.urlencoded({ extended: false })); // 判断请求体是不是json，不是的话把请求体转化为对象
app.use(multer({ dest: 'tmp/' }).array('file'));//multer中间件用于上传表单型数据，基本属性为dest，会添加file对象到request对象中，包含对象表单上传的文件信息
app.get('/',function (req,res) {
    res.sendfile(__dirname + "/public/" + "index.html" );
})
 
/**
 * 实现登录验证功能
 */
app.get('/login', function (req, res) {
    var response = {
        "name":req.query.name,
        "password":req.query.pwd,
    };
    /*var selectSQL = "select * from UserInfoTest where User_Name = '" + name + "' and User_Password = '" + password + "'";*/
    var selectSQL = "select User_Name,User_password from UserInfoTest where User_Name = '" + req.query.name + "' and User_Password = '" + req.query.pwd + "'";
    connection.query(selectSQL, function (err, result) {
        if (err) {
            console.log('[login ERROR] - ', err.message);
            return;
        }
        if (result == '') {
            console.log("帐号密码错误");
            res.end("The account does not exist or the password is wrong!");
        }
        else {
            console.log(result);
            console.log("OK");

            res.redirect("/public/" + "ok.html");//重定向到网页
        }
    });
    console.log(response);
})

    /**connection.query(selectSQL,function (err,rs) {
        if (err) throw  err;
        console.log(rs);
        console.log('OK');
        res.sendfile(__dirname + "/public/" + "ok.html" );
    })
})**/
 
app.get('/register.html',function (req,res) {
    res.sendfile(__dirname+"/public/"+"register.html");
})
 
/**
 * 实现注册功能
 */
app.get('/register',function (req,res) {
    var  name=req.query.name;
    var pwd = req.query.pwd;
    var selectSQL = "select User_Name,User_password from UserInfoTest where User_Name = '" + req.query.name+"'";
    connection.query(selectSQL, function (err, result) {
        if (err) {
            console.log('[login ERROR] - ', err.message);
            return;
        }
        if (result.length) {
            res.send("The account exist!");
        }
        else {
            var user = { User_Name: name, User_Password: pwd };
            connection.query('insert into UserInfoTest set ?', user, function (err, rs) {
                if (err) throw err;
                console.log('ok');
                res.redirect("/public/" + "index.html");
            })
        }
    })
})

app.get('/ok.html',function (req,res) {
    res.redirect("/public/"+"ok.html");
})
 
 
 
var  server=app.listen(3000,function () {
    console.log("start");
})

 // 上传文件api
app.post('/file_upload', function (req, res) {
 
   console.log(req.files[0]);  // 上传的文件信息
 
   var des_file = __dirname + "/0/" + req.files[0].originalname; 
   fs.readFile( req.files[0].path, function (err, data) {  
        fs.writeFile(des_file, data, function (err) { 
         if( err ){
              console.log( err );
         }else{
               response = {
                   message:'File uploaded successfully', 
                   filename:req.files[0].originalname
              };
          }
          console.log( response );
          res.end( JSON.stringify( response ) );
       });
   });
})

function execute(cmd) {     //调用cmd命令
    execSync(cmd, { cwd: './' }, function (error, stdout, stderr) {
        if (error) {
            console.error(error);
        }
        else {
            console.log("executing success!")
        }
    })
}
app.post('/check', function (req, res) {
    execute('python connect.py --ip 127.0.0.1 --port 7777 crawling --word computer');
    fs.readFile('./result.txt', 'utf-8', function (err, data) {
        if (err) {
            console.error(err);
        }
        else {
            res.send(data);
        }
    });
    
})
 

