package com.jeesms.manager.system;

import com.jeesms.annotation.Permission;
import com.jeesms.common.Constants;
import com.jeesms.dao.generic.GenericDao;
import com.jeesms.dao.system.DepartmentDao;
import com.jeesms.entity.system.Department;
import com.jeesms.manager.generic.GenericManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 部门Manager
 *
 * @author ASHNL
 * @time 2014-07-27 17:01:04
 */
@Service("departmentManager")
public class DepartmentManager extends GenericManager<Department> {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    @Qualifier(value = "departmentDao")
    private DepartmentDao departmentDao;

    @Override
    @Permission(code = "department-edit")
    @CacheEvict(value = Constants.DEPARTMENT_CACHE, allEntries = true)
    public synchronized void saveOrUpdate(Department department) {
        departmentDao.evict(department);
        Department compDepartment = departmentDao.findUnique("code", department.getCode());
        if (compDepartment != null && !compDepartment.getId().equals(department.getId())) {
            throw new IllegalArgumentException("部门编号[" + department.getCode() + "]，已存在，请更换");
        }
        //合并对象
        super.saveOrUpdate(departmentDao.merge(department));
        logger.debug("saveOrUpdate clear [{}].", Constants.DEPARTMENT_CACHE);
    }

    @Override
    @Permission(code = "department-delete")
    @CacheEvict(value = Constants.DEPARTMENT_CACHE, allEntries = true)
    public void deleteByIds(String ids) {
        super.deleteByIds(ids);
        logger.debug("deleteByIds clear [{}].", Constants.DEPARTMENT_CACHE);
    }

    @Override
    public GenericDao getBaseDao() {
        return departmentDao;
    }

    @Cacheable(value = Constants.DEPARTMENT_CACHE, key = "#parentId")
    public List<Department> queryDepartmentsByParentId(String parentId) {
        return departmentDao.queryDepartmentsByParentId(parentId);
    }
}
