package com.cloudcross.ssp.back.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import com.cloudcross.ssp.back.model.User;
import com.cloudcross.ssp.back.model.UserGroup;
import com.cloudcross.ssp.back.service.ISecurityService;
import com.cloudcross.ssp.back.service.IUserService;
import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.common.utils.Assert;
import com.cloudcross.ssp.common.utils.MapBuilder;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.common.utils.SqlHelper;
import com.cloudcross.ssp.web.widget.SelectorController.ISelector;
import com.cloudcross.ssp.web.widget.SelectorController.ISelectorProvider;

@Service
public class UserService implements IUserService,ISecurityService, ISelectorProvider {
	private static final Logger LOG = Logger.getLogger(UserService.class);
	
	@Autowired
	private GenericIBatisDao myBatisDao;
	
	@Override
	public boolean add(String userGroupType, User user) {
		// 添加一个用户组。
		UserGroup userGroup = new UserGroup();
		userGroup.setUserGroup(user.getUsername());
		userGroup.setUserGroupType(userGroupType);
		myBatisDao.save("back.userGroupSqlMapper.addUserGroup", userGroup);
		
		// 添加一个用户。
		user.setUserGroupId(userGroup.getId());
		user.setPassword(user.getPassword());
		user.setCreateDate(new Date());
		myBatisDao.save("back.userSqlMapper.addUser", user);
		
		return true;
	}

	@Override
	public int countByParams(Map<String, Object> paramMap) {
		String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
		paramMap.put("key", paramMap.get("searchKey"));
		paramMap.put("value", searchValue);
		return myBatisDao.get("back.userSqlMapper.countByParams", paramMap);
	}

	@Override
	public boolean edit(User user) {
		user.setModifyDate(new Date());
		myBatisDao.save("back.userSqlMapper.editUser", user);
		return true;
	}

	@Override
	public User findById(Long id) {
		return myBatisDao.get("back.userSqlMapper.selectById", id);
	}

	@Override
	public List<User> findByParams(Map<String, Object> paramMap, Pager pager) {
		String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
		paramMap.put("key", paramMap.get("searchKey"));
		paramMap.put("value", searchValue);
		paramMap.put("pager", pager);
		return myBatisDao.getList("back.userSqlMapper.selectByParams", paramMap);
	}

	@Override
	public User findByUsername(String username) {
		return myBatisDao.get("back.userSqlMapper.selectByUsername", username);
	}
	
	@Override
	public List<User> findByUserGroupType(String userGroupType) {
		return myBatisDao.getList("back.userSqlMapper.selectByUserGroupType",
				userGroupType);
	}

	/**
	 * @see UserDetailsService#loadUserByUsername(String)
	 */
//	@Override
//	public UserDetails loadUserByUsername(String s)
//			throws UsernameNotFoundException {
//		UserDetails userDetails = null;
//		User user = findByUsername(s);
//		if (user == null) {
//			String warnMsg = "用户("+s+")禁用或者不存在！";
//			LOG.info(warnMsg);
//			throw new UsernameNotFoundException(warnMsg);
//		}
		
		// 查找登录用户角色
//		UserGroup userGroup = findUserGroupById(user.getUserGroupId());
//		String myRole = UserRole.SPRING_SECURITY_ROLE_PREFIX.concat(userGroup
//				.getUserGroupType());
//		LOG.info("用户（" + s + "）角色信息：" + myRole);
//		
//		userDetails = new org.springframework.security.core.userdetails.User(
//				user.getUsername(), user.getPassword(), true, true, true, true,
//				Arrays.asList(new GrantedAuthorityImpl(myRole)));
//		return userDetails;
//	}

	@Override
	public UserGroup findUserGroupById(Long userGroupId) {
		UserGroup userGroup = myBatisDao.get(
				"back.userGroupSqlMapper.findUserGroupById", userGroupId);
		return userGroup;
	}

	@Override
	public boolean updateStatus(List<Long> userIdList, int status) {
		myBatisDao.save("back.userSqlMapper.updateUserStatus",
				MapBuilder.create(HashMap.class)
					.add("userIdList", userIdList)
					.add("modifyDate", new Date())
					.add("status", status).map());
		return true;
	}

	@Override
	public boolean add(User t) {
		throw new UnsupportedOperationException();
	}

	@Override
	public Map<String, List<? extends ISelector>> provideData(String[] parentId) {
		Assert.isTrue(ArrayUtils.isNotEmpty(parentId));
		String userGroupType = parentId[0];
		List<User> userList = findByUserGroupType(userGroupType);
		return MapBuilder.create(HashMap.class).add(userGroupType, userList)
				.map();
	}

}
