package net.wicp.tams.duckula.ops.pages.cas;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.util.TextStreamResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import net.wicp.tams.app.duckula.controller.bean.models.SysOrg;
import net.wicp.tams.app.duckula.controller.bean.models.SysRole;
import net.wicp.tams.app.duckula.controller.bean.models.SysRoleAssignExample;
import net.wicp.tams.app.duckula.controller.bean.models.SysRoleRes;
import net.wicp.tams.app.duckula.controller.bean.models.SysRoleResExample;
import net.wicp.tams.app.duckula.controller.bean.models.SysRoleResExample.Criteria;
import net.wicp.tams.app.duckula.controller.dao.SysRoleAssignMapper;
import net.wicp.tams.app.duckula.controller.dao.SysRoleMapper;
import net.wicp.tams.app.duckula.controller.dao.SysRoleResMapper;
import net.wicp.tams.app.duckula.controller.service.cas.IMenuService;
import net.wicp.tams.app.duckula.controller.service.cas.IStaffService;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.apiext.json.EasyUiAssist;
import net.wicp.tams.common.apiext.json.easyuibean.EasyUINode;
import net.wicp.tams.common.constant.dic.YesOrNo;
import net.wicp.tams.duckula.ops.beans.SessionBean;
import net.wicp.tams.duckula.ops.pages.ParentPageBean;

/****
 * 资源分派页面
 *
 * @author Administrator
 *
 */
@Import(stack = "easyuistack")
public class ResAllot extends ParentPageBean<SysOrg> {
	@Inject
	private IMenuService menuService;

	@Inject
	private IStaffService staffService;

	@Property(write = false)
	private List<SysRole> roles;
	@Property
	private SysRole role;

	@Inject
	private SysRoleMapper sysRoleMapper;

	@Inject
	private SysRoleResMapper sysRoleResMapper;
	@Inject
	private SysRoleAssignMapper sysRoleAssignMapper;

	@SessionState
	@Property(write = false)
	private SessionBean sessionBean;
	
	

