var util = require('util');
var utils = require('utils');
var crypto = require('crypto');
var uuid = require('node-uuid');
var Service = require('Service');
var Connection = require('Connection');
var Org = require('../../dao/org');
var Dep = require('../../dao/dep');
var User = require('../../dao/user');
var Role = require('../../dao/role');
var DepUser = require('../../dao/dep_user');
var RoleUser = require('../../dao/role_user');
var AppAuthDao = require('../../dao/app_auth');
var OrgAppDao = require('../../dao/org_app');
var OrgAppCategoryDao = require('../../dao/org_app_category');

var Create = function() {
	Service.call(this);
  this.checkLogin = false;
};

util.inherits(Create, Service);

module.exports = Create;

Create.prototype.process =  function(req, res, cb) {
	if(!req.orgCode) {
		this.onLogicError(2, '请提供组织代码！');
		return;
	}
	if(!req.orgName) {
		this.onLogicError(3, '请提供组织名称！');
		return;
	}
	var self = this;
	var orgDao = new Org(this);
	orgDao.query({where:"code='"+req.orgCode+"'"}, function(rows1) {
    if(rows1.length>0) {
    	self.onLogicError(4, '组织代码已存在！');
		  return;
    }
		orgDao.query({where:"name='"+req.orgName+"'"}, function(rows2) {
	    if(rows2.length>0) {
	    	self.onLogicError(5, '组织名称已存在！');
			  return;
	    }

	    var org = {};
	    org.code = req.orgCode;
	    org.name = req.orgName;
	    org.status = 0;
	    org.creater_id = 1;
	    org.createtime = new Date();
	    org.last_update = new Date();
	    org.auth_key = uuid.v1().replace(/-/g,'');  //组织身份验证Key
	    org.user_count = 20;
		  if(req.user_count) org.user_count = parseInt(req.user_count);
		  org.default_pwd = utils.md5('taskmsg');
	    if(req.default_pwd) org.default_pwd = utils.md5(req.default_pwd);

	    //通讯录相关设置
	    org.look_all = 1;                       //可以查看全部
	    org.look_self_bureau = 1;               //可以查看本单位
	    org.look_self_dep = 1;                  //可以查看本部门
	    org.look_leader = 1;                    //可以查看领导
	    org.look_under = 1;                     //可以查看下属
	    org.show_nickname_in_user_list = 0;     //是否在用户列表中显示昵称
	    org.show_netstatus_in_user_list = 0;    //是否在用户列表中显示网络状态
	    org.show_post_in_user_list = 0;         //是否在用户列表中显示职务
	    org.show_motto_in_user_list = 0;        //是否在用户列表中显示个性签名
	    org.show_type_in_role_list = 0;         //是否在群组列表中显示类型
	    org.show_description_in_role_list = 0;  //是否在群组列表中显示描述
	    org.user_cell_left_info = 'name';       //在用户列表中左侧显示的信息，默认为姓名
	    org.user_cell_right_info = 'mobile';    //在用户列表中右侧显示的信息，默认为手机号码
	    org.user_cell_bottom_info = 'post';     //在用户列表中底部显示的信息，默认为职务
	    org.allow_add_friend = 0;               //是否允许添加好友，默认为否
	    if(req.look_all==0) org.look_all = 0;  //可以查看全部
	    if(req.look_self_bureau==0) org.look_self_bureau = 0;  //可以查看本单位
	    if(req.look_self_dep==0) org.look_self_dep = 0;  //可以查看本部门
	    if(req.look_leader==0) org.look_leader = 0;  //可以查看领导
	    if(req.look_under==0) org.look_under = 0;  //可以查看下属
	    if(req.show_nickname_in_user_list) org.show_nickname_in_user_list = 1;  //是否在用户列表中显示昵称
	    if(req.show_netstatus_in_user_list) org.show_netstatus_in_user_list = 1;  //是否在用户列表中显示网络状态
	    if(req.show_post_in_user_list) org.show_post_in_user_list = 1;  //是否在用户列表中显示职务
	    if(req.show_motto_in_user_list) org.show_motto_in_user_list = 1;  //是否在用户列表中显示个性签名
	    if(req.show_type_in_role_list) org.show_type_in_role_list = 1;  //是否在群组列表中显示类型
	    if(req.show_description_in_role_list) org.show_description_in_role_list = 1;  //是否在群组列表中显示描述
	    if(req.user_cell_left_info) org.user_cell_left_info = req.user_cell_left_info;  //在用户列表中左侧显示的信息，默认为姓名
	    if(req.user_cell_right_info) org.user_cell_right_info = req.user_cell_right_info;  //在用户列表中右侧显示的信息，默认为手机号码
	    if(req.user_cell_bottom_info) org.user_cell_bottom_info = req.user_cell_bottom_info;  //在用户列表中底部显示的信息，默认为职务
	    if(req.allow_add_friend) org.allow_add_friend = 1;  //是否允许添加好友，默认为否
      
      //聊天有关设置
	    org.disable_chat = 0;  //是否禁用即时通讯，默认否
	    org.create_group = 1;  //是否可以创建群组，默认是
	    org.ignore_pc_online = 0;  //手机客户端是否忽略PC客户端是否在线都会提醒，默认否
	    org.apns_channel = 0;  //APNS通道编号，默认为0
	    if(req.disable_chat) org.disable_chat = 1;  //是否禁用即时通讯，默认否
	    if(req.create_group==0) org.create_group = 0;  //是否可以创建群组，默认是
	    if(req.ignore_pc_online) org.ignore_pc_online = 1;  //手机客户端是否忽略PC客户端是否在线都会提醒，默认否
	    if(req.apns_channel) org.apns_channel = req.apns_channel;  //APNS通道编号，默认为0
	    
	    //底部导航栏及应用中心设置
	    org.only_app_center = 0;  //是否仅显示应用中心，默认否
	    org.disable_app_center = 0;  //是否禁用应用中心，默认否
	    org.show_app_center_banner = 1;  //是否显示应用中心广告条，默认显示
	    org.appcenter_netdisk = 0;  //是否在应用中心显示网盘，默认否
	    org.disable_appmarket = 0;  //是否禁用应用市场，默认不禁用
	    org.disable_taskmsg = 0;  //是否禁用任讯，默认不禁用
	    org.disable_address_book = 0;  //是否禁用通讯录，默认不禁用
	    org.disable_msg_center = 0;  //是否禁用消息中心，默认不禁用
	    org.disable_work_circle = 1;  //是否禁用朋友圈，默认禁用
	    if(req.only_app_center) org.only_app_center = 1;  //是否仅显示应用中心，默认否
	    if(req.disable_app_center) org.disable_app_center = 1;  //是否禁用应用中心，默认否
	    if(req.show_app_center_banner==0) org.show_app_center_banner = 0;  //是否显示应用中心广告条，默认显示
	    if(req.appcenter_netdisk) org.appcenter_netdisk = 1;  //是否在应用中心显示网盘，默认否
	    if(req.disable_appmarket) org.disable_appmarket = 1;  //是否禁用应用市场，默认不禁用
	    if(req.disable_taskmsg) org.disable_taskmsg = 1;  //是否禁用任讯，默认不禁用
	    if(req.disable_address_book) org.disable_address_book = 1;  //是否禁用通讯录，默认不禁用
	    if(req.disable_msg_center) org.disable_msg_center = 1;  //是否禁用消息中心，默认不禁用
	    if(req.disable_work_circle==0) org.disable_work_circle = 0;  //是否禁用朋友圈，默认禁用
	    
	    //个性化logo、加载图片、应用中心顶部图片设置
	    org.disable_set_ad = 0;  //是否禁止设置应用中心广告条，默认不禁止
	    org.disable_set_logo = 0;  //是否禁止设置Logo，默认不禁止
	    org.disable_set_slogan = 0;  //是否禁止设置口号，默认不禁止
	    org.disable_set_launch_image = 0;  //是否禁止设置加载图片，默认不禁止
	    if(req.disable_set_ad) org.disable_set_ad = 1;  //是否禁止设置应用中心广告条，默认不禁止
	    if(req.disable_set_logo) org.disable_set_logo = 1;  //是否禁止设置Logo，默认不禁止
	    if(req.disable_set_slogan) org.disable_set_slogan = 1;  //是否禁止设置口号，默认不禁止
	    if(req.disable_set_launch_image) org.disable_set_launch_image = 1;  //是否禁止设置加载图片，默认不禁止
	    
	    //网盘
	    org.disk_limit = 10;  //网盘存储空间大小，默认10G
	    org.disk_limit_unit = 'G';
	    org.file_size_limit = 200*1024*1024; //文件上传最大尺寸，默认200M
	    if(req.disk_limit) org.disk_limit = parseInt(req.disk_limit);  //网盘存储空间大小，默认10G
	    if(req.disk_limit_unit) org.disk_limit_unit = req.disk_limit_unit;
	    if(req.file_size_limit) org.file_size_limit = parseInt(req.file_size_limit)*1024*1024; //文件上传最大尺寸，默认200M
	    //其他设置
	    org.custom_install_package = 0;  //是否使用自定义安装包，默认不使用
	    org.allow_regist = 1;  //是否允许用户注册，默认允许
	    org.disable_chpwd = 0;  //是否禁止修改密码，默认不禁止
	    org.hide_about = 0;  //手机端是否隐藏关于菜单，默认不隐藏
	    org.bind_client_device = 0;  //手机端是否绑定设备，默认不绑定
      org.auth_end_date = new Date();  //授权截止日期，默认30天
      org.auth_end_date.setDate(org.auth_end_date.getDate()+30);
      if(req.custom_install_package) org.custom_install_package = 1;  //是否使用自定义安装包，默认不使用
	    if(req.allow_regist==0) org.allow_regist = 0;  //是否允许用户注册，默认允许
	    if(req.disable_chpwd) org.disable_chpwd = 1;  //是否禁止修改密码，默认不禁止
	    if(req.hide_about) org.hide_about = 1;  //手机端是否隐藏关于菜单，默认不隐藏
	    if(req.bind_client_device) org.bind_client_device = 1;  //手机端是否绑定设备，默认不绑定
      if(req.auth_end_date) org.auth_end_date = req.auth_end_date;

	    orgDao.create(org, function(retOrg) {
	    	org.id = retOrg.insertId;
	    	self.createUser(req, res, org, cb);
	    });
	  });
  });
};

