/**
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.sifang.modules.sys.service;

import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.sifang.modules.sys.common.entity.Menu;
import com.sifang.modules.sys.common.entity.Role;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.dao.MenuDao;
import com.sifang.modules.sys.dao.RoleDao;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.extention.shiro.SystemAuthorizingRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 系统管理，安全相关实体的管理类,包括用户、角色、菜单.
 * @version 22019-11-15
 */
@Service(value="systemService")
@Transactional(readOnly = true,rollbackFor = Exception.class)
public class SystemService extends BaseService {
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private MenuDao menuDao;
	@Resource(name = "DJXSystemRealm")
	private SystemAuthorizingRealm systemRealm;

	//-- User Service --//
	
	public User getUser(String id) {
		return userDao.get(id);
	}
	
	public void updateLoginTime(String userId){
		Db.update(" update sys_user set update_time = ? where id = ? ", new Date(), userId);
	}

	@Transactional(readOnly = false)
	public void saveUser(User user) {
		userDao.clear();
		userDao.save(user);
		systemRealm.clearAllCachedAuthorizationInfo();
		// 同步到Activiti
		//saveActiviti(user);
	}

	@Transactional(readOnly = false)
	public void deleteUser(String id) {
		userDao.deleteById(id);
		// 同步到Activiti
		//deleteActiviti(userDao.get(id));
	}


	public User getUserByLoginName(String loginName) {
		return userDao.findByLoginName(loginName);
	}

	@Transactional(readOnly = false)
	public void updatePasswordById(String id, String loginName, String newPassword) {
		userDao.updatePasswordById(entryptPassword(newPassword), id);
		systemRealm.clearCachedAuthorizationInfo(loginName);
	}
	
	@Transactional(readOnly = false)
	public void updatePassword(String id, String newPassword) {
		userDao.updatePasswordById(entryptPassword(newPassword), id);
	}

	
	/**
	 * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
//		byte[] salt = Digests.generateSalt(SALT_SIZE);
//		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
//		return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
		return HashKit.md5(plainPassword);
	}
	
	public Role getRole(String id) {
		return roleDao.get(id);
	}

	public Role findRoleByName(String name) {
		return roleDao.findByName(name);
	}
	
	@Transactional(readOnly = false)
	public Boolean outUserInRole(Role role, String userId) {
		User user = userDao.get(userId);
		List<String> roleIds = user.getRoleIdList();
		List<Role> roles = user.getRoleList();
		// 
		if (roleIds.contains(role.getId())) {
			roles.remove(role);
			saveUser(user);
			return true;
		}
		return false;
	}
	
	@Transactional(readOnly = false)
	public User assignUserToRole(Role role, String userId) {
		User user = userDao.get(userId);
		List<String> roleIds = user.getRoleIdList();
		if (roleIds.contains(role.getId())) {
			return null;
		}
		user.getRoleList().add(role);
		saveUser(user);		
		return user;
	}
	
	public Menu getMenu(String id) {
		return menuDao.get(id);
	}


}
