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

import com.uas.platform.b2b.dao.RoleDao;
import com.uas.platform.b2b.model.Role;
import com.uas.sso.entity.UserSpaceView;
import com.uas.sso.entity.UserSpaceDetail;
import com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.UserDao;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.support.CommBufferedLogger;
import com.uas.platform.b2b.v2.service.EnterpriseService;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.model.Status;
import com.uas.sso.entity.UserView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

@Service("v2.EnterpriseService")
public class EnterpriseServiceImpl implements EnterpriseService {

	@Autowired
	private EnterpriseDao enterpriseDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;

	private final static CommBufferedLogger logger = BufferedLoggerManager.getLogger(CommBufferedLogger.class);

	@Override
	public Enterprise save(UserSpaceView detail) {
		Enterprise enterprise = getEnterprise(detail);
		boolean isNew = false;
		if (enterprise == null) {
			enterprise = new Enterprise();
			enterprise.setEnStatus((short) Status.ENABLED.value());
			isNew = true;
		}

		enterprise.setUu(detail.getSpaceUU());
		enterprise.setEnAddress(detail.getRegAddress());
		enterprise.setBusinesscodeimg(detail.getBusinessCodeImage());
		enterprise.setEnAdminEmail(detail.getAdmin().getEmail());
		enterprise.setEnAdminName(detail.getAdmin().getVipName());
		enterprise.setEnAdminTel(detail.getAdmin().getMobile());
		enterprise.setEnAdminuu(detail.getAdminUU() == null ? detail.getAdmin().getUserUU() : detail.getAdminUU());
		enterprise.setEnArea(detail.getArea());
		enterprise.setEnBussinessCode(detail.getBusinessCode());
		enterprise.setEnCorporation(detail.getCorporation());
		if(null != detail.getRegisterDate()) {
			enterprise.setEnDate(new Date(detail.getRegisterDate()));
		} else {
			enterprise.setEnDate(new Date());
		}
		enterprise.setEnName(detail.getSpaceName());
		enterprise.setLogUrl(detail.getLogoImage());
		enterprise.setProfession(detail.getProfession());
		enterprise.setTags(detail.getTags());
		enterprise.setInviteSource(detail.getSource());
		enterprise.setInviteTime(detail.getInvitationTime());
		enterprise.setInviteUserUU(detail.getInviteUserUU());
		enterprise.setInviteUU(detail.getInviteSpaceUU());
		enterprise = enterpriseDao.save(enterprise);

		// 把管理员添加进企业
		User user = userDao.findOne(enterprise.getEnAdminuu());
		if (user == null) {
			user = new User(detail.getAdmin());
		}
		user.addEnterprise(enterprise);
		// 将用户设置为管理员，只对用户的当前企业的角色进行修改
		Set<Role> existRoles = new HashSet<Role>(); // 新用户注册企业时为空
		if (!CollectionUtils.isEmpty(user.getRoles())) { // 老用户注册新企业
			existRoles = user.getRoles();
		}
		// 设置为本企业管理员
		List<Role> adminList = roleDao.findByEnUUAndDesc(enterprise.getUu(), "管理员");
		if (!CollectionUtils.isEmpty(adminList)) {
			existRoles.add(adminList.get(0));
			user.setRoles(existRoles);
		}
		userDao.save(user);

		if (isNew) {
			final Long enUU = enterprise.getUu();
			new Thread() {
				@Override
				public void run() {
					enterpriseDao.callInitProcedure(enUU);
					logger.log("企业信息", "企业初始化", "新注册企业初始化资料", enUU);
				}
			}.start();
		}
		return enterprise;
	}

	private Enterprise getEnterprise(UserSpaceView userSpace) {
		Enterprise enterprise = null;
		if (userSpace.getSpaceUU() != null) {
			enterprise = enterpriseDao.findEnterpriseByUu(userSpace.getSpaceUU());
		} else if (userSpace.getBusinessCode() != null) {
			enterprise = enterpriseDao.findEnterpriseByEnBussinessCode(userSpace.getBusinessCode());
		}
		return enterprise;
	}

	@Override
	public void delete(UserSpaceView userSpace) {
		Enterprise enterprise = getEnterprise(userSpace);
		if (enterprise != null) {
			List<User> users = userDao.findByEnUU(enterprise.getUu());
			if (CollectionUtils.isEmpty(users)) {
				enterpriseDao.delete(enterprise);
			}
		}
	}

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

}
