package com.uas.platform.b2b.v2.service.impl;

import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.User;
import com.uas.sso.entity.UserView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.RoleDao;
import com.uas.platform.b2b.dao.UserDao;
import com.uas.platform.b2b.v2.service.UserService;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.util.encry.Md5Utils;

import java.util.HashSet;
import org.springframework.util.StringUtils;

@Service("v2.UserService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private EnterpriseDao enterpriseDao;
	
	static final String defaultPassword = "111111";

	@Override
	public User save(UserView user) {
		User oldUser = getUser(user);
		if (oldUser == null) { // 如果是新用户，就新增一个user
			oldUser = new com.uas.platform.b2b.model.User(user);
			oldUser.setEnable(Constant.YES);
			oldUser.setUserPwd(Md5Utils.encode(defaultPassword, oldUser.getUserUU()));
		}
		oldUser.setUserEmail(user.getEmail());
		oldUser.setUserIdcode(user.getIdCard());
		oldUser.setUserName(user.getVipName());
		oldUser.setUserSex(user.getSex());
		oldUser.setUserTel(user.getMobile());
		oldUser.setUserIMId(StringUtils.isEmpty(user.getImId()) ? null : Long.valueOf(user.getImId()));
		if (user.getPassword() != null) {
			if (user.getPassword().length() < 32) { // 传过来的是明文
				oldUser.setUserPwd(Md5Utils.encode(user.getPassword(), user.getUserUU()));
			} else {
				oldUser.setUserPwd(user.getPassword());// 传过来的是密文
			}
		}
		oldUser = userDao.save(oldUser);
		return oldUser;
	}

	private com.uas.platform.b2b.model.User getUser(UserView user) {
		com.uas.platform.b2b.model.User oldUser = null;
		if (user.getUserUU() != null) {
			oldUser = userDao.findOne(user.getUserUU());
		}
		return oldUser;
	}

	@Override
	public void changePassword(UserView user, String password) {
		User oldUser = getUser(user);
		if (oldUser != null) {
			oldUser.setUserPwd(Md5Utils.encode(password, oldUser.getUserUU()));
			userDao.save(oldUser);
		}
	}

	@Override
	public void addUser(Long spaceUU, UserView userView) {
		User user = userDao.findOne(userView.getUserUU());
		Enterprise enterprise = enterpriseDao.findOne(spaceUU);
		if (user == null) {
			user = new User(userView);
			user.setEnterprises(new HashSet<Enterprise>());
		}
		if (user == null || enterprise == null) {
			return;
		}
		user.getEnterprises().add(enterprise);
		userDao.save(user);
	}

	@Override
	public void removeUser(Long spaceUU, Long userUU) {
		User user = userDao.findOne(userUU);
		Enterprise enterprise = enterpriseDao.findOne(spaceUU);
		if (user == null || enterprise == null) {
			return;
		}

		user.getEnterprises().remove(enterprise);
		userDao.save(user);
	}

}