Create.prototype.createUser =  function(req, res, org, cb) {
	var user = {};
  user.org_id = org.id;
  user.code = '9999';
  
  user.name = '管理员';
  user.loginname = 'admin';
  user.password = org.default_pwd;
  
  user.status = 0;
  user.sex = 0; 
  user.creater_id = 0;
  user.head_id = 0;
  user.createtime = new Date();
  
  user.disable_address_book = org.disable_address_book;
  user.create_group = org.create_group;
  user.look_all = 1;
  user.look_self_bureau = 1;
  user.look_self_dep = 1;
  user.look_leader = 1;
  user.look_under = 1;
  user.disable_work_circle = org.disable_work_circle;
  user.only_app_center = org.only_app_center;

  var self = this;
  var userDao = new User(this);
  userDao.create(user, function(retUser) {
  	user.id = retUser.insertId;
  	userDao.update({creater_id: retUser.insertId}, 
      {where: 'id='+retUser.insertId+' and org_id='+org.id},
    function(){
	  	self.createDep(req, res, org, user, cb);
	  });
  });
};

Create.prototype.createDep =  function(req, res, org, user, cb) {
	var dep = {};
  dep.org_id = org.id;
  dep.code = '01';
  dep.name = '默认部门';
  dep.fullname = dep.name;
  dep.status = 0;
  dep.parent_id = 0;
  dep.creater_id = user.id;
  dep.createtime = new Date();

  var self = this;
  var depDao = new Dep(this);
  depDao.create(dep, function(retDep) {
  	dep.id = retDep.insertId;
  	var dep_user = {};
    dep_user.org_id = org.id;
    dep_user.dep_id = dep.id;
    dep_user.user_id = user.id;
    dep_user.creater_id = user.id;
    dep_user.createtime = new Date();

    var depUserDao = new DepUser(self);
    depUserDao.create(dep_user, function(){
    	self.createRole(req, res, org, user, cb);
    });
  });
};

