package com.engine.voting.web;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.BrowserBean;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionType;
import com.api.voting.bean.RightMenu;
import com.api.voting.util.BrowserType;
import com.api.voting.util.ConditionUtil;
import com.api.voting.util.RightMenuType;
import com.api.voting.util.VotingCommonUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.voting.service.VotingListService;
import com.engine.voting.service.impl.VotingListServiceImpl;
import com.engine.workflow.util.CommonUtil;

/**
 * 网上调查列表
 * */
@Path("/voting/list")
public class VotingListAction {
	private VotingListService getService(HttpServletRequest request, HttpServletResponse response) {
        return ServiceUtil.getService(VotingListServiceImpl.class, CommonUtil.getUserByRequest(request, response));
    }

    /**
     * 调查结果列表
     * */
    @GET
    @Path("/result")
    @Produces(MediaType.TEXT_PLAIN)
    public String result(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        try {
            User user = HrmUserVarify.getUser(request, response);    
            Map<String, Object> params = getRequestMap(request);
            apidatas = getService(request, response).getResultList(user, params);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "系统内部异常");
        }
        return JSONObject.toJSONString(apidatas);
    }
	
    /**
     * 未参与列表
     * */
    @GET
    @Path("/myVoting")
    @Produces(MediaType.TEXT_PLAIN)
    public String myVoting(@Context HttpServletRequest request, @Context HttpServletResponse response)
            throws Exception {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        try {
            User user = HrmUserVarify.getUser(request, response);

            //当前选中tab
            int tabInfo = Util.getIntValue(request.getParameter(ConditionUtil.TAB_REQ_NAME), ConditionUtil.TAB_VOTING_DEFAULT);

            apidatas = getService(request, response).getMyVoting(user, this.getRequestMap(request), tabInfo);

        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "系统内部异常");
        }
        return JSONObject.toJSONString(apidatas);
    }
	
	/**
	 * 与我相关，未参与，我发起，已参与 调查数量
	 * */
	@GET
	@Path("/myVotingNum")
	@Produces(MediaType.TEXT_PLAIN)
	public String myVotingNum(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			Map<String,Object> params = getRequestMap(request);
			apidatas = getService(request, response).getMyVotingNum(user, params);
			
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "系统内部异常");
		}
		return JSONObject.toJSONString(apidatas);
	}
	
	/**
	 * TAB页
	 * @author wangqs
	 * */
	@GET
	@Path("/tabInfo")
	@Produces(MediaType.TEXT_PLAIN)
	public String getTabInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			
			int _default = ConditionUtil.TAB_VOTING_DEFAULT;
			
			List<Map<String,Object>> groupinfo = new ArrayList<Map<String,Object>>();
			
			Map<String,Object> undo = new HashMap<String,Object>();
			undo.put("color","");
			undo.put("selected",ConditionUtil.TAB_ALL_VALUE == _default);
			undo.put("groupid","undo");
			undo.put("editable",false);
			undo.put("showcount",false);
			undo.put("title",SystemEnv.getHtmlLabelName(33850,user.getLanguage()));
			undo.put(ConditionUtil.TAB_REQ_NAME, ConditionUtil.TAB_VOTING_UN_DO);
			groupinfo.add(undo);
			
			Map<String,Object> hasDown = new HashMap<String,Object>();
			hasDown.put("color","");
			hasDown.put("selected",ConditionUtil.TAB_TODAY_VALUE == _default);
			hasDown.put("groupid","hasDown");
			hasDown.put("editable",false);
			hasDown.put("showcount",false);
			hasDown.put("title",SystemEnv.getHtmlLabelName(33849,user.getLanguage()));
			hasDown.put(ConditionUtil.TAB_REQ_NAME, ConditionUtil.TAB_VOTING_DO);
			groupinfo.add(hasDown);
			
			apidatas.put("groupinfo",groupinfo);
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "系统内部异常");
		}
		return JSONObject.toJSONString(apidatas);	
	}
	
	/**
	 * 右键菜单
	 * @author wangqs
	 * */
	@GET
	@Path("/rightMenu")
	@Produces(MediaType.TEXT_PLAIN)
	public String getRightMenu(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			List<RightMenu> rightMenus = new ArrayList<RightMenu>(); 
			
			String listType = request.getParameter("listType");//  --result:调查结果，myVoting-参与调查
			int tabInfo = Util.getIntValue(request.getParameter(ConditionUtil.TAB_REQ_NAME),ConditionUtil.TAB_VOTING_DEFAULT);
			
			int language = user.getLanguage();
			
			//if("result".equals(listType) || ("myVoting".equals(listType) && tabInfo == ConditionUtil.TAB_VOTING_DO)){
				rightMenus.add(new RightMenu(language, RightMenuType.BTN_SEARCH, "", false));
			//}
			rightMenus.add(new RightMenu(language, RightMenuType.BTN_STORE, "", false));
			rightMenus.add(new RightMenu(language, RightMenuType.BTN_HELP, "", false));
			
			apidatas.put("rightMenus", rightMenus);
			//当前选中tab
		}catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "系统内部异常");
		}
		return JSONObject.toJSONString(apidatas);	
	}
	
	/**
	 * 高级搜索
	 * */
	@GET
	@Path("/condition")
	@Produces(MediaType.TEXT_PLAIN)
	public String getConDition(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			
			String listType = request.getParameter("listType");//  --result:调查结果，myVoting-参与调查
			int tabInfo = Util.getIntValue(request.getParameter(ConditionUtil.TAB_REQ_NAME),ConditionUtil.TAB_VOTING_DEFAULT);
			String isFromMobile = Util.null2String(request.getParameter("_ec_ismobile"));
			int viewcondition = Util.getIntValue(request.getParameter("viewcondition"), 1); //0:未参与列表，1：已参与列表
			
			List<Map<String,Object>> grouplist = new ArrayList<Map<String,Object>>();
			
			Map<String,Object> groupitem1 = new HashMap<String,Object>();
			List<SearchConditionItem> itemlist1 = new ArrayList<SearchConditionItem>();
			groupitem1.put("title", SystemEnv.getHtmlLabelNames(ConditionUtil.COMMON_CONDITION, user.getLanguage()));
			groupitem1.put("defaultshow", true);
			groupitem1.put("items", itemlist1);
			grouplist.add(groupitem1);
			
			SearchConditionItem titleItem = new SearchConditionItem(ConditionType.INPUT, SystemEnv.getHtmlLabelName(33439, 
					user.getLanguage()), new String[]{"subject"});
			titleItem.setIsQuickSearch(true);
			itemlist1.add(titleItem);
			BrowserBean createUser = new BrowserBean(BrowserType.USER);
			
			if("result".equals(listType) || "true".equals(isFromMobile)){
				itemlist1.add(new SearchConditionItem(ConditionType.BROWSER, SystemEnv.getHtmlLabelName(882, 
						user.getLanguage()), new String[]{"createrid"},createUser));
				
				List<SearchConditionOption>  options = new ArrayList<SearchConditionOption>();
				List<Map<String,String>> votingTypes = getService(request, response).getVotingTypes();
				for(Map<String,String> votingType : votingTypes){
					options.add(new SearchConditionOption(votingType.get("id"),votingType.get("name")));
				}
//				SearchConditionItem votingTypeItem = new SearchConditionItem(ConditionType.SELECT, SystemEnv.getHtmlLabelName(24111,
//						user.getLanguage()), new String[]{"votingtype"});
//				votingTypeItem.setOptions(options);
//				itemlist1.add(votingTypeItem);
			} else if("myVoting".equals(listType)) { //未参与列表才有创建
			    // 创建人
                itemlist1.add(new SearchConditionItem(ConditionType.BROWSER, SystemEnv.getHtmlLabelName(882, user.getLanguage()), new String[]{"createrid"}, createUser));
            }
			
			List<SearchConditionOption>  statusOptions = new ArrayList<SearchConditionOption>();
			statusOptions.add(new SearchConditionOption("",""));
			//statusOptions.add(new SearchConditionOption("3",SystemEnv.getHtmlLabelNames("30835",user.getLanguage())));
			statusOptions.add(new SearchConditionOption("1",SystemEnv.getHtmlLabelName(18600,weaver.general.Util.getIntValue(user.getLanguage())))); //进行
			statusOptions.add(new SearchConditionOption("2",SystemEnv.getHtmlLabelName(405,weaver.general.Util.getIntValue(user.getLanguage())))); //结束
			SearchConditionItem votingStatusItem = new SearchConditionItem(ConditionType.SELECT, SystemEnv.getHtmlLabelName(602, user.getLanguage()), new String[]{"status"});
			votingStatusItem.setOptions(statusOptions);
			itemlist1.add(votingStatusItem);
			
			//调查时间（时间选择）
			itemlist1.add(new SearchConditionItem(ConditionType.DATE, SystemEnv.getHtmlLabelName(500889, user.getLanguage()), "", new String[]{"datetype", "begindate", "enddate"}, 
			        VotingCommonUtil.getDateSelectOption(user.getLanguage(), false, false), 6, 18, null));
			
			if("myVoting".equals(listType) && tabInfo == ConditionUtil.TAB_VOTING_UN_DO){
				//grouplist = new ArrayList<Map<String,Object>>();
			}
			
			if("true".equals(isFromMobile)){
				apidatas.put("conditioninfo", grouplist);
			}else{
				apidatas.put("condition", grouplist);
			}
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "系统内部异常");
		}
		return JSONObject.toJSONString(apidatas);
	}
	
	public Map<String,Object> getRequestMap(HttpServletRequest request){
		Map<String,Object> dataMap = new HashMap<String,Object>();
		Enumeration paramNames = request.getParameterNames(); 
		while (paramNames.hasMoreElements()) { 
			String paramName = (String) paramNames.nextElement(); 
			String paramValue = Util.null2String(request.getParameter(paramName));
			dataMap.put(paramName,paramValue);
		}
		return dataMap;
	}
}
