package com.palmnest.service.org.impl;

import com.alibaba.fastjson.JSON;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.core.util.LingLingUtil;
import com.palmnest.application.dto.OrgKoalaInfoVo;
import com.palmnest.dao.lingling.LingLingDao;
import com.palmnest.model.*;
import com.palmnest.model.lingling.LingLingLog;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.TbOrganizationConfig;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.RoleManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.FaceClientManager;
import com.palmnest.service.estateserve.ServeConfigService;
import com.palmnest.service.lingling.manager.LingLingManager;
import com.palmnest.service.org.OrganizationService;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.ws.FacePlusClient;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.CookieStore;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

@Service("organizationService")
public class OrganizationServiceImpl implements OrganizationService {

	@Autowired
	private RoleManager         roleManager;
	@Autowired
	private ServeConfigService  serveConfigService;
	@Autowired
	private UserManager         userManager;
	@Autowired
	private OrganizationManager organizationManager;
	
	@Autowired
	private BaseRedisService    baseRedisService;
	
	@Autowired
	private LingLingManager lingLingManager;
	
	@Autowired
	private FaceClientManager faceClientManager;
	


	@Async
	@Override
	public void addRoleForOrg(Integer orgId) {

		//创建新项目同时创建一个该项目对应的角色,并且为该角色分配基础的功能
		TbOrganization org = organizationManager.getOrganizationById(orgId);
		if (org == null) {
			return;
		}
		Role role = new Role();
		role.setName(org.getName() + "-项目管理员");
		role.setDescription(org.getName() + "-项目管理员角色");
		role.setRoleType(AppConstants.OGR_MANAGER_ROLE_TYPE);
		role.setStatusFlag(1);
		role.setIsenalbed(ElementConstant.YESORNO_1);
		role.setLastUpdatedTime(new Date());
		role.setISINITIALIZATION(0);
		role.setFLOOR_REPAIR(3);//管理员类型
		//保存角色信息
		role.setOrgId(orgId);
		roleManager.saveModel(role);
		System.out.println(role.getId());
		//赋给项目管理员基础服务权限
		List<AppFunction> functions = serveConfigService.getServiceFunctionList(AppConstants.BASEFUNCTION, null);
		for (AppFunction f : functions) {
			RoleFunction roleFunction = new RoleFunction(role, f);
			roleManager.saveRoleFunction(roleFunction);
		}
	}

	@Async
	@Override
	public void updateOrgServiceRoleFuction(Integer orgId, Integer serviceId, Integer type) {
		//查找项目下的项目管理员角色
		List<Role> roles = roleManager.getByOrg(orgId, AppConstants.OGR_MANAGER_ROLE_TYPE);
		if (roles.size() > 0) {
			Role role = roles.get(0);
			//查询该角色下的功能权限
			List<RoleFunction> roleFunctions = roleManager.queryRoleFunctionSet(role);
			List<Integer>      funcIds       = new ArrayList<Integer>();
			for (RoleFunction roleF : roleFunctions) {
				funcIds.add(roleF.getFunction().getId());
			}
			List<AppFunction> functions = serveConfigService.getServiceFunctionList(serviceId, null);
			//新增
			if (type == 1) {
				for (AppFunction f : functions) {
					if (funcIds.contains(f.getId())) {
						continue;
					}
					RoleFunction roleFunction = new RoleFunction(role, f);
					roleManager.saveRoleFunction(roleFunction);
				}
			} else if (type == 2) {
				//删除
				for (AppFunction f : functions) {
					if (funcIds.contains(f.getId())) {
						roleManager.deleteRoleFunction(role.getId(), f.getId());
						;
					}
				}
			}
		}
	}

	@Override
	public void updateUserRole(List<String> orgnizations, Long userId) {
		//查找项目下的项目管理员角色
		User user = userManager.get(userId);
		if (user.getUserType() == 1 || user.getUserType() == 2) {
			Role role = roleManager.get(Long.parseLong("-1"));
			user.addRole(role);
		} else if (user.getUserType() == 3) {
			for (String orgId : orgnizations) {
				List<Role> roles = roleManager.getByOrg(Integer.parseInt(orgId), AppConstants.OGR_MANAGER_ROLE_TYPE);
				if (roles.size() > 0) {
					Role role = roles.get(0);
//					user.addRole(role);
					Set<Role> set = new HashSet<Role>();
					set.add(role);
					user.setRoles(set);
				}
			}
		}
		userManager.updateUser(user);
	}

	@Override
	public List<TbCompany> getCompanyList(String isenabled) {
		return organizationManager.getCompanyList(isenabled);
	}

	@Override
	public TbOrganizationConfig getObj(String id) {
		return organizationManager.getObj(id);
	}

	@Override
	public TbOrganizationConfig getDiscoverConfigByOrgId(String orgId) {
		return organizationManager.getDiscoverConfigByOrgId(orgId);
	}

	@Override
	public String saveOrUpdateTbOrgConfig(TbOrganizationConfig config) {
		return organizationManager.saveOrUpdateTbOrgConfig(config);
	}

