var util = require('util');
var Service = require('Service');
var utils = require('utils');
var crypto = require('crypto');
var OrgDao = require('../../dao/org');

/**
 * 设置基础信息
 */
var SetBaseInfo = function() { 
  Service.call(this);
};

util.inherits(SetBaseInfo, Service);

module.exports = SetBaseInfo;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
SetBaseInfo.prototype.process =  function(req, res) { 
  /*if(!req.OrgCode) {
    this.onLogicError(1, '请提供组织代码！', req, res);
    return;
  }
  if(utils.haveEspecialChar(req.OrgCode)) {
    this.onLogicError(2, '组织代码只能是字母和数字！', req, res);
    return;
  }*/
  if(!req.DefaultPassword) {
    this.onLogicError(3, '请提供默认密码！', req, res);
    return;
  }
  if(!req.DefaultTheme) {
    this.onLogicError(4, '请提供系统默认界面风格！', req, res);
    return;
  }

  if(req.DefaultPassword=='********') {
    this.setConfig(req, res);
    return;
  }

  //加密
  var md5 = crypto.createHash('md5');
  md5.update(req.DefaultPassword);
  var password = md5.digest('hex');

  var self = this;
  var orgDao = new OrgDao(this);
  orgDao.update({default_pwd: password}, 
    {where:'id='+req.session.orgId}, function(){
    req.session.cache.setCurOrg({default_pwd: password}, function(){
      self.setConfig(req, res);
    });
  });
};

SetBaseInfo.prototype.setConfig =  function(req, res) { 
  server.config.DefaultTheme = req.DefaultTheme;
  server.config.HomePage = req.HomePage;

  utils.saveJSONToFile(utils.getPath('/config/'+server.id+'.json'), server.config);
  
  this.end(res);
};
