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.SysOrg;
import net.wicp.tams.app.duckula.controller.bean.models.SysPosition;
import net.wicp.tams.app.duckula.controller.bean.models.SysPositionExample;
import net.wicp.tams.app.duckula.controller.bean.models.SysUserPosition;
import net.wicp.tams.app.duckula.controller.bean.models.SysUserPositionExample;
import net.wicp.tams.app.duckula.controller.bean.models.SysUserPositionExample.Criteria;
import net.wicp.tams.app.duckula.controller.dao.SysPositionMapper;
import net.wicp.tams.app.duckula.controller.dao.SysUserPositionMapper;
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.callback.IConvertValue;
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 PositionAssign 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<SysPosition> allPosition;// 已选中组织中拥有的群组

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

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

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

	@Inject
	private SysUserPositionMapper sysUserPositionMapper;
	@Inject
	private SysPositionMapper sysPositionMapper;

	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(allPosition, selPosition, 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(ColsSysOrg.tb, ColsSysOrg.orgName.getOriColName()));
		selAll(staffId, null);
	}

	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)));
			}
		}

		SysPositionExample example = new SysPositionExample();
		SysPositionExample.Criteria criteria = example.createCriteria();
		if (CollectionUtils.isNotEmpty(orgidsTrue)) {
			criteria.andOrgIdIn(orgidsTrue);
		}
		allPosition = sysPositionMapper.selectByExample(example);
		findGroupId(staffId, orgidsTrue);
	}

	private void findGroupId(long staffId, List<Long> orgidsTrue) {
		// 查询已选择的群组
		// String alias = "group_"; //查询时的table别名
		SysUserPositionExample example = new SysUserPositionExample();
		SysUserPositionExample.Criteria createCriteria = example.createCriteria();
		createCriteria.andUserIdEqualTo(staffId);
		if (orgidsTrue != null) {
			SysPositionExample positionExample = new SysPositionExample();
			SysPositionExample.Criteria createCriteria2 = positionExample.createCriteria();
			createCriteria2.andOrgIdIn(orgidsTrue);
			List<SysPosition> positions = sysPositionMapper.selectByExample(positionExample);
			Set<Long> positionIds = CollectionUtil.getColSetFromObj(positions, "id");
			if (CollectionUtils.isNotEmpty(positionIds)) {
				createCriteria.andPositionIdIn(Arrays.asList(positionIds.toArray(new Long[positionIds.size()])));
			}
		}
		List<SysUserPosition> selectByExample = sysUserPositionMapper.selectByExample(example);
		Set<Object> positionIdset = CollectionUtil.getColSetFromObj(selectByExample, "positionId");
		List<String> retlist = new ArrayList<String>();
		for (Object ele : positionIdset) {
			retlist.add(String.valueOf(ele));
		}
		selPosition = retlist;
	}

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

		// 找到已有的群组
		if (orgs == null || orgs.size() == 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[selPosition.size()];
		for (int i = 0; i < oriIds.length; i++) {
			oriIds[i] = Long.parseLong(String.valueOf(selPosition.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 positionId : addList) {
				SysUserPosition saveobj = new SysUserPosition();
				saveobj.setPositionId(positionId);
				saveobj.setUserId(staffId);
				sysUserPositionMapper.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)) {
			SysUserPositionExample example = new SysUserPositionExample();
			Criteria createCriteria = example.createCriteria();
			createCriteria.andUserIdEqualTo(staffId);
			createCriteria.andPositionIdIn(delList);
			sysUserPositionMapper.deleteByExample(example);
		}
		return Result.getSuc();
	}
}
