package com.cloudcross.ssp.web.dsp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.consts.FieldValidate;
import com.cloudcross.ssp.common.utils.Common;
import com.cloudcross.ssp.common.utils.FieldInfo;
import com.cloudcross.ssp.model.DspAgent;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.service.IDspAgentService;
import com.cloudcross.ssp.service.ILogService;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * 类名称：DspAgentController
 * 类描述：dsp账户
 * 创建人：rongying
 * 创建时间：2015.12.11
 *
 */

@Controller
@RequestMapping("/dsp/main/dsp-agent")
public class DspAgentController extends SimpleController{
	
	@SuppressWarnings("unused")
	private static final Logger LOG = Logger.getLogger(DspAgentController.class);
	
	@Autowired
	private IDspAgentService dspAgentService;
	
	@Autowired
	private ILogService logService;
	
	/**
	 * 批量添加dsp账户
	 * @param paramMap 参数，json数组
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/add")
	public @ResponseBody List<Map<String,Object>> add(HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		List<DspAgent> list = new ArrayList<DspAgent>();
		String dspAgentList = (String) paramMap.get("request");
		Map<String, FieldInfo> fieldInfoMap = DspAgent.getFieldInfoForDspAgent();
		if(dspAgentList != null && !"".equals(dspAgentList)){
			Map<String,Object> mapObj = this.getDspAgentList(dspAgentList, result, list, fieldInfoMap,"add");
			list = (List<DspAgent>) mapObj.get("list");
			result = (List<Map<String,Object>>) mapObj.get("result");
			if(!list.isEmpty()){
				dspAgentService.add(list);
				/*** 新增日志 ***/
				this.addLog(request, list, "add");
			}
		}else{
			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_EMPTY,false,null,0,"error"));
		}
		return result;
	}
	
	/**
	 * 批量编辑dsp账户
	 * @param paramMap 参数，json数组
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/update")
	public @ResponseBody List<Map<String,Object>> update(HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		List<DspAgent> list = new ArrayList<DspAgent>();
		String dspAgentList = (String) paramMap.get("request");
		Map<String, FieldInfo> fieldInfoMap = DspAgent.getFieldInfoForDspAgent();
		if(dspAgentList != null && !"".equals(dspAgentList)){
			Map<String,Object> mapObj = this.getDspAgentList(dspAgentList, result, list, fieldInfoMap,"edit");
			list = (List<DspAgent>) mapObj.get("list");
			result = (List<Map<String,Object>>) mapObj.get("result");
			if(!list.isEmpty()){
				dspAgentService.add(list);
				/*** 新增日志 ***/
				this.addLog(request, list, "edit");
			}
		}else{
			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_EMPTY,false,null,0,"error"));
		}
		return result;
	}
	
	/**
	 * 查询所有dsp账户
	 * @param paramMap 参数
	 * @return
	 */
	@RequestMapping("/getAll")
	public @ResponseBody List<DspAgent> getAll(HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
		List<DspAgent> result = new ArrayList<DspAgent>();
		result = dspAgentService.getAll(paramMap);
		return result;		
	}
	
	/**
	 * 根据id，批量查询dsp账户
	 * 
	 * @param paramMap 参数
	 * 				dspIds:"1,2"  以逗号分隔的字符串
	 * @return
	 */
	@RequestMapping("/get")
	public @ResponseBody List<DspAgent> get(HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
		List<DspAgent> result = new ArrayList<DspAgent>();
		if(paramMap.get("dspIds") != null && !"".equals(paramMap.get("dspIds"))){
			List<Long> list = new ArrayList<Long>();
			String[] ids = paramMap.get("dspIds").toString().split(",");
			for (int i = 0, l = ids.length; i < l; i++) {
				list.add(Long.valueOf(ids[i]));
			}
			paramMap.put("idList", list);
			result = dspAgentService.get(paramMap);
		}
		return result;		
	}
	
	/**
	 * 根据id，批量查询dsp账户
	 * 
	 * @param paramMap 参数
	 * 				dspIds:"1,2"  以逗号分隔的字符串
	 * @return
	 */
	@RequestMapping("/isCheck")
	public @ResponseBody boolean isCheck(HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
		boolean success = false;
		if(paramMap.get("name") != null && !"".equals(paramMap.get("name")) &&
				paramMap.get("token") != null && !"".equals(paramMap.get("token"))){
			DspAgent dspAgent = new DspAgent();
			dspAgent.setName(String.valueOf(paramMap.get("name")));
			dspAgent.setToken(String.valueOf(paramMap.get("token")));
			int count = dspAgentService.isCheck(dspAgent);
			if(count > 0){
				success = true;
			}else{
				success = false;
			}
		}
		return success;		
	}
	
	/**
	 * 解析传递的数据
	 * @param dspAdvertiserList 广告主数据集合
	 * @param result 记录的错误描述结果
	 * @param list 没有问题的数据集合
	 * @param fieldInfoMap 字段属性
	 * @return tab 标识：添加或编辑
	 */
	private Map<String,Object> getDspAgentList(String dspAgentList, List<Map<String,Object>> result,
			List<DspAgent> list, Map<String, FieldInfo> fieldInfoMap, String tab){
		Map<String,Object> mapObj = new HashMap<String,Object>();
		try {
			//解析JSONArray
			JSONArray jsonArray = JSONArray.fromObject(dspAgentList);
			for (int i = 0, l = jsonArray.size(); i < l; i++) {
				boolean flag = false;
				JSONObject obj = jsonArray.getJSONObject(i);
				if(!obj.containsKey("id") && "edit".equals(tab)){//编辑时，没有id这下面的代码不需要执行
					result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_DSPID_NOT_EMPTY,false,null,(i+1),"error"));
					continue;
				}
				this.addNotEmptyField(obj);//如果必填字段没有传递，手动添加必填字段，值为空
				@SuppressWarnings("unchecked")
				Iterator<String> itt = obj.keys();
				while (itt.hasNext()) {
	                String key = itt.next().toString();  
	                Object value = obj.getString(key);
	                Map<String,Object> map = FieldInfo.validateField(fieldInfoMap, key, value, (i+1));
	                if(!map.isEmpty()){
	                	flag = true;
	                	result.add(map);
	                }
	            }
				if(!flag){
					Long dspId = null;
					if("edit".equals(tab)){
						dspId = Long.valueOf(obj.get("id").toString());
					}
					Long id = this.getDataMaxId(obj.get("token").toString(), obj.get("name").toString(), dspId);
                	if(id != null && id != 0){
                		if("add".equals(tab)){
                			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_ADD_REPEAT,false,null,(i+1),"error"));
                		}else{
                			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_UPDATE_REPEAT,false,null,(i+1),"error"));
                		}
                	}else{
                		list.add((DspAgent)JSONObject.toBean(obj,DspAgent.class));
                		if("add".equals(tab)){
                			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_ADD_SUCCESS,false,null,(i+1),"success"));
                		}else{
                			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_UPDATE_SUCCESS,false,null,(i+1),"success"));
                		}
                	}
				}
			}
			mapObj.put("result", result);
			mapObj.put("list", list);
		}catch (JSONException e) {
			// TODO Auto-generated catch block
			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_FORMAT_ERROR,false,null,0,"error"));
		}
		mapObj.put("result", result);
		mapObj.put("list", list);
		return mapObj;
	}
	
	/**
	 * 添加操作的日志信息
	 * @param request
	 * @param list 数据集合
	 * @param tab 标识：添加或编辑
	 */
	private void addLog(HttpServletRequest request, List<DspAgent> list, String tab){
		/*** 新增日志 ***/
		JSONArray jsonArray = JSONArray.fromObject(list);
		for (int i = 0, l = jsonArray.size(); i < l; i++) {
			JSONObject obj = jsonArray.getJSONObject(i);
			Log log = new Log();
			//对应模块
			log.setModule("DspAgent");
			//对应表名
			log.setTableName("t_dsp_agent");
			if("add".equals(tab)){
				Long id = this.getDataMaxId(obj.get("token").toString(), obj.get("name").toString(), null);
            	//增加对应的id
				log.setRecordId(id);
				//对应操作类型
				log.setActionType("新增");
				//对应的操作
				log.setAction("新增了一个dsp账户：" + obj.get("name").toString());
			}else if("edit".equals(tab)){
				//增加对应的id
				log.setRecordId(Long.valueOf(obj.get("id").toString()));
				//对应操作类型
				log.setActionType("编辑");
				//对应的操作
				log.setAction("编辑原来的dsp账户为：" + obj.get("name").toString());
			}
			//下面这几个字段目前后端数据没有得到。所以仅作测试用！
			log.setActionTime("100");
			log.setAccountId(new Long(getLoginUser().getId()));
			log.setUserIp(Common.toIpAddr(request));
			log.setAccountName(getLoginUser().getAccountName());
			logService.add(log);
		}
	}
	
	/**
	 * 获取最大的id，根据条件查询
	 * @param token
	 * @param name
	 * @return 返回查询的值
	 */
	private Long getDataMaxId(String token, String name, Long dspId){
		Map<String,Object> repeatmap = new HashMap<String,Object>();
		repeatmap.put("token", token);
		repeatmap.put("name", name);
		repeatmap.put("dspId", dspId);
    	Long id = dspAgentService.selectMaxId(repeatmap);
		return id;
	}
	
	/**
	 * 添加必填字段，以防对方没有传递此参数
	 * @param obj
	 */
	private void addNotEmptyField(JSONObject obj){
		if(!obj.containsKey("token")){
			obj.put("token", "");
		}
		if(!obj.containsKey("name")){
			obj.put("name", "");
		}
		if(!obj.containsKey("ip")){
			obj.put("ip", "");
		}
		if(!obj.containsKey("port")){
			obj.put("port", "");
		}
	}
	
}
