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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;

import net.wicp.tams.app.duckula.controller.bean.constant.UnitType;
import net.wicp.tams.app.duckula.controller.bean.models.SysRole;
import net.wicp.tams.app.duckula.controller.bean.models.SysRoleAssign;
import net.wicp.tams.app.duckula.controller.bean.models.SysRoleAssignExample;
import net.wicp.tams.app.duckula.controller.bean.models.SysRoleAssignExample.Criteria;
import net.wicp.tams.app.duckula.controller.bean.models.SysUser;
import net.wicp.tams.app.duckula.controller.dao.SysRoleAssignMapper;
import net.wicp.tams.app.duckula.controller.dao.SysUserMapper;
import net.wicp.tams.app.duckula.controller.service.cas.IOrgService;
import net.wicp.tams.app.duckula.controller.service.cas.IStaffService;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.callback.IConvertValue;
import net.wicp.tams.component.SymbolConstantsCus;
import net.wicp.tams.duckula.ops.beans.SessionBean;
import net.wicp.tams.duckula.ops.pages.ParentPage;

public class RoleAssign extends ParentPage {

	@Inject
	private IStaffService staffService;
	@Inject
	private IOrgService orgService;

	@Property
	private List<SysRole> allRoles;
	@Property
	private List<String> selRoleIds;
	@SuppressWarnings("rawtypes")
	@Property
	private Map<String, IConvertValue> convmap;// 转换器

	@Persist(PersistenceConstants.CLIENT)
	private String unitType;// 会通过参数传过来
	@Persist(PersistenceConstants.CLIENT)
	private long objId;

	@Inject
	private SysRoleAssignMapper sysRoleAssignMapper;

	@Inject
	private SysUserMapper sysUserMapper;

	/***
	 * 保存选择的结果
	 * 
	 * @param selIds
	 * @return
	 */
	@OnEvent(value = SymbolConstantsCus.EVENT_SAVE)
	private Result sava(JSONArray selIds) {
		if (selIds == null) {
			return Result.getError("需要传入要保存的对象");
		}

		List<SysRole> selRoles = null;
		if ("STAFF".equals(unitType)) {
			selRoles = staffService.findRolesByStaff(objId);
		} else {
			selRoles = staffService.findRolesByUnit(UnitType.findByName(unitType), objId, false);
		}
		// 去除开发者
		CollectionUtils.filter(selRoles, new Predicate() {
			@Override
			public boolean evaluate(Object object) {
				SysRole caRole = (SysRole) object;
				return caRole.getId() != 0;
			}
		});

		long[] oriIds = new long[selRoles.size()];
		for (int i = 0; i < oriIds.length; i++) {
			oriIds[i] = selRoles.get(i).getId();
		}
		long[] saveIds = new long[selIds.size()];
		for (int i = 0; i < selIds.size(); i++) {
			saveIds[i] = Long.parseLong(selIds.getString(i));
		}
		List<Long> addList = new ArrayList<Long>();// 新增
		for (int i = 0; i < saveIds.length; i++) {
			if (!ArrayUtils.contains(oriIds, saveIds[i])) {
				addList.add(saveIds[i]);
			}
		}
		if (CollectionUtils.isNotEmpty(addList)) {
			for (Long roleid : addList) {
				SysRoleAssign saveobj = new SysRoleAssign();
				saveobj.setAssignType(unitType);
				saveobj.setAssignValue(objId);
				saveobj.setRoleId(roleid);
				sysRoleAssignMapper.insert(saveobj);
			}

		}
		List<Long> delList = new ArrayList<Long>();// 删除
		for (int i = 0; i < oriIds.length; i++) {
			if (!ArrayUtils.contains(saveIds, oriIds[i])) {
				delList.add(oriIds[i]);
			}
		}

		if (CollectionUtils.isNotEmpty(delList)) {
			if ("STAFF".equals(unitType)) {
				List<String> saveMinu = new ArrayList<String>();
				for (Long delId : delList) {
					SysRoleAssignExample example = new SysRoleAssignExample();
					Criteria criteria = example.createCriteria();
					criteria.andAssignTypeEqualTo(unitType);
					criteria.andAssignValueEqualTo(objId);
					criteria.andRoleIdEqualTo(delId);

					int delint = sysRoleAssignMapper.deleteByExample(example);
					if (delint > 0) {
						saveMinu.add(String.valueOf(delId));
					}
				}

				// 保存排除的ids,防止这些角色会从组织、职位等继承
				String saveValue = CollectionUtil.listJoin(saveMinu, ",");
				SysUser uppo = new SysUser();
				uppo.setMinusRole(saveValue);
				uppo.setId(objId);
				sysUserMapper.updateById(uppo);
			} else {
				SysRoleAssignExample example = new SysRoleAssignExample();
				Criteria criteria = example.createCriteria();
				criteria.andAssignTypeEqualTo(unitType);
				criteria.andAssignValueEqualTo(objId);
				criteria.andRoleIdIn(delList);
				sysRoleAssignMapper.deleteByExample(example);
			}
		}
		return Result.getSuc();
	}
	
	@SessionState
	private SessionBean sessionBean;

	/****
	 * 需要分派页面初始化
	 * 
	 * @param unitType STAFF 雇员 ,其它对应UnitType枚举类型
	 * @param staffId
	 */
	void onActivate(String unitType, long objId) {
		this.unitType = unitType;
		this.objId = objId;
		
		allRoles = staffService.findValidRole(sessionBean.isSuperUser());
		convmap = new HashMap<String, IConvertValue>();//
		convmap.put("roleName1", I18NConvert);
		if ("STAFF".equals(unitType)) {
			List<SysRole> selRoles = staffService.findRolesByStaff(objId);
			selRoleIds = (List<String>) CollectionUtil.getColFromObj(selRoles, "id");
		} else {
			List<SysRole> selRoles = staffService.findRolesByUnit(UnitType.findByName(unitType), objId, false);
			selRoleIds = (List<String>) CollectionUtil.getColFromObj(selRoles, "id");
		}
	}
}