	public String getTreeData() {
		List<EasyUINode> roots = menuService.findAllModuleMenu(I18NConvert, false, true, sessionBean.isSuperUser());
		String retstr = EasyUiAssist.getTreeFromList(roots);
		return retstr;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONArray onQuerySelResForRole(long roleid) {
		JSONArray retobj = new JSONArray();
		Map newMap = CollectionUtil.newMap("role_id", roleid);
		if (sessionBean != null && sessionBean.isSuperUser()) {// 超级用户会跳过加tenant_id
			Long tenantId = sessionBean.getTenantId();
			newMap.put("tenant_id", tenantId);
		}
		List<SysRoleRes> roleRess = sysRoleResMapper.selectByMap(newMap);
		if (CollectionUtils.isNotEmpty(roleRess)) {
			for (SysRoleRes roleRes : roleRess) {
				retobj.add(roleRes.getResId());
			}
		}
		return retobj;
	}

	@SuppressWarnings("rawtypes")
	public TextStreamResponse onSaveMenuForRole() {
		final String roleIdStr = request.getParameter("roleId");
		long roleid = Long.parseLong(roleIdStr);
		String nodeIds = request.getParameter("nodeIds");

		QueryWrapper<SysRoleRes> queryWrapper = new QueryWrapper<SysRoleRes>();
		queryWrapper.eq("role_id", roleid);
		if (sessionBean != null && sessionBean.isSuperUser()) {// 超级用户会跳过加tenant_id
			Long tenantId = sessionBean.getTenantId();
			queryWrapper.eq("tenant_id", tenantId);
		}
		List<SysRoleRes> oldResList = sysRoleResMapper.selectList(queryWrapper);// 旧的权限

		// 添加新的资源对象
		if (StringUtils.isNotBlank(nodeIds)) {
			String[] resAry = nodeIds.split(",");
			final List<String> newResIdList = Arrays.asList(resAry);
			List<Long> olsResIdList = (List<Long>) CollectionUtil.getColFromObj(oldResList, "resId");
			// 需要增加的id，string类型
			Collection addlist = CollectionUtils.select(newResIdList, new Predicate() {

				@Override
				public boolean evaluate(Object arg0) {
					return !olsResIdList.contains(Long.parseLong(String.valueOf(arg0)));
				}
			});
			SysRole role = sysRoleMapper.selectById(roleid);
			for (Object resIdStr : addlist) {
				long resid = Long.parseLong(String.valueOf(resIdStr));
				SysRoleRes insertObj = new SysRoleRes();
				insertObj.setAuthCode(1l);
				insertObj.setRoleId(role.getId());
				insertObj.setResId(resid);
				sysRoleResMapper.insert(insertObj);
			}

			// 删除的资源
			Set<Long> superResId = menuService.findSuperResId();
			@SuppressWarnings("unchecked")
			List<Long> delList = (List<Long>) CollectionUtils.select(olsResIdList, new Predicate() {
				@Override
				public boolean evaluate(Object object) {
					return !newResIdList.contains(String.valueOf(object)) && (sessionBean.isSuperUser()
							|| (!sessionBean.isSuperUser() && !superResId.contains(object)));// 不是超级用户,但菜单也不是超级用户才能操作的资源
				}
			});
			if (CollectionUtils.isNotEmpty(delList)) {
				SysRoleResExample example = new SysRoleResExample();
				Criteria criteria = example.createCriteria();
				criteria.andRoleIdEqualTo(role.getId());
				criteria.andResIdIn(delList);
				sysRoleResMapper.deleteByExample(example);
			}

			// 保存到Redis缓存
//			Jedis jedis = RedisClient.getConnectionDefault();
//			String queryStr = "select resValue from ca_resource where resType=3 and resValue<>''  and  id in(:resIds)";
//			if (CollectionUtils.isNotEmpty(newResList)) {// 新增和修改
//				Query queryres = hbService.getQuerySQL(queryStr);
//				queryres.setParameterList("resIds", newResList);
//				List<String> adds = queryres.list();
//				for (String add : adds) {
//					int lIndex = add.indexOf("?");
//					String key = String.format(RedisKey.resAuth, lIndex == -1 ? add : add.substring(0, lIndex));
//					List<String> roleIds = jedis.lrange(key, 0, -1);
//					if (!roleIds.contains(roleIdStr)) {
//						jedis.lpush(key, roleIdStr);
//					}
//				}
//			}
			// 删除
//			if (CollectionUtils.isNotEmpty(delList)) {
//				Query queryres = hbService.getQuerySQL(queryStr);
//				queryres.setParameterList("resIds", delList);
//				List<String> dels = queryres.list();
//				for (String del : dels) {
//					int lIndex = del.indexOf("?");
//					String key = String.format(RedisKey.resAuth, lIndex == -1 ? del : del.substring(0, lIndex));
//					List<String> roleIds = jedis.lrange(key, 0, -1);
//					CollectionUtils.filter(roleIds, new Predicate() {
//						@Override
//						public boolean evaluate(Object object) {
//							return !roleIdStr.equals(object);
//						}
//					});
//					//jedis.del(key);
////					if (roleIds.size() > 0) {
////						jedis.lpush(key, roleIds.toArray(new String[roleIds.size()]));
////					}
//				}
//			}
//			RedisClient.returnResource(jedis);

		}
		return retSuccInfo();
	}

	public TextStreamResponse onSaveRole() {
		String idstr = request.getParameter("id");
		String roleName = request.getParameter("name");
		String isValid = request.getParameter("status");
		String remark = request.getParameter("remark");
		String isSuper=request.getParameter("isSuper");
		SysRole caRole = new SysRole();
		if (StringUtils.isNotEmpty(idstr)) {
			caRole.setId(Long.parseLong(idstr));
		}
		caRole.setName(roleName);
		caRole.setStatus(isValid);
		caRole.setRemark(remark);
		caRole.setIsSuper(isSuper);
		if (caRole.getId() == null) {
			caRole.setIsSuper(YesOrNo.no.name());
			sysRoleMapper.insert(caRole);
		} else {
			sysRoleMapper.updateById(caRole);
		}
		return retSuccInfo();
	}

	public TextStreamResponse onDelRole() {
		String idstr = request.getParameter("id");
		long roleId = Long.parseLong(idstr);
		sysRoleMapper.deleteById(roleId);
		// 删除角色对应的资源
		SysRoleResExample example = new SysRoleResExample();
		Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(roleId);
		sysRoleResMapper.deleteByExample(example);
		// 删除角色对应的权限
		SysRoleAssignExample example2 = new SysRoleAssignExample();
		SysRoleAssignExample.Criteria criteria2 = example2.createCriteria();
		criteria2.andRoleIdEqualTo(roleId);
		sysRoleAssignMapper.deleteByExample(example2);
		return retSuccInfo();
	}

	@SetupRender
	void init() {
		roles = staffService.findValidRole(sessionBean.isSuperUser());
		// 找到可以配置资源的角色,开发者角色拥有所有页面，不用配置
//		final int devrole = Integer.parseInt(SpringInit.conf.getProperty("role.dev"));
//		CollectionUtils.filter(roles, new Predicate() {
//			@Override
//			public boolean evaluate(Object object) {
//				SysRole temp = (SysRole) object;
//				return devrole != temp.getId();
//			}
//		});
	}

	@Override
	public void doSave(SysOrg t, boolean isInsert) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doDel(String id) {
		// TODO Auto-generated method stub

	}

	@Override
	public BaseMapper<SysOrg> getBaseMapper() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void packageQuery(SysOrg t, QueryWrapper<SysOrg> queryWrapper) {
		// TODO Auto-generated method stub

	}
}
