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.DspAdvertiser;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.service.IDspAdvertiserService;
import com.cloudcross.ssp.service.IDspAgentService;
import com.cloudcross.ssp.service.ILogService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 类名称：DspAdvertiserController
 * 类描述：dsp-广告主
 * 创建人：rongying
 * 创建时间：2015.12.11
 *
 */

@Controller
@RequestMapping("/dsp/main/dsp-advertiser")
public class DspAdvertiserController extends SimpleController{
	
	@SuppressWarnings("unused")
	private static final Logger LOG = Logger.getLogger(DspAdvertiserController.class);
	
	@Autowired
	private IDspAdvertiserService dspAdvertiserService;
	
	@Autowired
	private IDspAgentService dspAgentService;
	
	@Autowired
	private ILogService logService;
	
	/**
	 * 批量添加广告主
	 * @param paramMap 参数，json数组
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/add")
	public @ResponseBody List<Map<String,Object>> add(HttpServletRequest request,
			HttpServletResponse response,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		/** 跨域问题 ,校验身份 **/
		result = this.checkIdentityAndCros(response, result, paramMap);
		if(result.isEmpty()){
			List<DspAdvertiser> list = new ArrayList<DspAdvertiser>();
			String dspAdvertiserList = (String) paramMap.get("request");
			Map<String, FieldInfo> fieldInfoMap = DspAdvertiser.getFieldInfoForDspAdvertiser();
			if(dspAdvertiserList != null && !"".equals(dspAdvertiserList)){
				Map<String,Object> mapObj = this.getDspAdvertiserList(dspAdvertiserList, result, list, fieldInfoMap,"add",
						Long.valueOf(paramMap.get("dspId").toString()));
				list = (List<DspAdvertiser>) mapObj.get("list");
				result = (List<Map<String,Object>>) mapObj.get("result");
				if(!list.isEmpty()){
					dspAdvertiserService.add(list);
					/*** 新增日志 ***/
					this.addLog(request, list, "add");
				}
			}else{
				result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_EMPTY,false,null,0,"error"));
			}
		}
		return result;		
	}
	
	/**
	 * 批量编辑广告主
	 * @param paramMap 参数，json数组
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/update")
	public @ResponseBody List<Map<String,Object>> update(HttpServletRequest request,
			HttpServletResponse response,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		/** 跨域问题 ,校验身份 **/
		result = this.checkIdentityAndCros(response, result, paramMap);
		if(result.isEmpty()){
			List<DspAdvertiser> list = new ArrayList<DspAdvertiser>();
			String dspAdvertiserList = (String) paramMap.get("request");
			Map<String, FieldInfo> fieldInfoMap = DspAdvertiser.getFieldInfoForDspAdvertiser();
			if(dspAdvertiserList != null && !"".equals(dspAdvertiserList)){
				Map<String,Object> mapObj = this.getDspAdvertiserList(dspAdvertiserList, result, list, fieldInfoMap,"edit",
						Long.valueOf(paramMap.get("dspId").toString()));
				list = (List<DspAdvertiser>) mapObj.get("list");
				result = (List<Map<String,Object>>) mapObj.get("result");
				if(!list.isEmpty()){
					dspAdvertiserService.update(list);
					/*** 新增日志 ***/
					this.addLog(request, list, "add");
				}
			}else{
				result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_EMPTY,false,null,0,"error"));
			}
		}
		return result;
	}
	
	/**
	 * 查询dsp账户下所有广告主
	 * @param paramMap 参数
	 * @return
	 */
	@RequestMapping("/getAll")
	public @ResponseBody List<Map<String,Object>> getAll(HttpServletRequest request,
			HttpServletResponse response,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		/** 跨域问题 ,校验身份 **/
		result = this.checkIdentityAndCros(response, result, paramMap);
		if(result.isEmpty()){
			result = dspAdvertiserService.getAll(paramMap);
		}
		return result;		
	}
	
	/**
	 * 根据id，批量查询广告主账户
	 * 
	 * @param paramMap 参数
	 * 				advertiserIds:"1,2"  以逗号分隔的字符串
	 * @return
	 */
	@RequestMapping("/get")
	public @ResponseBody List<Map<String,Object>> get(HttpServletRequest request,
			HttpServletResponse response,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		/** 跨域问题 ,校验身份 **/
		result = this.checkIdentityAndCros(response, result, paramMap);
		if(result.isEmpty()){
			String advertiserIdsStr = (String) paramMap.get("request");
			if(advertiserIdsStr != null && !"".equals(advertiserIdsStr)){
				try {
					//解析JSONArray
					JSONArray jsonArray = JSONArray.fromObject(advertiserIdsStr);
					for (int i = 0, l = jsonArray.size(); i < l; i++) {
						JSONObject obj = jsonArray.getJSONObject(i);
						if(obj.containsKey("advertiserIds") && obj.get("advertiserIds") != null 
							&& !"".equals(obj.get("advertiserIds"))){
							List<Long> list = new ArrayList<Long>();
							String[] ids = obj.get("advertiserIds").toString().split(",");
							for (int j = 0, m = ids.length; j < m; j++) {
								list.add(Long.valueOf(ids[j]));
							}
							paramMap.put("advertiserIdList", list);
							result = dspAdvertiserService.get(paramMap);
						}else{
							result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_ADVERTISERIDS_NOT_EMPTY,false,null,0,"error"));
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_FORMAT_ERROR,false,null,0,"error"));
				}
			}else{
				result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_EMPTY,false,null,0,"error"));
			}
		}
		return result;		
	}
	
	/**
	 * 根据id，批量查询状态
	 * 
	 * @param paramMap 参数
	 * 				advertiserIds:"1,2"  以逗号分隔的字符串
	 * @return
	 */
	@RequestMapping("/queryState")
	public @ResponseBody List<Map<String,Object>> queryState(HttpServletRequest request,
			HttpServletResponse response,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		/** 跨域问题 ,校验身份 **/
		result = this.checkIdentityAndCros(response, result, paramMap);
		if(result.isEmpty()){
			String advertiserIdsStr = (String) paramMap.get("request");
			if(advertiserIdsStr != null && !"".equals(advertiserIdsStr)){
				try {
					//解析JSONArray
					JSONArray jsonArray = JSONArray.fromObject(advertiserIdsStr);
					for (int i = 0, l = jsonArray.size(); i < l; i++) {
						JSONObject obj = jsonArray.getJSONObject(i);
						if(obj.containsKey("advertiserIds") && obj.get("advertiserIds") != null 
							&& !"".equals(obj.get("advertiserIds"))){
							List<Long> list = new ArrayList<Long>();
							String[] ids = obj.get("advertiserIds").toString().split(",");
							for (int j = 0, m = ids.length; j < m; j++) {
								list.add(Long.valueOf(ids[j]));
							}
							paramMap.put("advertiserIdList", list);
							result = dspAdvertiserService.queryState(paramMap);
							for (int k = 0, n = result.size(); k < n; k++) {
								Map<String,Object> map = result.get(k);
								if(Integer.parseInt(map.get("state").toString()) == 0){
									map.put("stateValue", "通过");
								}else if(Integer.parseInt(map.get("state").toString()) == 1){
									map.put("stateValue", "待检查");
								}else if(Integer.parseInt(map.get("state").toString()) == 2){
									map.put("stateValue", "检查未通过");
								}
							}
						}else{
							result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_ADVERTISERIDS_NOT_EMPTY,false,null,0,"error"));
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_FORMAT_ERROR,false,null,0,"error"));
				}
			}else{
				result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_EMPTY,false,null,0,"error"));
			}
		}
		return result;		
	}
	
	/**
	 * 解析传递的数据
	 * @param dspAdvertiserList 广告主数据集合
	 * @param result 记录的错误描述结果
	 * @param list 没有问题的数据集合
	 * @param fieldInfoMap 字段属性
	 * @return tab 标识：添加或编辑
	 */
	private Map<String,Object> getDspAdvertiserList(String dspAdvertiserList, List<Map<String,Object>> result,
			List<DspAdvertiser> list, Map<String, FieldInfo> fieldInfoMap, String tab,Long dspId){
		Map<String,Object> mapObj = new HashMap<String,Object>();
		try {
			//解析JSONArray
			JSONArray jsonArray = JSONArray.fromObject(dspAdvertiserList);
			for (int i = 0, l = jsonArray.size(); i < l; i++) {
				boolean flag = false;
				JSONObject obj = jsonArray.getJSONObject(i);
				if(!obj.containsKey("advertiserId")){//没有advertiserId这下面的代码不需要执行
					result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_ADVERTISERID_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);
	                }
	            }
				obj.put("dspId", dspId);
				if(!flag){
					if("add".equals(tab)){
						Long count = this.getDataMaxId(dspId, Long.valueOf(obj.get("advertiserId").toString()));
						if(count > 0){
                			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_ADD_REPEAT,false,null,(i+1),"error"));
						}else{
							list.add((DspAdvertiser)JSONObject.toBean(obj,DspAdvertiser.class));
	                		result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_ADD_SUCCESS,false,null,(i+1),"success"));
						}
					}
					else{
                		list.add((DspAdvertiser)JSONObject.toBean(obj,DspAdvertiser.class));
                		result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_PARAMDATA_UPDATE_SUCCESS,false,null,(i+1),"success"));
                	}
				}
			}
		}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<DspAdvertiser> 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("DspAdvertiser");
			//对应表名
			log.setTableName("t_dsp_advertiser");
			//增加对应的id
			log.setRecordId(Long.valueOf(obj.get("advertiserId").toString()));
			if("add".equals(tab)){
				//对应操作类型
				log.setActionType("新增");
				//对应的操作
				log.setAction("新增了一个广告主：" + obj.get("name").toString());
			}else if("edit".equals(tab)){
				
				//对应操作类型
				log.setActionType("编辑");
				//对应的操作
				log.setAction("编辑原有的广告主为：" + obj.get("name").toString());
			}
			//下面这几个字段目前后端数据没有得到。所以仅作测试用！
			log.setActionTime("100");
			log.setAccountId(Long.valueOf(obj.get("dspId").toString()));
			log.setUserIp(Common.toIpAddr(request));
			log.setAccountName("dsp对接方");
			logService.add(log);
		}
	}
	
	/**
	 * 获取最大的id，根据条件查询
	 * @param dspId
	 * @param advertiserId
	 * @return 返回查询的值
	 */
	private Long getDataMaxId(Long dspId,Long advertiserId){
		Map<String,Long> repeatmap = new HashMap<String,Long>();
    	repeatmap.put("dspId", dspId);
		repeatmap.put("advertiserId", advertiserId);
    	Long id = dspAdvertiserService.isRepeat(repeatmap);
		return id;
	}
	
	/**
	 * 添加必填字段，以防对方没有传递此参数
	 * @param obj
	 */
	private void addNotEmptyField(JSONObject obj){
		if(!obj.containsKey("industryId")){
			obj.put("industryId", "");
		}
		if(!obj.containsKey("name")){
			obj.put("name", "");
		}
		if(!obj.containsKey("regName")){
			obj.put("regName", "");
		}
		if(!obj.containsKey("homepage")){
			obj.put("homepage", "");
		}
		if(!obj.containsKey("tel")){
			obj.put("tel", "");
		}
		if(!obj.containsKey("email")){
			obj.put("email", "");
		}
		if(!obj.containsKey("licencePath")){
			obj.put("licencePath", "");
		}
		if(!obj.containsKey("idPath")){
			obj.put("idPath", "");
		}
		if(!obj.containsKey("orgPath")){
			obj.put("orgPath", "");
		}
		if(!obj.containsKey("cpiPath")){
			obj.put("cpiPath", "");
		}
	}
	
	/**
	 * 解决跨域问题,校验身份
	 */
	private List<Map<String,Object>> checkIdentityAndCros(HttpServletResponse response,
			List<Map<String,Object>> result,Map<String,Object> paramMap){
		response.reset();
		response.addHeader("ACCESS_CONTROL_ALLOW_ORIGIN", "*");
		response.addHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
		if(!paramMap.containsKey("dspId") || paramMap.get("dspId") == null || "".equals(paramMap.get("dspId"))){//没有dspId这下面的代码不需要执行
			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_DSPID_NOT_EMPTY,false,null,0,"error"));
			return result;
		}
		if(!paramMap.containsKey("token") || paramMap.get("token") == null || "".equals(paramMap.get("token"))){//没有dspId这下面的代码不需要执行
			result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_TOKEN_NOT_EMPTY,false,null,0,"error"));
			return result;
		}
		Long count = dspAgentService.checkIdentity(paramMap);
		if(count > 0 ){
			return result;
		}
		result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_TOKEN_NOT_CONFORM,false,null,0,"error"));
		return result;
	}
}
