var Service = require('Service');
var util = require('util');
var LogDao = require('../../dao/log');

/**
 * 获得日志列表
 */
var GetList = function() { 
  Service.call(this);
};

util.inherits(GetList, Service);

module.exports = GetList;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
GetList.prototype.process =  function(req, res) {
  var self = this;
//   self.onLogicError(1,utils.getPath('文件名'));
  var logDao = new LogDao(this);
  var where = '';
  if(req.start){
    where += ' and time > "'+req.start+' 00:00"';
  }
  if(req.end){
    where += ' and time < "'+req.end+' 23:59"';
  }
  if(req.ipdz){
    where += ' and ip = "'+req.ipdz+'"';
  }
  if(req.yhxm){
    where += ' and (user_name like "%'+req.yhxm+'%")';
  }
  if(req.yy){
    where += ' and app = "'+req.yy+'"';
  }
  if(req.fw){
    where += ' and service = "'+req.fw+'"';
  }
  if(req.lx){
    where += ' and client_type = "'+req.lx+'"';
  }
  if(req.isExport){//导出excel
    logDao.query({where: 'org_id='+req.session.orgId+where,fields: 'id,time,ip,user_name,app,service,client_type,client_version,server_type',order: 'id ASC'}, function(rows) {
        var datas = [];
        var columns = ["操作时间","IP地址","用户姓名","应用","服务","客户端类型","客户端版本","服务器类型"];
        datas.push(columns);
        for(var i=0;i<rows.length;i++) {
          var row = [];
          row.push(rows[i].time);
          row.push(rows[i].ip);
          row.push(rows[i].user_name);
          row.push(rows[i].app);
          row.push(rows[i].service);
          row.push(rows[i].client_type);
          row.push(rows[i].client_version);
          row.push(rows[i].server_type);

          datas.push(row);
        }
        
        var args = {};
        args.data = datas;
        args.appCode = 'syslog';
        args.fileName = '导出信息'+(new Date()).format('_yyyyMMddhhmmss')+'.xlsx';
        self.exportExcel(req, args, function(resIM) {
          self.end(resIM);
        });
    });
  }else{
    logDao.queryDataPage(req, {where:'org_id='+req.session.orgId+where, order: 'id desc'}, function(dataPage){
      res.dataPage = dataPage;
      self.emit('end', res);
    });
  }
};