package com.goafanti.permission.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goafanti.common.bo.Error;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.OrderExamineMapper;
import com.goafanti.common.dao.OrganizationContactBookMapper;
import com.goafanti.common.dao.PatentNewMapper;
import com.goafanti.common.dao.RoleMapper;
import com.goafanti.common.dao.RolePermissionMapper;
import com.goafanti.common.dao.RoleResourcesMapper;
import com.goafanti.common.dao.TOrderMidMapper;
import com.goafanti.common.dao.TOrderNewMapper;
import com.goafanti.common.dao.TOrderTaskMapper;
import com.goafanti.common.dao.TTaskLogMapper;
import com.goafanti.common.dao.UserBusinessMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.dao.UserRoleMapper;
import com.goafanti.common.enums.roleResources;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Role;
import com.goafanti.common.model.RolePermission;
import com.goafanti.common.model.RoleResources;
import com.goafanti.common.model.UserRole;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.permission.bo.RoleBo;
import com.goafanti.permission.bo.RolePermissionBo;
import com.goafanti.permission.service.NewRoleService;
@Service
public class NewRoleServiceImpl extends BaseMybatisDao<RoleMapper> implements NewRoleService {
	@Autowired
	private RoleMapper				roleMapper;
	@Autowired
	private UserMapper				userMapper;
	@Autowired
	private UserRoleMapper			userRoleMapper;
	@Autowired
	private RolePermissionMapper	rolePermissionMapper;
	@Autowired
	private RoleResourcesMapper		roleResourcesMapper;
	@Autowired
	private UserBusinessMapper		userBusinessMapper;
	@Autowired
	private PatentNewMapper			patentNewMapper;
	@Autowired
	private OrganizationContactBookMapper	organizationContactBookMapper;
	@Autowired
	private TOrderTaskMapper	tOrderTaskMapper;
	@Autowired
	private TOrderNewMapper	tOrderNewMapper;
	@Autowired
	private TTaskLogMapper	tTaskLogMapper;
	@Autowired
	private TOrderMidMapper	tOrderMidMapper;
	@Autowired
	private OrderExamineMapper	orderExamineMapper;
	@Override
	public Pagination<RoleBo> findRoles(RoleBo role, Integer pageNo, Integer pageSize) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String,Object> params =disposeParams(role);
		@SuppressWarnings("unchecked")
		Pagination<RoleBo> p=(Pagination<RoleBo>)findPage("selectRoleList","selectRoleCount",params,pageNo,pageSize);		
		@SuppressWarnings("unchecked")
		List<RoleBo> list=(List<RoleBo>) p.getList();
		for(RoleBo i:list){
			if(i.getCreateTime()!=null){
				i.setCreateTimez(sdf.format(i.getCreateTime()));
			}
			
		}
		return p;
	}
	private Map<String,Object> disposeParams(RoleBo role){
		Map<String,Object> params = new HashMap<String, Object>();			
		if(StringUtils.isNotBlank(role.getRoleName())) params.put("roleName", role.getRoleName());		
		return params;
		
	}
	
	@Override
	public Set<String> findRoleByUserId(String userId) {
		return roleMapper.findRoleByUserId(userId);
	}

	

	@Override
	public int insert(List<Role> records) {
		return roleMapper.insertBatch(records);
	}

	@Override
	public int deleteByPrimaryKeys(List<String> records) {
		rolePermissionMapper.deleteByRoleId(records);
		userRoleMapper.deleteByRoleId(records);
		List<String> data= userRoleMapper.findUserIdByRoleIds(records);
		TokenManager.clearUserAuthByUserId(data.toArray(new String[]{}));
		return roleMapper.deleteByPrimaryKeys(records);
	}


	@Override
	public int bindPermission(String rid, String pid) {
		TokenManager.clearUserAuthByUserId((String[]) userRoleMapper.findUserIdByRoleId(rid).toArray());
		return rolePermissionMapper.insert(new RolePermission(rid, pid));
	}

	@Override
	public int bindUser(String rid, String uid) {
		TokenManager.clearUserAuthByUserId(new String[] { uid });
		return userRoleMapper.insert(new UserRole(uid, rid));
	}

	@Override
	public int unbindPermission(String roleId, String permissionId) {
		Map<String, Object> params = new HashMap<>();
		params.put("rid", roleId);
		params.put("pid", permissionId);
		TokenManager.clearUserAuthByUserId((String[]) userRoleMapper.findUserIdByRoleId(roleId).toArray());
		return rolePermissionMapper.deleteByPrimaryKey(params);
	}

	@Override
	public int unbindUser(String roleId, String userId) {
		Map<String, Object> params = new HashMap<>();
		params.put("rid", roleId);
		params.put("uid", userId);
		TokenManager.clearUserAuthByUserId(new String[] { userId });
		return userRoleMapper.deleteByUserRole(params);
	}

	@Override
	public int insert(Role record, List<String> permissions) {
		Date now = new Date();
		if (record.getId() != null) {
			List<RolePermission> rps = new ArrayList<>();
			rolePermissionMapper.deleteByRid(record.getId());
			for (String pid : permissions) {
				rps.add(new RolePermission(record.getId(), pid));
			}
			if (!rps.isEmpty()) {
				rolePermissionMapper.insertBatch(rps);
			}
			List<String> ids = userRoleMapper.findUserIdByRoleId(record.getId());
			TokenManager.clearUserAuthByUserId(ids.toArray(new String[ids.size()]));
		}
		record.getId();
		record.setCreater("管理员");		
		record.setCreateTime(now);
		return roleMapper.insert(record);
	}
	@Override
	public List<RolePermissionBo> selectRolePList(String id) {
		List<RolePermissionBo> list=roleMapper.selectRolePList(id);
		return list;
	}
	@Override
	public int addResources(String rid, String resources) {
		List<String> list = Arrays.asList(resources.split(","));
		RoleResources rr=new RoleResources();
		if (roleResourcesMapper.checkRid(rid)>0) {
			roleResourcesMapper.deleteResources(rid);
		}
		for (String s : list) {
			rr.setId(UUID.randomUUID().toString());
			rr.setRoleId(rid);
			rr.setCreateTime(new Date());
			try {
			    rr.setResources(Integer.parseInt(s));
			} catch (NumberFormatException e) {
			    e.printStackTrace();
			}
			roleResourcesMapper.insert(rr);
		}
		return 1;
	}
	
	@Override
	public int updatedimission(String aid, String transferId) {
		List<Integer> list=roleResourcesMapper.selectAdminRoleResources(aid);
		if (list.size()<1||list.get(0)==null) {
			throw new BusinessException(new Error("","用户角色资源不存在"));
		}
		for (Integer s : list) {
			if (s==roleResources.YXKH.getCode()) {
				roleResourcesMapper.updateLockRelease("0",aid,transferId);//将用户锁转给指定人
				userBusinessMapper.updateDimissionTransfer(aid,transferId);
				organizationContactBookMapper.updateDimissionTransfer(aid,transferId);
				//所有客户转交给接受者
				userMapper.updateDimissionTransfer(aid,transferId);
			}
			if (s==roleResources.QDYW.getCode()) {
				tOrderNewMapper.updateSalesmanId(aid, transferId);
				tOrderMidMapper.updateSalesmanId(aid, transferId);
				patentNewMapper.updateAdmin(aid,transferId);
				roleResourcesMapper.updateLockRelease("1",aid,transferId);//将业务锁转给指定人
			}
			if (s==roleResources.XMRW.getCode()) {
//				contractTaskLogMapper.updateDimissionTransfer(aid,transferId);
				//获取被转角色判断修改对应任务角色
				Integer type=-1;
				if (TokenManager.hasRole(AFTConstants.TECH)) type=0;
				else if (TokenManager.hasRole(AFTConstants.TECH_MANAGER))type=1;
				if (type!=-1) {
					tOrderTaskMapper.updateDimissionTransfer(aid,transferId,type);
					tTaskLogMapper.updateDimissionTransfer(aid,transferId);
					orderExamineMapper.updateDimissionTransfer(aid,transferId);
				}
			}
			if (s!=roleResources.QDYW.getCode()) {
				roleResourcesMapper.updateDimissionTransfer(s,aid,transferId);
			}
		}
		return 1;
	}
	@Override
	public List<RoleResources> ResourcesDetail(String rid) {
		return roleResourcesMapper.selectByRid(rid);
	}
	
}
