/**
 * Copyright &copy; 2013-2017 <a href="http://www.rhcncpa.com/">瑞华会计师事务所</a> All rights reserved.
 */
package com.jeeplus.modules.sys.service;

import com.jeeplus.common.service.BaseService;
import com.jeeplus.common.service.TreeService;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.dao.CompanyDao;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.dao.UserofficeDao;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.workcontractinfo.dao.WorkContractInfoDao;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

/**
 * 机构Service
 * @author jeeplus
 * @version 2014-05-16
 */
@Service
@Transactional(readOnly = true)
public class OfficeService extends TreeService<OfficeDao, Office> {

	@Autowired
	private UserDao userDao;
	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private UserofficeDao userOfficeDao;
	@Autowired
	private WorkContractInfoDao contractInfoDao;
	@Autowired
    private RoleDao roleDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    @Lazy
    private SystemService systemService;
	
	public List<Office> findAll(){
		return UserUtils.getOfficeList();
	}

	//微信查询
	public List<Office> findByNameWx(String officeName){
		return officeDao.findByNameWx(officeName);
	}
	public List<Office> findList(Boolean isAll){
		if (isAll != null && isAll){
			return UserUtils.getOfficeAllList();
//			return UserUtils.getOfficeList();
		}else{
			return UserUtils.getOfficeList();
		}
	}
	public List<Office> findListIndex(Office office){
		User user = UserUtils.getUser();
		if(user.isAdmin()){
			return UserUtils.getOfficeList();
		}
		List<Role> roleList =  roleDao.getManagerRoleList(user.getId(),UserUtils.getSelectCompany().getId());
		if(roleList!=null&&roleList.size()>0){
			StringBuilder stringBuilder=new StringBuilder();
			for(Role role:roleList){
				if(stringBuilder==null||stringBuilder.length()==0){
					stringBuilder.append(" and a.id in ( SELECT id FROM sys_office s where s.id='"+role.getOffice().getId()+"' or s.parent_ids  like concat('%','"+role.getOffice().getId()+"','%')) ");
				}else{
					stringBuilder.append(" or a.id in ( SELECT id FROM sys_office s where s.id='"+role.getOffice().getId()+"' or s.parent_ids  like concat('%','"+role.getOffice().getId()+"','%')) ");
				}
			}
			office.getSqlMap().put("dsf",stringBuilder.toString());
			List<Office> list=officeDao.findMangeList(office);
			return  list;
		}else{
			office.getSqlMap().put("dsf"," and a.id in ( SELECT id FROM sys_office s where s.id='"+UserUtils.getSelectBranchOffice()+"' or s.parent_ids  like concat('%','"+UserUtils.getSelectBranchOffice()+"','%')) ");
			List<Office> list=officeDao.findMangeList(office);
			/*office.getSqlMap().put("dsf", BaseService.dataScopeFilterOR(user, "a", "","", MenuStatusEnum.OFFICE.getValue()));
			office.setUseable("");
			Office company = UserUtils.getSelectCompany();
			office.setIsSon(company.getIsSon());
			List<Office> list=officeDao.findList(office);*/
			return list;
		}
	}
	public List<Office> findByUserId(String userId){
		return officeDao.findByUserId(userId);
	}
	public List<Office> findByCompany(Office office){
		Office company = UserUtils.getSelectCompany();
		office.setIsSon(company.getIsSon());
		office.setId(company.getId());
		return officeDao.findByCompany(office);
	}
	public List<Office> findByCompanyDSF(Office office){
		Office office1 = UserUtils.getSelectOffice();
		office.setIsSon(office1.getIsSon());
		if(StringUtils.isNotBlank(office1.getBranchOffice())) {
			office.setId(office1.getBranchOffice());
		}else {
			office.setId(UserUtils.getSelectCompany().getId());
		}
		return officeDao.findByCompany(office);
	}

	@Transactional(readOnly = true)
	public List<Office> findByParentIdsLike(Office office){
		office.setId(office.getParentIds());
		office.setParentIds(office.getParentIds()+"%");
		Office company = UserUtils.getSelectCompany();
		office.setIsSon(company.getIsSon());
		List<Office> offices = dao.findByParentIdsLike(office);
		return offices;
	}
	@Transactional(readOnly = true)
	public List<Office> findByParentId(Office office){
		office.setId(office.getParent().getId());
		Office company = UserUtils.getSelectCompany();
		office.setIsSon(company.getIsSon());
		return dao.findByParent(office);
	}
	@Transactional(readOnly = true)
	public List<Office> findByParentIdsCompany(Office company,Office office){
		Office o = new Office();
		o.setId(company.getId());
		o.setParentIds(company.getId()+"%");
		o.setBranchOffice(office.getBranchOffice());
		office.setIsSon(company.getIsSon());
		return dao.findByParentIdsCompany(o);
	}
	@Transactional(readOnly = true)
	public List<Office> findListt(Office office){
		office.setParentIds(office.getParentIds());
		Office company = UserUtils.getSelectCompany();
		office.setIsSon(company.getIsSon());
		List<Office> list = officeDao.findByParentIdsLikee(office);
		return list;
	}
	
	@Transactional(readOnly = true)
     public List<Office> findByGroupId(String groupId){
        return dao.findByGroupId(groupId);
    }

