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

import com.uas.sso.util.AccountUtils;
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.model.Enterprise;
import com.uas.platform.b2b.model.Role;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.temporary.model.ChangeAdminDetail;
import com.uas.platform.b2b.v2.service.ChangeAdminService;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.util.encry.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@SuppressWarnings("deprecation")
@Service("v2.ChangeAdminService")
public class ChangeAdminServiceImpl implements ChangeAdminService {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private EnterpriseDao enterpriseDao;

	/**
	 * 删除方法
	 */
	private final String REMOVE_METHOD = "remove";

	/**
	 * 初始密码
	 */
	static final String defaultPassword = "111111";

	@SuppressWarnings("null")
	@Override
	public Enterprise save(ChangeAdminDetail detail) {
		// 如果用户存在，则更换管理员
		User user = userService.findUserByUserTel(detail.getAdminTel());
		Enterprise enterprise = enterpriseDao.findEnterpriseByEnBussinessCode(detail.getBusinessCode());
		// 如果方式是删除，解除以前管理员与本企业的关系
		if((REMOVE_METHOD).equals(detail.getMethod())) {
			EnterpriseDeleteUser(enterprise);
		} else {
			// 将以前的管理员设置成普通用户
			updateUserRole(enterprise);
		}
		if (user != null) {
			enterprise.setEnAdminuu(user.getUserUU());
			enterprise.setAdmin(user);
			user.addEnterprise(enterprise);
			user.setCurrentEnterprise();
			user.setEnable(Constant.YES);
			// 将用户设置为管理员，只对用户的当前企业的角色进行修改
			// 新用户注册企业时为空
			Set<Role> existRoles = new HashSet<Role>();
			// 老用户注册新企业
			if (!CollectionUtils.isEmpty(user.getRoles())) {
				existRoles = user.getRoles();
			}
			// 设置为本企业管理员
			List<Role> adminList = roleDao.findByEnUUAndDesc(enterprise.getUu(), "管理员");
			existRoles.add(adminList.get(0));
			user.setRoles(existRoles);
			userDao.save(user);
			enterprise = enterpriseDao.save(enterprise);
		} else {// 不存在的话调用新增用户的方法新增一个用户
			User newUser = new User();
			newUser.setUserEmail(detail.getAdminEmail());
			newUser.setUserTel(detail.getAdminTel());
			newUser.setUserName(detail.getAdminName());
			newUser.setUserUU(null);
			newUser.addEnterprise(SystemSession.getUser().getEnterprise());
			newUser.setCurrentEnterprise();
			newUser = userDao.save(newUser);
			newUser.setUserPwd(Md5Utils.encode(defaultPassword, newUser.getUserUU()));
			enterprise.setEnAdminuu(newUser.getUserUU());
			enterprise.setAdmin(newUser);
			newUser.addEnterprise(enterprise);
			newUser.setCurrentEnterprise();
			newUser.setEnable(Constant.YES);
			// 将用户设置为管理员，只对用户的当前企业的角色进行修改
			// 新用户注册企业时为空
			Set<Role> existRoles = new HashSet<Role>();
			// 老用户注册新企业
			if (!CollectionUtils.isEmpty(user.getRoles())) {
				existRoles = user.getRoles();
			}
			// 设置为本企业管理员
			List<Role> adminList = roleDao.findByEnUUAndDesc(enterprise.getUu(), "管理员");
			existRoles.add(adminList.get(0));
			user.setRoles(existRoles);
			userDao.save(newUser);
			enterprise = enterpriseDao.save(enterprise);
		}
		return enterprise;
	}

	private void updateUserRole(Enterprise enterprise) {
		User newUser =  userDao.findOne(enterprise.getEnAdminuu());
		if (!CollectionUtils.isEmpty(newUser.getRoles())) {
			Set<Role> existRoles = newUser.getRoles();
			// 保留用户在其他企业的角色
			if(!CollectionUtils.isEmpty(existRoles)) {
				Iterator<Role> iterator = existRoles.iterator();
				Long currentEnuu = enterprise.getUu();
				while (iterator.hasNext()) {
					Role role = iterator.next();
					if(role.getEnUU().equals(currentEnuu)) {
						iterator.remove();
					}
				}
			} else {
				existRoles = new HashSet<>();
			}
			newUser.setRoles(existRoles);
			try {
				userDao.save(newUser);
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage());
			}
		}

	}


	private void EnterpriseDeleteUser(Enterprise enterprise) {
		User user = userDao.findOne(enterprise.getEnAdminuu());
		if (user.getEnterprises().contains(enterprise)) {
			try {
				AccountUtils.removeUser(user.getUserUU(), enterprise.getUu());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void save(Enterprise enterprise) {
		enterpriseDao.save(enterprise);
	}

}
