package com.scpyun.platform.jilinsscgsdp.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.scpyun.base.core.utils.*;
import com.scpyun.platform.jilinsscgsdp.bean.bo.GardenInfoBo;
import com.scpyun.platform.jilinsscgsdp.bean.bo.UserInfoBo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.scpyun.base.bean.NSHttpResponse;
import com.scpyun.base.bean.Page;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.constant.Constant;
import com.scpyun.platform.sc.entity.LoginUserBean;
import com.scpyun.platform.sc.service.impl.LoginServiceImpl;

import cn.hutool.core.map.MapUtil;

@Api("app服务")
@Service("appService")
public class AppServiceImpl {

	@Autowired
	private LoginServiceImpl loginService;

	private Map<String,String> roleNameMap=new HashMap<>();

    private static final Log logger = LogFactory.getLog(AppServiceImpl.class);

    @Autowired
    CommonService commonService;

	@ApiOperation(value = "gobsName", nologin = true)
	public Map<String, Object> gobsName(Map<String, Object> map) {
		Map<String, Object> returnMap = new HashMap<>();
		returnMap.put("env", Global.getConfig("server.enviro"));

//        logger.error("-- out error logger  oops! --");
        logger.info("-- out info logger  oops! --");

		return returnMap;
	}

	@ApiOperation(value = "gJedisKey", nologin = true)
	public String sJedisKey(Map<String, Object> map) {
		return JedisUtils.set((String) map.get("key"), (String) map.get("key"), 0);
	}

	@ApiOperation(value = "gsJedisKey", nologin = true)
	public String gsJedisKey(Map<String, Object> map) {
		JedisUtils.set((String) map.get("key"), (String) map.get("key"), 0);
		return JedisUtils.get((String) map.get("key"));
	}
    
	@ApiOperation(value = "查询首页用户信息", desc = "查询首页用户信息")
    public Object getWorkerInfo(Map<String, Object> map) {
		UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
		Map<String, Object> topUserInfo = new HashMap<>();
		topUserInfo.put("userId", userInfo.getId());
		topUserInfo.put("userName", userInfo.getName());
		topUserInfo.put("companyId", userInfo.getCompany_id());
		topUserInfo.put("companyGrade", userInfo.getCompany_grade());
		topUserInfo.put("mobile", userInfo.getMobile()==null?"暂无":userInfo.getMobile());
		
		StringBuilder officeInfoStr=new StringBuilder();
		boolean isGardenUser=false;
		String canPatrol = "0"; // 0 不能巡查 1能巡查
		Map<String,Object> userMap = commonService.getObject(Constant.NAMESPACE_APP+"queryUserInfo", userInfo.getId());
		topUserInfo.put("cardnoPt", userMap.get("cardnoPt")==null?"暂无":userMap.get("cardnoPt"));
		if("6".equals(userInfo.getCompany_grade())) {
			isGardenUser=true;
			isGardenUser="1".equals(MapUtil.getStr(userMap, "job_duty"))?true:false;
		}
		Map<String, String> areaMap = getAreaMapCache();
		if(isGardenUser) {
			List<GardenInfoBo> gardenInfoBoList=commonService.findList(Constant.NAMESPACE_APP+"queryGardenUserInfo",MapUtil.getStr(userMap, "cardno"));
			if(gardenInfoBoList.isEmpty()) {
				topUserInfo.put("roleInfo","社区网格员(网格未绑定)");
				generateOfficeInfo(userInfo, officeInfoStr, areaMap);
			}else {
				canPatrol="1";
				topUserInfo.put("roleInfo","社区网格员");
				Integer index = MapUtil.getInt(map, "index");
				if(index==null) {
					index=0;
				}
				if((index+1) > gardenInfoBoList.size()) {
					index=index%gardenInfoBoList.size();
				}
				GardenInfoBo gardenInfoBo = gardenInfoBoList.get(index);
				officeInfoStr.append(areaMap.get(gardenInfoBo.getCityId()));
				officeInfoStr.append(areaMap.get(gardenInfoBo.getStreetId()));
				officeInfoStr.append(areaMap.get(gardenInfoBo.getCommunityId()));
				officeInfoStr.append(gardenInfoBo.getGardenName());
				
				topUserInfo.put("gardenCount", gardenInfoBoList.size());
				topUserInfo.put("gardenId", gardenInfoBo.getGardenId());
				topUserInfo.put("gardenUserId", gardenInfoBo.getGardenUserId());
				topUserInfo.put("index", index);
				topUserInfo.put("cardNo", userMap.get("cardno"));
			}
		}else {
			generateOfficeInfo(userInfo, officeInfoStr, areaMap);
			topUserInfo.put("roleInfo",getRoleInfo(userInfo.getId()));
		}
		topUserInfo.put("canPatrol", canPatrol);
		topUserInfo.put("officeInfo", officeInfoStr.toString());
		
    	return topUserInfo;
    }

