package com.jw.app.common.action;

import java.sql.Timestamp;
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.UnitBusiness;
import com.jw.app.pushData.util.PushDataUtils;

import net.sf.json.JSONObject;

public class unitReceiveActAction extends BasicAction{

	/**
	 * 接收推送过来的部门接口
	 */
	private static final long serialVersionUID = 3624471794915430204L;
	private JSONObject jsonObject = new JSONObject();

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}
    public String receive() throws BusinessException{
    	UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
    	PushDataBusiness pushDataBusiness = BusinessManager.getBusiness(PushDataBusiness.class);
		Map<String,Object> entity = RequestUtils.getUpdateFieldMap(request, RequestUtils.UPDATEDATAFIELDPREFIX);
		try{
			System.out.println("部门信息接收处理......");
			List<Map<String,Object>> mylistData = AssertUtil.fromJsonString((String)entity.get("JSON"));
			mylistData = QueryParamUtil.StringToDate(mylistData);
			List<String> listpush =  new ArrayList<String>();
			Map<String, Object> mappush = new HashMap<String, Object>();
			for(Map<String, Object> map : mylistData){
				String query = null;
				if(null != map.get("UNIT_ID") && null != map.get("NAME") && null != map.get("PARENT_ID") && null != map.get("UUID")){
					query = map.get("UUID").toString();
					System.out.println("接收到的部门编号：" + query);
				}else{
					jsonObject.putAll(Status.getStatusErrorMessage("必须字段缺失!"));
					System.out.println("必须字段缺失!");
				}
				List<Map<String, Object>> retlist = business.listUnitReceive(query);
				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 {
							business.update_unit(map);
							//插入推送绑定表
							listpush.add((String) map.get("UUID"));
							pushDataBusiness.delete_pushApp(listpush);
							mappush = getPushAppUnit((String) map.get("UUID"));
							pushDataBusiness.insert_pushApp(mappush);
							//推送
							pushDataUnit(map, PropUtil.getValue("clientCode","quartz_service","0000"));
							jsonObject.putAll(Status.getStatusErrorMessage("更新成功！"));
							System.out.println("更新成功！");
						}
					}	
				}else if(retlist.size() == 0){
					business.insert_unit(map);
					//插入推送绑定表
					listpush.add((String) map.get("UUID"));
					pushDataBusiness.delete_pushApp(listpush);
					mappush = getPushAppUnit((String) map.get("UUID"));
					pushDataBusiness.insert_pushApp(mappush);
					//推送
					pushDataUnit(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("UUID").toString());
					}
					business.delete_unit(list);
					business.insert_unit(map);
					//插入推送绑定表
					listpush.add((String) map.get("UUID"));
					pushDataBusiness.delete_pushApp(listpush);
					mappush = getPushAppUnit((String) map.get("UUID"));
					pushDataBusiness.insert_pushApp(mappush);
					//推送
					pushDataUnit(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> getPushAppUnit(String uuid){
    	Map<String, Object> unit = new HashMap<String, Object>();
    	unit.put("UUID", UUID.randomUUID().toString());
    	unit.put("TYPE", "2");
    	unit.put("PUSH_DATA_ID", uuid);
    	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 pushDataUnit(Map<String,Object> map, String clientCode) throws BusinessException{
    	PushDataUtils pd = new PushDataUtils();
		String jsondata = pd.getPushUnitData(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_UNIT_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_UNIT_URL"));
				pushData.put("PUSH_ENCODE", url.get("PUSH_ENCODE"));
				pushData.put("CLIENT_CODE", url.get("CODE"));
				pushData.put("PUSH_DATA_ID", map.get("UUID"));
				pushData.put("ISFINISH", "1");
				pushData.put("CREATOR_ID", SessionUtil.getEmid());
				pushData.put("TYPE", "2");// 类型:1=人员 2=单位

				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_UNIT_URL"));
				pushData.put("PUSH_ENCODE", url.get("PUSH_ENCODE"));
				pushData.put("CLIENT_CODE", url.get("CODE"));
				pushData.put("PUSH_DATA_ID", map.get("UUID"));
				pushData.put("CREATOR_ID", SessionUtil.getEmid());
				pushData.put("TYPE", "2");// 类型:1=人员 2=单位

				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);
				}

			}
		}
		System.out.println("推送结束");
    }
}
