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

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.tapestry5.Asset;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.commons.util.CollectionFactory;
import org.apache.tapestry5.http.services.Request;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.TextStreamResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import net.wicp.tams.app.duckula.controller.bean.constant.ResAuthType;
import net.wicp.tams.app.duckula.controller.bean.models.SysGlobal;
import net.wicp.tams.app.duckula.controller.bean.models.SysResource;
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.config.constant.ConfigGlobleName;
import net.wicp.tams.app.duckula.controller.dao.SysGlobalMapper;
import net.wicp.tams.app.duckula.controller.dao.SysResourceMapper;
import net.wicp.tams.app.duckula.controller.dao.SysRoleResMapper;
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.constant.dic.YesOrNo;
import net.wicp.tams.component.assistbean.Menu;
import net.wicp.tams.component.tools.TapestryAssist;
import net.wicp.tams.duckula.ops.beans.SessionBean;

/**
 * Start page of application duckula-ops.
 */
public class Index {

	@Inject
	@Path("menu.properties")
	private Asset asset;

	@SessionState
	@Property
	private SessionBean sessionBean;

	private boolean sessionBeanExists;

	@InjectPage
	private Login login;

	@Inject
	protected Request request;

	@Inject
	private SysGlobalMapper sysGlobalMapper;

	@Inject
	private SysResourceMapper sysResourceMapper;
	

	@OnEvent(value = "switchMenu")
	public List<Menu> switchMenu(String moudleId) throws IOException {
//		Properties prop = new Properties();
//		prop.load(asset.getResource().openStream());
//		String[] menus = prop.getProperty("menu.all").split(",");
//		List<Menu> retlist = CollectionFactory.newList();
//		for (int i = 0; i < menus.length; i++) {
//			if (!menus[i].startsWith(moudleId)) {
//				continue;
//			}
//			String id = prop.getProperty(String.format("%s.id", menus[i]));
//
//			String resName = prop.getProperty(String.format("%s.resName", menus[i]));
//			String resType = prop.getProperty(String.format("%s.resType", menus[i]));
//			String resValue = prop.getProperty(String.format("%s.resValue", menus[i]));
//			if (StringUtil.isNotNull(id) && StringUtil.isNotNull(resName) && StringUtil.isNotNull(resType)
//					&& StringUtil.isNotNull(resValue)) {
//				Menu menu = Menu.builder().id(id).resName(resName).resType(ResType.get(resType)).resValue(resValue)
//						.build();
//				retlist.add(menu);
//			}
//		}
		QueryWrapper<SysResource> queryWrapper = new QueryWrapper<SysResource>();
		queryWrapper.eq("parent_id", Long.parseLong(moudleId));
		queryWrapper.eq("res_type", ResAuthType.URL.name());
		List<SysResource> selectList = sysResourceMapper.selectList(queryWrapper);
		
		
		Set<Long> findResByRoles = findResByRoles();
		CollectionUtils.filter(selectList, new Predicate() {
			@Override
			public boolean evaluate(Object arg0) {
				SysResource sysResource=(SysResource)arg0;
				return findResByRoles.contains(sysResource.getId());
			}
		});
		List<Menu> retlist = CollectionFactory.newList();
		for (SysResource sysResource : selectList) {
			String id = String.valueOf(sysResource.getId());
			String resName = sysResource.getResName();
			String resType = sysResource.getResType();
			String resValue = sysResource.getResValue();
			if (StringUtil.isNotNull(id) && StringUtil.isNotNull(resName) && StringUtil.isNotNull(resType)
					&& StringUtil.isNotNull(resValue)) {
				Menu menu = Menu.builder().id(id).resName(resName).resType(net.wicp.tams.component.constant.ResType.get(resType)).resValue(resValue)
						.build();
				retlist.add(menu);
			}
		}
		return retlist;
	}

	private Set<Long> findResByRoles() {
		//得到
		SysRoleResExample example = new SysRoleResExample();
		Criteria criteria = example.createCriteria();
		criteria.andRoleIdIn(sessionBean.getRoles());
		List<SysRoleRes> list = sysRoleResMapper.selectByExample(example);
		Set<Long> resIds = CollectionUtil.getColSetFromObj(list, "resId");
		return resIds;
	}


	@Inject
	private SysRoleResMapper sysRoleResMapper;

	@SetupRender
	void init() {
		// 设置模块
		if (sessionBean.getModules() == null || sessionBean.getModules().isEmpty()) {
			QueryWrapper<SysResource> queryWrapper = new QueryWrapper<SysResource>();
			queryWrapper.eq("res_type", "MODULE");
			List<SysResource> selectList = sysResourceMapper.selectList(queryWrapper);
			//List<Long> roles = new ArrayList<Long>();// 测试用
			//roles.add(1405760902957436930l);
			
			Set<Long> findResByRoles = findResByRoles();
			
			// 得到有权限的模块
			CollectionUtils.filter(selectList, new Predicate() {
				@Override
				public boolean evaluate(Object arg0) {
					SysResource sysResource = (SysResource) arg0;
					return findResByRoles.contains(sysResource.getId());
				}
			});
			JSONArray temp = new JSONArray();
			for (SysResource sysResource : selectList) {
				JSONObject menu = new JSONObject();
				menu.put("id", sysResource.getId());
				menu.put("icon", sysResource.getIcon());
				menu.put("alt", sysResource.getResName());
				temp.add(menu);
			}
			sessionBean.setModules(temp);
		}
	}

	public TextStreamResponse onDataSave() {
		String saveDataStr = request.getParameter("saveData");
		JSONObject dgAll = JSONObject.parseObject(saveDataStr);
		JSONArray rows = dgAll.getJSONArray("rows");
		System.out.println("rows=" + rows.size());
		SysGlobal save = new SysGlobal();
		save.setId(1l);
		save.setConfigGloble(dgAll.toJSONString());
		save.setLastUpdatetime(new Date());
		save.setLastUsername(sessionBean.getSysUser().getUserName());
		ConfigGlobleName.putAwsConfig(save);
		SysGlobal selectById = sysGlobalMapper.selectById(1L);
		if (selectById == null) {
			sysGlobalMapper.insert(save);
		} else {
			sysGlobalMapper.updateByPrimaryKeySelective(save);
		}
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	public TextStreamResponse onDataInit() {
		JSONObject retjson = null;
		SysGlobal sysGlobal = sysGlobalMapper.selectById(1L);
		if (sysGlobal != null) {
			retjson = JSON.parseObject(sysGlobal.getConfigGloble());
		} else {
			ConfigGlobleName.putAwsConfig(sysGlobal);
			retjson = ConfigGlobleName.retInitJsonObject();
		}
		return TapestryAssist.getTextStreamResponse(retjson.toJSONString());
	}

	public TextStreamResponse onLogout() {
		sessionBean = null;
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	public Object onActivate() {
		if (!sessionBeanExists || sessionBean == null || sessionBean.getIsLogin() == YesOrNo.no) {
			return login;
		} else {
			return null;
		}
	}
}
