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

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

import org.apache.commons.collections.CollectionUtils;
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.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.util.TextStreamResponse;

import net.wicp.tams.app.duckula.controller.bean.models.SysGroup;
import net.wicp.tams.app.duckula.controller.bean.models.SysGroupExample;
import net.wicp.tams.app.duckula.controller.bean.models.SysGroupExample.Criteria;
import net.wicp.tams.app.duckula.controller.bean.models.SysOrg;
import net.wicp.tams.app.duckula.controller.bean.models.SysUserGroup;
import net.wicp.tams.app.duckula.controller.bean.models.SysUserGroupExample;
import net.wicp.tams.app.duckula.controller.dao.SysGroupMapper;
import net.wicp.tams.app.duckula.controller.dao.SysUserGroupMapper;
import net.wicp.tams.app.duckula.controller.service.cas.IOrgService;
import net.wicp.tams.cas.bean.constant.ColsSysOrg;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.apiext.jdbc.JdbcAssit;
import net.wicp.tams.common.callback.IConvertValue;
import net.wicp.tams.common.jdbc.DruidAssit;
import net.wicp.tams.common.jdbc.convert.ConvertValueMysql;
import net.wicp.tams.component.SymbolConstantsCus;
import net.wicp.tams.component.tools.TapestryAssist;
import net.wicp.tams.duckula.ops.pages.ParentPage;

public class GroupAssign extends ParentPage {
	@Inject
	private IOrgService orgService;
	@Property
	private String orgTree;
	@Persist(PersistenceConstants.CLIENT)
	@Property
	private long staffId;
	@Persist(PersistenceConstants.CLIENT)
	private JSONArray orgs;

	@Property
	private List<SysGroup> allGroup;// 已选中组织中拥有的群组

//如果不持久化onInitByOrg方法不能用
	@Property
	@Persist
	private Map<String, IConvertValue<String>> convmap;// 转换器

	@Property
	private List<String> selGroup;// 已分派到的群组

	@Inject
	private SysGroupMapper sysGroupMapper;
	@Inject
	private SysUserGroupMapper sysUserGroupMapper;

	public String getAlias() {
		return "orgId,orgName1";
	}

	public TextStreamResponse onInitByOrg() {
		JSONObject params = TapestryAssist.packParams(request, false);
		orgs = TapestryAssist.getParams(params, "orgIds");
		List<Object> orgIds = orgs == null ? null : orgs.toList();
		selAll(params.getLong("staffId"), orgIds);
		JSONObject ret = TapestryAssist.buildSelGroupInit(allGroup, selGroup, new String[] { getAlias() }, convmap);
		return retStream(ret.toString(true));
	}

	void onActivate(long staffId) {
		this.staffId = staffId;
		orgTree = orgService.createOrgTree(new IConvertValue<Object>() {
			@Override
			public String getStr(Object obj) {
				SysOrg org = (SysOrg) obj;
				String key = org.getOrgName();
				if (StringUtil.isNull(key) || !messages.contains(key)) {
					return key;
				}
				return messages.get(key);
			}
		});
		convmap = new HashMap<String, IConvertValue<String>>();//
		convmap.put("orgName1",
				new ConvertValueMysql( DruidAssit.getDefaultDb("defautl"), ColsSysOrg.tb, ColsSysOrg.orgName.getOriColName()));
		selAll(staffId, null);
	}

	/**
	 * 查询某用户在某些组织下面的群组,群组是可以跨组织的，所以用户可以加入所有的群
	 * 
	 * @param staffId
	 * @param orgIds
	 */
	private void selAll(long staffId, List<Object> orgIds) {
		// 参数转为list
		List<Long> orgidsTrue = null;
		if (orgIds != null) {
			orgidsTrue = new ArrayList<Long>();
			for (Object ele : orgIds) {
				orgidsTrue.add(Long.parseLong(String.valueOf(ele)));
			}
		}

		SysGroupExample example = new SysGroupExample();
		Criteria criteria = example.createCriteria();
		if (CollectionUtils.isNotEmpty(orgidsTrue)) {
			criteria.andOrgIdIn(orgidsTrue);
		}
		allGroup = sysGroupMapper.selectByExample(example);
		findGroupId(staffId, orgidsTrue);
	}

	/**
	 * 选择已加入的群
	 * 
	 * @param staffId
	 * @param orgidsTrue
	 */
	private void findGroupId(long staffId, List<Long> orgidsTrue) {
		// 查询已选择的群组
		// String alias = "group_"; //查询时的table别名
		SysUserGroupExample example = new SysUserGroupExample();
		SysUserGroupExample.Criteria createCriteria = example.createCriteria();
		createCriteria.andUserIdEqualTo(staffId);
		if (orgidsTrue != null) {
			SysGroupExample groupExample = new SysGroupExample();
			Criteria createCriteria2 = groupExample.createCriteria();
			createCriteria2.andOrgIdIn(orgidsTrue);
			List<SysGroup> groups = sysGroupMapper.selectByExample(groupExample);
			Set<Long> groupIds = CollectionUtil.getColSetFromObj(groups, "id");
			if (CollectionUtils.isNotEmpty(groupIds)) {
				createCriteria.andGroupIdIn(Arrays.asList(groupIds.toArray(new Long[groupIds.size()])));
			}
		}
		List<SysUserGroup> selectByExample2 = sysUserGroupMapper.selectByExample(example);
		Set<Object> groupIdset = CollectionUtil.getColSetFromObj(selectByExample2, "groupId");
		List<String> retlist=new ArrayList<String>();
		for (Object ele : groupIdset) {
			retlist.add(String.valueOf(ele));
		}
		selGroup =retlist;
	}

	/***
	 * 保存选择的结果
	 * 
	 * @param selIds
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@OnEvent(value = SymbolConstantsCus.EVENT_SAVE)
	private Result sava(JSONArray selIds) {
		if (selIds.size() != 0) {
			List<SysUserGroup> groupstaffs = sysUserGroupMapper
					.selectByMap(CollectionUtil.newMap("group_id", selIds.get(0)));

			if (CollectionUtils.isNotEmpty(groupstaffs)) {
				for (SysUserGroup groupstaff : groupstaffs) {
					if (groupstaff.getUserId() == staffId)
						return Result.getError("该群组已存在,请勿重复添加");
				}
			}
		}
		if (selIds.size() > 1)
			return Result.getError("每个用户只能选择一个群组");
		if (selIds == null) {
			return Result.getError("需要传入要保存的对象");
		}

		// 找到已有的群组
		if (orgs == null || orgs.length() == 0) {
			findGroupId(staffId, null);
		} else {
			List<Long> orgidsTrue = new ArrayList<Long>();
			for (int i = 0; i < orgs.size(); i++) {
				orgidsTrue.add(Long.parseLong(orgs.getString(i)));
			}
			findGroupId(staffId, orgidsTrue);
		}

		long[] oriIds = new long[selGroup.size()];
		for (int i = 0; i < oriIds.length; i++) {
			oriIds[i] = Long.parseLong(String.valueOf(selGroup.get(i)));
		}
		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 groupid : addList) {
				SysUserGroup saveobj = new SysUserGroup();
				saveobj.setGroupId(groupid);
				saveobj.setUserId(staffId);
				sysUserGroupMapper.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)) {
			SysUserGroupExample example = new SysUserGroupExample();
			SysUserGroupExample.Criteria createCriteria = example.createCriteria();
			createCriteria.andUserIdEqualTo(staffId);
			createCriteria.andGroupIdIn(delList);
			sysUserGroupMapper.deleteByExample(example);

		}
		return Result.getSuc();
	}
}