Create.prototype.createRole =  function(req, res, org, user, cb) {
	var role = {};
  role.code = '01';
  role.name = '系统管理员';
  role.org_id = org.id;
  role.status = 0;
  role.creater_id = user.id;
  role.createtime = new Date();
  role.disable_address_book = org.disable_address_book;
  role.disable_work_circle = org.disable_work_circle;
  role.only_app_center = org.only_app_center;

  var self = this;
  var roleDao = new Role(this);
  roleDao.create(role, function(retRole) {
    role.id = retRole.insertId;
  	var role2 = {};
    role2.code = '02';
    role2.name = '所有人';
    role2.org_id = org.id;
    role2.status = 0;
    role2.creater_id = user.id;
    role2.createtime = new Date();
    role2.disable_address_book = org.disable_address_book;
    role2.disable_work_circle = org.disable_work_circle;
    role2.only_app_center = org.only_app_center;
    roleDao.create(role2, function(retRole2) {
      role2.id = retRole2.insertId;
      var role_user = {};
      role_user.org_id = org.id;
      role_user.role_id = role.id;
      role_user.user_id = user.id;
      role_user.creater_id = user.id;
      role_user.createtime = new Date();
      var roleUserDao = new RoleUser(self);
      roleUserDao.create(role_user, function(){
        var role_user2 = {};
        role_user2.org_id = org.id;
        role_user2.role_id = role2.id;
        role_user2.user_id = user.id;
        role_user2.creater_id = user.id;
        role_user2.createtime = new Date();
        roleUserDao.create(role_user2, function(){
        	self.createAppInfo(req, res, org, user, role, cb);
        });
      });
    });
  });
};

