package com.ibeetl.admin.core.service;

import com.ibeetl.admin.core.conf.PasswordConfig.PasswordEncryptService;
import com.ibeetl.admin.core.dao.CoreOrgDao;
import com.ibeetl.admin.core.dao.CoreUserDao;
import com.ibeetl.admin.core.dao.CoreUserPwdDao;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.CoreUserPwd;
import com.ibeetl.admin.core.rbac.UserLoginInfo;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.enums.DelFlagEnum;
import com.ibeetl.admin.core.util.enums.GeneralStateEnum;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CoreUserService {
	@Autowired
	CoreUserDao userDao;

	@Autowired
	CoreOrgDao orgDao;

	@Autowired
	PasswordEncryptService passwordEncryptService;
	@Autowired
	CoreUserPwdDao coreUserPwdDao;

	@Autowired
	SQLManager sqlManager;

	public UserLoginInfo login(String encodeKey, String userName,
			String password) {
		UserLoginInfo loginInfo = new UserLoginInfo();
			Query<CoreUser> query = sqlManager.query(CoreUser.class);
			
			CoreUser user = query.andEq("CODE", userName).single();
			System.out.println("user = " + user);
			
				if (user == null) {
					throw new PlatformException("用户" + userName + "不存在或者密码错误");
					
				}
				if (!user.getState().equals(GeneralStateEnum.ENABLE.getValue())) {
					throw new PlatformException("用户" + userName + "已经失效");
				}
				if (user.getDelFlag() == DelFlagEnum.DELETED.getValue()) {
					throw new PlatformException("用户" + userName + "已经删除");
				}
				if(!password.equals(user.getPassword())){
					throw new PlatformException("用户" + userName + "密码错误");
				}
				List<CoreOrg> orgs = getUserOrg(user.getId(), user.getOrgId());
				
				loginInfo.setOrgs(orgs);
				
				loginInfo.setUser(user);
				return loginInfo;
				

	}
/*	public UserLoginInfo login(String encodeKey, String userName,
			String password) {
		CoreUser user = null;
		String pas = "";
		try {
			CoreUser query = new CoreUser(encodeKey, password);
			query.setCode(userName);
			
			query.setState(GeneralStateEnum.ENABLE.getValue());
			user = userDao
					.createLambdaQuery()
					.andEq(CoreUser::getCode, userName)
					.andEq(CoreUser::getPassword,
							DesUtilTo32.encode(encodeKey,password)).single();
			if (user == null) {
				throw new PlatformException("用户" + userName + "不存在或者密码错误");
				
			}
			if (!user.getState().equals(GeneralStateEnum.ENABLE.getValue())) {
				throw new PlatformException("用户" + userName + "已经失效");
			}
			if (user.getDelFlag() == DelFlagEnum.DELETED.getValue()) {
				throw new PlatformException("用户" + userName + "已经删除");
			}
			pas = DesUtilTo32.encode(encodeKey, password);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<CoreOrg> orgs = getUserOrg(user.getId(), user.getOrgId());
		UserLoginInfo loginInfo = new UserLoginInfo();
		loginInfo.setOrgs(orgs);
		
		user.setPassword(pas);
		System.out.println("加密----" + pas);
		loginInfo.setUser(user);
		return loginInfo;
		
	}
*/
	public List<CoreOrg> getUserOrg(long userId, long orgId) {
		List<CoreOrg> orgs = orgDao.queryOrgByUser(userId);
		if (orgs.isEmpty()) {
			// 没有赋值任何角色，默认给一个所在部门
			CoreOrg userOrg = orgDao.unique(orgId);
			orgs.add(userOrg);
		}
		return orgs;
	}

	public List<CoreUser> getAllUsersByRole(String role) {
		return userDao.getUserByRole(role);
	}

	public CoreUser getUserByCode(String userName) {
		CoreUser user = new CoreUser("", "");
		user.setCode(userName);
		return userDao.templateOne(user);
	}

	public void update(CoreUser user) {
		userDao.updateById(user);
	}

	public CoreOrg getOrgById(Long orgId) {
		return orgDao.unique(orgId);
	}

	public CoreUser getUserById(Long userId) {
		return userDao.unique(userId);
	}

	public List<String> getOrgCode(List<Long> orgIds) {
		return orgDao.queryAllOrgCode(orgIds);
	}

	/**
	 * 判断是否进入修改密码页面
	 * @param usercode
	 * @param exporetime
	 * @return
	 * @throws Exception
	 */
	public boolean ifUpUserPwd(String usercode,String exporetime,String ifexpore) throws Exception{
		boolean ifup=true;
		if("S1".equals(ifexpore)) {
			List<CoreUserPwd> list = coreUserPwdDao.getUserPwd(usercode);
			if (list.size() > 0) {
				if (exporetime != null || "".equals(exporetime)) {
					if (Integer.valueOf(exporetime) > DateUtil.mathday(list.get(0).getInserttime(), DateUtil.now("yyyy-MM-dd HH:mm:ss"),
							"yyyy-MM-dd HH:mm:ss") / (3600000 * 24)) {
						ifup = false;
					}
				}
			}
		}else{
			return false;
		}
		return ifup;
	}
}