	@Override
	public TbOrganization getByMettingClient(String mettingClient) {
		return organizationManager.getByMettingClient(mettingClient);
	}

	@Override
	public List<TbOrganization> enableOrgList(Integer enable) {
		return organizationManager.enableOrgList(enable);
	}

	@Override
	public void koalaProjectConfig() {


       Integer passType = 4;

        List<TbOrganization> listOrgEntirys = organizationManager.passTypeOrgList(passType);
        if(listOrgEntirys.size()>=1){
            for(TbOrganization vo:listOrgEntirys){


                //log.info("项目：{} 考拉配置koalaProjectConfig _url:{},_koalaUserName:{},_koalaUserPwd:{}",vo.getName(),vo.getKoalaAuthUrl(),vo.getKoalaUserName(),vo.getKoalaUserPwd());
                //AppConstants.koala_project_map.put(vo.getId()+"_url",vo.getKoalaAuthUrl());
                //AppConstants.koala_project_map.put(vo.getId()+"_koalaUserName",vo.getKoalaUserName());
                //AppConstants.koala_project_map.put(vo.getId()+"_koalaUserPwd",vo.getKoalaUserPwd());
                //RedisString redisString = new RedisString("User.id:"+ CodeConstants.RSA_REDIS_ORGKOALA_KEY + "_"+vo.getId());


            	OrgKoalaInfoVo orgKoalaInfoVo =new OrgKoalaInfoVo(vo.getKoalaAuthUrl(),vo.getKoalaUserName(),vo.getKoalaUserPwd());

                baseRedisService.set("User.id:"+ CodeConstants.RSA_REDIS_ORGKOALA_KEY + "_"+vo.getId(),JSON.toJSONString(orgKoalaInfoVo));

   
            }
        }   
		
	}

	@Override
	public void snycKoalaPassLog() {

	       Integer passType = 4;

	        List<TbOrganization> listOrgEntirys = organizationManager.passTypeOrgList(passType);
	        if(listOrgEntirys.size()>=1){
	            for(TbOrganization vo:listOrgEntirys){	            

	            	int orgId = vo.getId();
	            	//CookieStore cookieStore = Constants.FaceMap.get("org_cookiestore_" + orgId);
	            	CookieStore cookieStore =faceClientManager.getCookieStoreByOrgId(orgId);
	    			if (cookieStore == null) {
	    				continue;
	    			}
	            	
	    			try{
	    				
	    				String cursorValue = baseRedisService.get("User.id:"+ CodeConstants.RSA_REDIS_CURSOR_KEY + "_"+orgId);
	    				Map<String, Object> paramMap = new HashMap<String, Object>();
	    				if(StringUtils.isNotEmpty(cursorValue)){
	    					paramMap.put("cursor", cursorValue);
	    				}  				
	    				
		    			JSONObject map = FacePlusClient.scan(paramMap,cookieStore);
		    			
		    			System.out.println("snycKoalaPassLog 同步koala日志记录======>"+ map.toString());
		    			
		    			JSONArray eventsJSONArray =  (JSONArray)map.get("events");
		    			String cursor = map.getString("cursor");//游标
		    			baseRedisService.set("User.id:"+ CodeConstants.RSA_REDIS_CURSOR_KEY + "_"+orgId,cursor);
		    			
		    			for(int i=0;i<eventsJSONArray.length();i++){
		    				
		    				LingLingLog log = new LingLingLog();
		    				log.setCreateTime(new Date());     				
		    				log.setOrgId(orgId);
		    				JSONObject obj = eventsJSONArray.getJSONObject(i);
		    				String userName = obj.getString("name");
		    				String timestamp = obj.getString("timestamp");
		    				String deviceName = obj.getString("camera_position");//设备名称
		    				String subject_type = obj.getString("subject_type");//subject_tpe: 人员类型: 0:员工，1:访客(此接口包含vip)，2:vip访客， 3:黄名单，100:陌生人
		    				JSONObject subject = obj.getJSONObject("subject");
		    				
		    				if(null!= subject && subject.has("phone")){
		    					log.setMobile(subject.getString("phone"));
		    				}
		    		
		    				log.setType(LingLingUtil.OWNER_LOG_TYPE);
		    				if(StringUtils.isNotEmpty(subject_type) && "1".equals(subject_type)){
		    					log.setType(LingLingUtil.VISITOR_LOG_TYPE);
		    				}
		    				log.setUserName(userName);
		    				log.setDeviceName(deviceName);
		    				if(StringUtils.isNotEmpty(timestamp)){
		    					Timestamp t = new Timestamp(Long.valueOf(timestamp+"000"));
		    				    Date d = new Date(t.getTime());
		    				    log.setOpenTime(d);
		    				}else{
		    					log.setOpenTime(new Date());
		    				}
		    				log.setPassType(4);//2-令令开门 4-koala
		    				
		    				
		    				lingLingManager.save(log);
		    				
		    			}
	    			}catch(Exception e){
	    				
	    				e.printStackTrace();
	    			}

	            	
	            	

	   
	            }
	        }   
			
		
		
		
		
	}
}
