package com.jw.app.apps.utils;

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

import org.apache.commons.lang.StringUtils;

import com.gaowj.business.comp.BusinessManager;
import com.gaowj.business.exception.BusinessException;
import com.jw.app.business.AppsBusiness;

public class appsSetUtil {
	
    public static void appsSet(Map<String, Object> user,boolean is_delete) throws BusinessException{
		AppsBusiness business = BusinessManager.getBusiness(AppsBusiness.class);	
		try{
		  String ls_code = (String)user.get("CODE");
		  String ls_depart = (String)user.get("EMDEPART");
		  if(is_delete){
			  Map<String,Object> t_app_entity = new HashMap<String,Object>();
			  t_app_entity.put("USERID", ls_code);
			  business.delete_install_app_user(t_app_entity);
			  business.delete_uninstall_app_user(t_app_entity);
		  }else{
			//查找此用户有权使用的应用
			Map<String,Object> ls_query = new HashMap<String,Object>();
			ls_query.put("G_ID", ls_depart);
			List<Map<String,Object>> ls_apps = business.list_app(ls_query);
			//查找是否已安装，没有则安装应用

			for(Map<String,Object> t_app : ls_apps){
				Map<String,Object> t_app_query = new HashMap<String,Object>();
				t_app_query.put("USERID", ls_code);
				t_app_query.put("APP_ID", t_app.get("APP_ID"));
				List<Map<String,Object>> ls_install_y = business.list_install(t_app_query);
				List<Map<String,Object>> ls_uninstall_y = business.list_uninstall(t_app_query);
				if((ls_install_y.size()+ls_uninstall_y.size())==0){
					String is_default = (String) t_app.get("IS_DEFAULT");
					Map<String,Object> entityNew = new HashMap<String,Object>();
			    	entityNew.put("APP_ID", t_app_query.get("APP_ID"));
			    	entityNew.put("USERID", t_app_query.get("USERID"));
			    	if(StringUtils.isNotEmpty(is_default) && StringUtils.equals(is_default, "1")){
			    	    business.insert_install(entityNew);
			    	}else{
			    		business.insert_uninstall(entityNew);
			    	}
				}
			}
		 }
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
