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

import com.uas.platform.b2b.dao.CommonDao;
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.Role;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.service.RoleService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.exception.IllegalOperatorException;
import com.uas.platform.core.model.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private UserDao userDao;

	@Autowired
    private CommonDao commonDao;

	@Override
	public List<Role> findAll() {
		return findByEnterprise(SystemSession.getUser().getEnterprise().getUu());
	}

	@Override
	public List<Role> findByEnterprise(long enUU) {
		List<Role> roles = roleDao.findByEnUU(enUU);
		if (CollectionUtils.isEmpty(roles)) {
			// 角色为空，说明资料未初始化或初始化失败，需重新init
			enterpriseDao.callInitProcedure(enUU);
			roles = roleDao.findByEnUU(enUU);
		}
		return roles;
	}

	@Override
	public Role save(Role role) {
		Assert.notNull(role.getDesc());
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		// 角色描述不能重复
		List<Role> roles = roleDao.findByEnUUAndDesc(enUU, role.getDesc());
		if (roles.size() > 0 && !roles.get(0).equals(role)) {
            throw new IllegalOperatorException("角色描述不能重复");
        }
		if (role.getName() == null) {
			// 自定义角色
			role.setName("ROLE_" + System.currentTimeMillis());
			role.setEnUU(enUU);
			role.setIsdefault(Constant.NO);
			role.setIssys(Constant.NO);
			role.setIndex(roleDao.findIndexByEnUU(enUU) + 1);
		}
		return roleDao.save(role);
	}

	@Override
	public Role findById(long id) {
		return roleDao.findOne(id);
	}

	@Override
	public void delete(Role role) {
		if (role != null && role.getId() != null) {
			List<User> users = userDao.findByRole(role.getId());
			if (!CollectionUtils.isEmpty(users)) {
				for (User user : users) {
					user.getRoles().remove(role);
				}
				userDao.save(users);
			}
			roleDao.delete(role);
		}
	}

	@Override
	public void delete(long id) {
		delete(findById(id));
	}

    @Override
    public List<Role> findByEnUUAndUserUU(Long enUU, Long userUU) {
	    String sql = "select s.role_enuu enUU,s.role_desc as `desc`,s.role_name name,s.role_id id from sec$roles s left join sec$userrole r " +
                "on s.role_id = r.role_id where s.role_enuu = " + enUU +" and r.user_uu = " + userUU;
	    List<Role> roles = commonDao.query(sql, Role.class);
        return roles;
    }

}