	private void generateOfficeInfo(UserInfoBo userInfo, StringBuilder officeInfoStr, Map<String, String> areaMap) {
		Map<String, String> officeMap = getOfficeMapCache();

		List<String> officeIds = new ArrayList<>( Arrays.asList(userInfo.getParent_ids().split(",")));
		officeIds.add(userInfo.getCompany_id());
		Iterator<String> it=officeIds.iterator();
		while(it.hasNext()) {
			String officeId=it.next();
			if(StringUtils.isBlank(officeId)||!officeMap.containsKey(officeId)
					||officeMap.get(officeId).equals("总机构")||officeMap.get(officeId).equals("总管理机构")) {
				it.remove();
			}
		}
		for(int i=0;i<officeIds.size();i++) {
			String officeId=officeIds.get(i);
			if(i==officeIds.size()-1) {
				officeInfoStr.append(officeMap.get(officeId));
			}else {
				officeInfoStr.append(areaMap.get(officeId));
			}
		}
	}

	/**
	 * 缓存sys_office信息， 用于转码， 有效期1天
	 * @return
	 */
	public Map<String, String> getOfficeMapCache() {
		Map<String, String> officeMap=new HashMap<>();
		if(JedisUtils.exists(Constant.CACHE_KEY_OFFICE_MAP)) {
			officeMap=JedisUtils.getMap(Constant.CACHE_KEY_OFFICE_MAP);
		}else {
	    	List<Map<String,String>> allOfficeList = commonService.findList(Constant.NAMESPACE_APP+"queryAllOffice", MapUtil.empty());
	    	officeMap = allOfficeList.stream()
	    			.collect(Collectors.toMap(item->item.get("id"), item->item.get("name")));
	    	JedisUtils.setMap(Constant.CACHE_KEY_OFFICE_MAP, officeMap, JedisUtils.EXRP_DAY);
		}
		return officeMap;
	}
	
	/**
	 * 缓存sys_area信息， 用于转码， 有效期1天
	 * @return
	 */
	private Map<String, String> getAreaMapCache() {
		Map<String, String> areaMap=new HashMap<>();
		if(JedisUtils.exists(Constant.CACHE_KEY_AREA_MAP)) {
			areaMap=JedisUtils.getMap(Constant.CACHE_KEY_AREA_MAP);
		}else {
	    	List<Map<String,String>> allAreaList = commonService.findList(Constant.NAMESPACE_APP+"queryAllArea", MapUtil.empty());
	    	areaMap = allAreaList.stream()
	    			.collect(Collectors.toMap(item->item.get("id"), item->item.get("name")));
	    	JedisUtils.setMap(Constant.CACHE_KEY_AREA_MAP, areaMap, JedisUtils.EXRP_DAY);
		}
		return areaMap;
	}
    
    @ApiOperation(value = "查询首页统计信息", desc = "查询首页统计信息")
    public Map<String,Object> getStaticCounts(Map<String, Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
    	Map<String, Object> queryMap = new HashMap<>();
    	queryMap.put("company_id", userInfo.getCompany_id());
    	queryMap.put("isGrid", "0");
		if(Constant.GRID_ROLE_CHNNAME.equals(getRoleInfo(userInfo.getId()))) {
			queryMap.put("isGrid", "1");
			queryMap.put("user_id", userInfo.getId());
    	}
    	Map<String,Object> mapReuslt = commonService.getObject(Constant.NAMESPACE_APP+"queryHomepageStaticCount", queryMap);
    	return mapReuslt;
    }
    
    @ApiOperation(value = "查询待办角标信息", desc = "查询待办角标信息")
    public Object getTaskCounts(Map<String, Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
    	Map<String, Object> queryMap = new HashMap<>();
    	queryMap.put("company_id", userInfo.getCompany_id());
    	queryMap.put("isGrid", "0");
		if(Constant.GRID_ROLE_CHNNAME.equals(getRoleInfo(userInfo.getId()))) {
			queryMap.put("isGrid", "1");
			queryMap.put("user_id", userInfo.getId());
    	}
    	Map<String,Object> mapReuslt = commonService.getObject(Constant.NAMESPACE_APP+"queryTaskCount", queryMap);
    	return mapReuslt;
    }
    