	@Transactional(readOnly = true)
     public List<Office> findByType(Office office){
        return dao.findByType(office);
    }

    @Transactional(readOnly = true)
    public Office getByCode(String code){
        return dao.getByCode(code);
    }
	
	
	@Transactional(readOnly = false)
	public void save(Office office) {
		super.save(office);
		if(office.getType().equals("3")){
			office.setBranchOffice(office.getId());
			dao.saveBranchOffice(office);
		}
		UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
	}
	@Transactional(readOnly = false)
	public void updateUseable(Office office) {
		dao.updateUseable(office);
		UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
	}
	@Transactional(readOnly = false)
	public void saveBranchOffice(Office office) {
		dao.saveBranchOffice(office);
		UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
	}

	@Transactional(readOnly = false)
	public void delete(Office office) {
		super.delete(office);
		UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
	}

    public List<Office> getAllDepts(String id) {
    	return officeDao.getAllDepts(id);
    }

    //判断是否有子公司
	public List<Office> getSon(Company company){
		Office office = this.get(company.getCompanyId());
		String oParentId = office.getId();
		Office office1 = new Office();
		office1.setType("1");
		office1.setParent(new Office(oParentId));
		List<Office> offices = officeDao.getInfo(office1);
		return offices;
	}

    public List<Office> findByBranchOffice() {
	    Office select = new Office();
        Office branchOffice = UserUtils.getUser().getBranchOffice();
        Office selectCompany = UserUtils.getSelectCompany();
        if(branchOffice!=null&&!branchOffice.equals(selectCompany)){
	        select.setBranchOffice(branchOffice.getId());
        }
        select.setParentIds(selectCompany.getId());
		select.setId(selectCompany.getId());
        return officeDao.findByParentIdsCompany(select);
    }
    public List<Office> findByBranchOfficeInfo(String branchOffice) {
	    Office select = new Office();
		Office selectCompany = UserUtils.getSelectCompany();
        Office branch = officeDao.get(branchOffice);
		if ("3".equals(branch.getType())){
            select.setBranchOffice(branchOffice);
        }
		select.setParentIds(selectCompany.getId());
		select.setId(selectCompany.getId());
        return officeDao.findByParentIdsCompany(select);
    }
	public List<Office> findByCompanyTemplate(Office office){
		office.setId(UserUtils.getSelectCompany().getId());
		return officeDao.findByCompanyTemplate(office);
	}

	@Transactional(readOnly = true)
	public List<Office> treeDataAllOffice(Office office){
		return dao.treeDataAllOffice(office);
	}

    public boolean validate(String id) {
	    if (userOfficeDao.countByOffice(id)>0){
	        return true;
        }
        return contractInfoDao.countByOffice(id)>0;
    }

    @Transactional(readOnly = false)
    public void logicDelete(Office office) {
	    //禁用机构及子机构
        officeDao.logicDelete(office);
        //禁用岗位
        roleDao.deleteByOffice(office);
        //删除岗位关联的用户缓存
        List<User> users =  userDao.findUserByOfficeRole(office);
        //查询当前机构所属公司
        String comId = "";
        boolean comFlag = false;
        if("0,".equals(office.getParentIds())){
            comId = office.getId();
            comFlag = true;
        }else {
            comId = office.getParentIds().split(",")[1];
        }
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getResource();
            if (users!=null && users.size()!=0){
                for (User user :users){
                    if(user!=null) {
                        jedis.del("menu1_" + comId + "_" + user.getId());
                        jedis.del("menu2_" + comId + "_" + user.getId());
                    }
                }
            }
        }catch (Exception e){
            logger.error("清理用户菜单数据权限缓存异常：", e);
        }finally {
            JedisUtils.returnResource(jedis);
        }
        if(comFlag) {
            User user = new User();
            user.setCompany(office);
            List<User> list = userDao.findList(user);
            systemService.removeSession(list);
            //如果是企业，删除企业信息
            companyDao.logicDelete(office);
            //删除user_office记录
            userOfficeDao.deleteByCompany(office.getId());
            userDao.updateUserCompanyId(office.getId());
        }
    }
    //获取最大值加1
    public String findWxOfficeIdService(){
		Integer integer = 1;
		String wxOfficeId = officeDao.findWxOfficeId();
		if (null!= wxOfficeId && !"".equals(wxOfficeId)){
			integer = new Integer(wxOfficeId)+1;
		}
		return String.valueOf(integer);
	}
	//分局office的id获取父级id
	public Integer findWxOfficeIdByParentIdService(String id){
		Integer integer = 1;
		String wxOfficeIdByParentId = officeDao.findWxOfficeIdByParentId(id);
		if (null!=wxOfficeIdByParentId && !"".equals(wxOfficeIdByParentId)){
			integer = new Integer(wxOfficeIdByParentId);
		}
		return integer;
	}

	public Integer findWxOfficeIdByIdSerice(String id){
		Integer integer = 1;
		String wxOfficeIdById = officeDao.findWxOfficeIdById(id);
		if (null!=wxOfficeIdById && !"".equals(wxOfficeIdById)){
			integer = new Integer(wxOfficeIdById);
		}
		return integer;
	}
}