Create.prototype.createAppInfo =  function(req, res, org, user, role, cb) {
	var appCategory = {
		code: '99',
		name: '系统维护',
		org_id: org.id,
		parent_id: 0,
		group_apps: 0,
		order_no: 99
	};
	var self = this;
	var daoAppCategory = new OrgAppCategoryDao(this);
	daoAppCategory.create(appCategory, function(ret) {
		appCategory.id = ret.insertId;
		var daoApp = new OrgAppDao(self);
		daoApp.execute('insert into sys_org_app(org_id,app_id,category_id,'
			+'status,installer_id,install_time,order_no) select '+org.id+',id,'
			+appCategory.id+',0,'+user.id+',sysdate(),id from sys_app '
			+'where developer_id=1 and category_id=1 and status=0', null, function() {
			var daoAppAuth = new AppAuthDao(self);
			daoAppAuth.execute('insert into sys_app_auth(org_id,app_id,owner_type,'
				+'owner_id,terminal) select '+org.id+',app_id,"role",'+role.id
				+',"web" from sys_org_app where org_id='+org.id, null, function(){

				if(cb) {
					cb(org, user);
					return;
				}
				
				//先结束服务，提交数据库事务，将数据保存到数据库中
				//否则，在下面加载组织的缓存数据时，由于不是同一个数据库连接，无法查询到上面添加的数据
				self.end(res);
				
				server.cache.loadOrgData(org.id, function(errCache) {
					if(errCache) {
						logger.log(errCache);
						return;
					}
				});
			});
		});
	});
};