    @ApiOperation(value = "查询辖区动态列表", desc = "查询辖区动态列表")
    public Object queryEventsByUserLevel(Page<Map<String, String>> page) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(page.getParams());
		Map<String, Object> queryMap = page.getParams();
		queryMap.put("grade", userInfo.getCompany_grade());
		queryMap.put("company_id", userInfo.getCompany_id());
		Page<Map<String,String>> pageList = commonService.findPage(Constant.NAMESPACE_APP+"queryAreaEventsPageList", page);
		dataShowHandler(pageList,null);
    	return pageList;
    }
    
    @ApiOperation(value = "分页查询待办任务", desc = "分页查询个人待办任务")
    public Object queryEventsUnHandlePageList(Page<Map<String, String>> page) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(page.getParams());
		Map<String, Object> queryMap = page.getParams();
		queryMap.put("company_id", userInfo.getCompany_id());
		queryMap.put("isGrid", "0");
		if(Constant.GRID_ROLE_CHNNAME.equals(getRoleInfo(userInfo.getId()))) {
			queryMap.put("isGrid", "1");
			queryMap.put("user_id", userInfo.getId());
    	}
		Page<Map<String,String>> pageList = commonService.findPage(Constant.NAMESPACE_APP+"queryEventsUnHandlePageList", page);
		dataShowHandler(pageList,userInfo.getId());
		roleNameMap.clear();
    	return pageList;
    }

    @ApiOperation(value = "分页查询已办任务", desc = "分页查询已办任务")
    public Object queryEventsHandledPageList(Page<Map<String, String>> page) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(page.getParams());
		Map<String, Object> queryMap = page.getParams();
		queryMap.put("company_id", userInfo.getCompany_id());
		Page<Map<String,String>> pageList = commonService.findPage(Constant.NAMESPACE_APP+"queryEventsHandledPageList", page);
		dataShowHandler(pageList,userInfo.getId());
		roleNameMap.clear();
    	return pageList;
    }

    @ApiOperation(value = "分页查询办结任务", desc = "分页查询办结任务")
    public Object queryEventsCompletePageList(Page<Map<String, String>> page) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(page.getParams());
		Map<String, Object> queryMap = page.getParams();
		queryMap.put("company_id", userInfo.getCompany_id());
		Page<Map<String,String>> pageList = commonService.findPage(Constant.NAMESPACE_APP+"queryEventsCompletePageList", page);
		dataShowHandler(pageList,null);
    	return pageList;
    }
    
    private String getRoleInfo(String userId) {
    	String roleName="未知身份";
    	if(roleNameMap.containsKey(userId)) {
    		roleName=roleNameMap.get(userId);
    	}else {
    		List<Map<String, String>> userRoleInfo = commonService.findList(Constant.NAMESPACE_APP+"queryUserRoleInfo", userId);
    		if(!userRoleInfo.isEmpty()) {
    			roleName=userRoleInfo.get(0).get("name");
    			roleNameMap.put(userId, roleName);
    		}
    	}
		return roleName;
    }
    
	/**
	 * 事件信息转码
	 * @param pageList
	 */
	private void dataShowHandler(Page<Map<String, String>> pageList,String userId) {
		Map<String, String> areaMap = getAreaMapCache();
		for(Map<String,String> map: pageList.getResults()) {
			String cityName="";
			String areaName="";
			String cityId=map.get("city_id");
			String areaId=map.get("area_id");
			if(areaMap.containsKey(cityId)) {
				cityName=areaMap.get(cityId);
			}else {
				cityName="未知城市";
			}
			if(areaMap.containsKey(areaId)) {
				areaName=areaMap.get(areaId);
			}else {
				areaName="未知区县";
			}
			map.put("areaInfo", cityName+areaName);
			if(StringUtils.isBlank(map.get("dispute_description"))) {
				map.put("dispute_description", "无");
			}else {
				if(map.get("dispute_description").length()>10) {
					map.put("dispute_description", map.get("dispute_description").substring(0, 10)+"...");
				}
			}
			if(userId!=null) {
				map.put("taskNode",getRoleInfo(userId)+"办理");
			}
		}
	}
	
    @ApiOperation(value = "矛盾事件详情查询", desc = "矛盾事件详情查询")
    public Map<String, Object> getEventDetailById(Map<String, Object> map) {
        Map<String, Object> eventMap = commonService.getObject(Constant.NAMESPACE_APP + "getEventDetailById", map);
        eventMap.put("userList", commonService.findList(Constant.NAMESPACE_USER + "selectUserByEventIdList", eventMap));
        return eventMap;
    }
    
    @ApiOperation(value = "查询事件总数分页列表", desc = "查询事件总数分页列表")
    public Object queryEventsOfAllPageList(Page<Map<String, String>> page) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(page.getParams());
		Map<String, Object> queryMap = page.getParams();
		queryMap.put("company_id", userInfo.getCompany_id());
		queryMap.put("isGrid", "0");
		if(Constant.GRID_ROLE_CHNNAME.equals(getRoleInfo(userInfo.getId()))) {
			queryMap.put("isGrid", "1");
			queryMap.put("user_id", userInfo.getId());
    	}
		Page<Map<String,String>> pageList = commonService.findPage(Constant.NAMESPACE_APP+"queryEventsOfAllPageList", page);
		dataShowHandler(pageList,null);
    	return pageList;
    }
    
	@ApiOperation(value = "APP_用户登录_加密", desc = "", nologin = true)
	public NSHttpResponse app_userLogin_encrypt(LoginUserBean loginUser, HttpServletRequest request) {
		String jSessionId=request.getSession().getId();
		NSHttpResponse ntResponse = loginService.userLogin_encrypt(loginUser, request);
		if(ntResponse.getBody().get("data")!=null && ntResponse.getBody().get("data") instanceof Map) {
			Map<String,String> map=(Map<String,String>) ntResponse.getBody().get("data");
			map.put("JSESSIONID", jSessionId);
		}
		
		return ntResponse;
	}
}
