package com.jw.app.common.action;

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

import com.gaowj.business.action.BasicAction;
import com.gaowj.business.comp.BusinessManager;
import com.gaowj.business.exception.BusinessException;
import com.gaowj.business.util.AssertUtil;
import com.gaowj.business.util.PropUtil;
import com.gaowj.business.util.QueryParamUtil;
import com.gaowj.business.util.RequestUtils;
import com.gaowj.business.util.SessionUtil;
import com.gaowj.business.util.Status;
import com.gaowj.service.client.utils.httpClientPostData;
import com.gaowj.service.client.utils.jsonFormatMap;
import com.jw.app.business.PushDataBusiness;
import com.jw.app.business.UserBusiness;
import com.jw.app.pushData.util.PushDataUtils;

import net.sf.json.JSONObject;

public class userReceiveActAction extends BasicAction{

	/**
	 * 接收推送过来的人员信息接口
	 */
	private static final long serialVersionUID = -1537850025967330353L;
	private JSONObject jsonObject = new JSONObject();

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}
    public String receive() throws BusinessException{
    	UserBusiness business = BusinessManager.getBusiness(UserBusiness.class);
    	PushDataBusiness pushDataBusiness = BusinessManager.getBusiness(PushDataBusiness.class);
		Map<String,Object> entity = RequestUtils.getUpdateFieldMap(request, RequestUtils.UPDATEDATAFIELDPREFIX);
		try{
			List<Map<String,Object>> mylistData = AssertUtil.fromJsonString((String)entity.get("JSON"));
			mylistData = QueryParamUtil.StringToDate(mylistData);
			for(Map<String, Object> map : mylistData){
				String query = null;
				if(null != map.get("USER_ID") && null != map.get("ID_NUMBER") && null != map.get("UNIT_ID") && null != map.get("USER_NAME")){
					query = map.get("USER_ID").toString();
					System.out.println("接收到人员编号：" + query);
				}else{
					jsonObject.putAll(Status.getStatusErrorMessage("必须字段缺失!"));
					System.out.println("必须字段缺失!");
				}
				List<Map<String, Object>> retlist = business.listUserReceive(query);
				Map<String, Object> user = new HashMap<String, Object>();
				Map<String, Object> userAccount = new HashMap<String, Object>();
				Map<String, Object> userExt = new HashMap<String, Object>();
				Map<String, Object> mappush = new HashMap<String, Object>();
				List<String> listpush =  new ArrayList<String>();
				if(retlist.size() == 1){
					for(Map<String, Object> retmap : retlist){
						if(retmap.get("DELETE_FLAG").equals("0")){
							jsonObject.putAll(Status.getStatusErrorMessage("人员信息已存在！"));
							System.out.println("人员信息已存在！");
						}else {
							//更新
							user = getUser(retmap);
							userAccount = getUserAccount(retmap);
							userExt = getUserExt(retmap);
							business.update_user(user);
							business.update_user_account(userAccount);
							business.update_user_ext(userExt);
							//插入推送绑定表
							listpush.add((String) map.get("USER_ID"));
							pushDataBusiness.delete_pushApp(listpush);
							mappush = getPushAppUnit((String) map.get("USER_ID"));
							pushDataBusiness.insert_pushApp(mappush);
							//推送
							pushDataUser(map, PropUtil.getValue("clientCode","quartz_service","0000"));
							jsonObject.putAll(Status.getStatusErrorMessage("更新成功！"));
							System.out.println("更新成功！");
						}
					}	
			    }else if(retlist.size() == 0){
					//插入
			    	user = getUser(map);
					userAccount = getUserAccount(map);
					userExt = getUserExt(map);
					business.insert_user(user);
					business.insert_user_account(userAccount);
					business.insert_user_ext(userExt);
					//插入推送绑定表
					listpush.add((String) map.get("USER_ID"));
					pushDataBusiness.delete_pushApp(listpush);
					mappush = getPushAppUnit((String) map.get("USER_ID"));
					pushDataBusiness.insert_pushApp(mappush);
					//推送
					pushDataUser(map, PropUtil.getValue("clientCode","quartz_service","0000"));
					jsonObject.putAll(Status.getStatusErrorMessage("新增成功！"));
					System.out.println("新增成功！");
				}else{
					List<String> list = new ArrayList<String>();
					for(Map<String, Object> maplist : retlist){
						list.add(maplist.get("USER_ID").toString());
					}
					//删除
					business.delete_user(list);
					business.delete_user_account(list);
					business.delete_user_ext(list);
					//新增
					business.insert_user(user);
					business.insert_user_account(userAccount);
					business.insert_user_ext(userExt);
					//插入推送绑定表
					listpush.add((String) map.get("USER_ID"));
					pushDataBusiness.delete_pushApp(listpush);
					mappush = getPushAppUnit((String) map.get("USER_ID"));
					pushDataBusiness.insert_pushApp(mappush);
					//推送
					pushDataUser(map, PropUtil.getValue("clientCode","quartz_service","0000"));
					jsonObject.putAll(Status.getStatusErrorMessage("新增成功！"));
					System.out.println("新增成功！");
				}
			}
		}catch(Exception e){
			jsonObject.putAll(Status.getStatusErrorMessage("数据保存失败!"));
			System.out.println("数据保存失败!");
			e.printStackTrace();
		}
		System.out.println("接收结束......");
		return "json";
    }
    
    //人员信息归类
    public Map<String, Object> getUser(Map<String, Object> map){
    	Map<String, Object> user = new HashMap<String, Object>();
    	user.put("USER_ID", map.get("USER_ID"));
    	user.put("USER_PWD", map.get("USER_PWD"));
    	user.put("USER_NAME", map.get("USER_NAME"));
    	if(null != map.get("USER_SEX")){
    		user.put("USER_SEX", map.get("USER_SEX"));
    	}
		return user;	
    }
    
    //人员账号归类
    public Map<String, Object> getUserAccount(Map<String, Object> map){
    	Map<String, Object> userAccount = new HashMap<String, Object>();
    	userAccount.put("USER_ID", map.get("USER_ID"));
    	userAccount.put("ID_NUMBER", map.get("ID_NUMBER"));
    	userAccount.put("UNIT_ID", map.get("UNIT_ID"));
    	if(null != map.get("IS_ACTIVE")){
    		userAccount.put("IS_ACTIVE", map.get("IS_ACTIVE"));
    	}
    	if(null != map.get("BEGIN_TIME")){
    		userAccount.put("BEGIN_TIME", map.get("BEGIN_TIME"));
    	}
    	if(null != map.get("UPDATE_TIME")){
    		userAccount.put("UPDATE_TIME", map.get("UPDATE_TIME"));
    	}
    	if(null != map.get("ORDER_ID")){
    		userAccount.put("ORDER_ID", map.get("ORDER_ID"));
    	}
    	if(null != map.get("ORDER_ID")){
    		userAccount.put("ORDER_ID", map.get("ORDER_ID"));
    	}
    	userAccount.put("DELETE_FLAG", map.get("DELETE_FLAG"));
    	userAccount.put("LEAVE_FLAG", map.get("LEAVE_FLAG"));
		return userAccount;	
    }
    
    //人员信息扩展归类
    public Map<String, Object> getUserExt(Map<String, Object> map){
    	Map<String, Object> userExt = new HashMap<String, Object>();
    	userExt.put("USER_ID", map.get("USER_ID"));
    	userExt.put("MOBILE", map.get("MOBILE"));
    	if(null != map.get("CARD_ID")){
    		userExt.put("CARD_ID", map.get("CARD_ID"));
    	}
    	if(null != map.get("EMAIL")){
    		userExt.put("EMAIL", map.get("EMAIL"));
    	}
    	if(null != map.get("TELEPHONE")){
    		userExt.put("TELEPHONE", map.get("TELEPHONE"));
    	}
    	if(null != map.get("TECHNIC")){
    		userExt.put("TECHNIC", map.get("TECHNIC"));
    	}
    	if(null != map.get("POST")){
    		userExt.put("POST", map.get("POST"));
    	}
    	if(null != map.get("IS_SFZB")){
    		userExt.put("IS_SFZB", map.get("IS_SFZB"));
    	}
    	if(null != map.get("ZBLB")){
    		userExt.put("ZBLB", map.get("ZBLB"));
    	}
    	if(null != map.get("REMARK")){
    		userExt.put("REMARK", map.get("REMARK"));
    	}
		return userExt;	
    }
    
  //插入推送绑定表
    public Map<String, Object> getPushAppUnit(String userid){
    	Map<String, Object> unit = new HashMap<String, Object>();
    	unit.put("UUID", UUID.randomUUID().toString());
    	unit.put("TYPE", "1");
    	unit.put("PUSH_DATA_ID", userid);
    	unit.put("CLIENT_CODE", PropUtil.getValue("clientCode","quartz_service","0000"));
    	unit.put("CREATOR_ID", SessionUtil.getEmid());
    	unit.put("CREATE_TIME", new Date());
		return unit;	
    }
    
    //推送人员
    public void pushDataUser(Map<String,Object> map, String clientCode) throws BusinessException{
    	PushDataUtils pd = new PushDataUtils();
		String jsondata = pd.getPushUserData(map);
		PushDataBusiness business = BusinessManager.getBusiness(PushDataBusiness.class);
		List<Map<String, Object>> list = business.list_pushData_one(clientCode);
		for(Map<String, Object> url : list){
			httpClientPostData myhttp = new httpClientPostData();
			String ret = myhttp.requestSystem(
					(String)url.get("PUSH_LOGIN_URL"),
					(String)url.get("PUSH_NAME"),
					(String)url.get("PUSH_PASS"), jsondata, 
					(String)url.get("PUSH_URL"), 
					(String)url.get("PUSH_ENCODE"));
			System.out.println("输出: 推送的url:"+url.get("PUSH_URL"));
			Map<String, Object> m = null;
			if (ret != null && ret.trim().length() > 0) {
				m = jsonFormatMap.getMap(ret);
			}
			if (m != null && m.get("NAME") != null && Integer.parseInt((String) m.get("NAME")) > 0) {
				System.out.println("用户[" + url.get("EMNAME") + "]推送成功!");
				// 将成功记录插入表
				Map<String, Object> pushData = new HashMap<String, Object>();
				pushData.put("PUSH_LOGIN_URL", url.get("PUSH_LOGIN_URL"));
				pushData.put("PUSH_NAME", url.get("PUSH_NAME"));
				pushData.put("PUSH_PASS", url.get("PUSH_PASS"));
				pushData.put("PUSH_URL", url.get("PUSH_URL"));
				pushData.put("PUSH_ENCODE", url.get("PUSH_ENCODE"));
				pushData.put("CLIENT_CODE", url.get("CODE"));
				pushData.put("PUSH_DATA_ID", map.get("USER_ID"));
				pushData.put("ISFINISH", "1");
				pushData.put("CREATOR_ID", clientCode);
				pushData.put("TYPE", "1");// 类型:1=人员 2=单位
                System.out.println("-------pushdta" + pushData);
				Map<String, Object> p_query = new HashMap<String, Object>();
				p_query.put("CLIENT_CODE", pushData.get("CLIENT_CODE"));
				p_query.put("PUSH_DATA_ID", pushData.get("PUSH_DATA_ID"));
				List<Map<String, Object>> p_query_data = business.list_pushData(p_query);
				if (p_query_data == null || p_query_data.size() == 0) {
					business.insert_pushData(pushData);
				} else {
					pushData.put("UUID", p_query_data.get(0).get("UUID"));
					business.update_pushData(pushData);
				}
			} else {
				System.out.println("用户["
								+ url.get("EMNAME")
								+ "]推送失败,失败的数据将提交给作业[RemotePushUserJob],在调度任务中作定时推送!");
				// 把数据存到推送失败的临时表里
				Map<String, Object> pushData = new HashMap<String, Object>();
				pushData.put("PUSH_LOGIN_URL", url.get("PUSH_LOGIN_URL"));
				pushData.put("PUSH_NAME", url.get("PUSH_NAME"));
				pushData.put("PUSH_PASS", url.get("PUSH_PASS"));
				pushData.put("PUSH_URL", url.get("PUSH_URL"));
				pushData.put("PUSH_ENCODE", url.get("PUSH_ENCODE"));
				pushData.put("CLIENT_CODE", url.get("CODE"));
				pushData.put("PUSH_DATA_ID", map.get("USER_ID"));
				pushData.put("CREATOR_ID", clientCode);
				pushData.put("TYPE", "1");// 类型:1=人员 2=单位
				System.out.println("-------pushdta" + pushData);
				Map<String, Object> p_query = new HashMap<String, Object>();
				p_query.put("CLIENT_CODE", pushData.get("CLIENT_CODE"));
				p_query.put("PUSH_DATA_ID", pushData.get("PUSH_DATA_ID"));
				List<Map<String, Object>> p_query_data = business.list_pushData(p_query);
				if (p_query_data == null || p_query_data.size() == 0) {
					business.insert_pushData(pushData);
				} else {
					pushData.put("UUID", p_query_data.get(0).get("UUID"));
					business.update_pushData(pushData);
				}

			}
		}
    }
}
