var express = require('express');
var router = express.Router();
var command=require('../util/database');
var model=require('../application');
//登录
router.get('/login', function (req, res, next) {
  res.render('zy002',model);
});
//验证
router.post('/validateuser', function (req, res) {
  let userid = req.body.id,
    pwd = req.body.pwd;
  let sqlstr = "select userid,username,gridid,manager from loginuser where userid='{0}' and password='{1}'";
  command.executesql(sqlstr.format(userid, pwd), (result) => {
    if (result.data && result.data.length > 0) {
      req.session.user = result.data[0];
    }else{
      req.session.user = null;
    }
    res.json(result);
  });
});
//进入主页面
router.get('/', function (req, res, next) {
  res.render('zy001',model);
});
//进入结构图页面
router.get('/zzjg', function (req, res, next) {
  res.render('zy003');
});
//注销
router.get('/logout', function (req, res) {
  req.session.user = null; // 删除session
  res.redirect('login');
});
//修改密码
router.post('/updatepwd', function (req, res) {
  let userid = req.body.userid,
    pwd = req.body.password,
    newpwd = req.body.newpassword;
  let sqlstr = "update loginuser set password='{0}' where userid='{1}' and password='{2}'";
  command.executesql(sqlstr.format(newpwd,userid, pwd), (result) => {
     res.json(result);
  },"update");
});

router.get('/intercom', function (req, res, next) {
  let x=req.url.split('?')[1].split('device_id=')[1];
  if(x===undefined)res.render('intercom-detail');
  res.render('intercom-detail',{device_id:x});
});
module.exports = router;