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

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

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

@Controller
@RequestMapping("/dsp/main/dsp-banner")
public class DspBannerController extends SimpleController{
	
	@SuppressWarnings("unused")
	private static final Logger LOG = Logger.getLogger(DspBannerController.class);
	
	@Autowired
	private IDspBannerService dspBannerService;
	
	@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<DspBanner> list = new ArrayList<DspBanner>();
			String dspBannerList = (String) paramMap.get("request");
			Map<String, FieldInfo> fieldInfoMap = DspBanner.getFieldInfoForDspBanner();
			if(dspBannerList != null && !"".equals(dspBannerList)){
				Map<String,Object> mapObj = this.getDspBannerList(dspBannerList, result, list, fieldInfoMap,"add",
						Long.valueOf(paramMap.get("dspId").toString()));
				list = (List<DspBanner>) mapObj.get("list");
				result = (List<Map<String,Object>>) mapObj.get("result");
				if(!list.isEmpty()){
					dspBannerService.add(list);
					//给对接方用  只操作一条数据
					Long id = this.getDataMaxId(Long.valueOf(paramMap.get("dspId").toString()), Long.valueOf(list.get(0).getAdvertiserId()), null);
					Map<String,Object> a =  (Map<String, Object>) result.get(0).get("success");
					a.put("bannerId", id);
					/*** 新增日志 ***/
					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<DspBanner> list = new ArrayList<DspBanner>();
			String dspBannerList = (String) paramMap.get("request");
			Map<String, FieldInfo> fieldInfoMap = DspBanner.getFieldInfoForDspBanner();
			if(dspBannerList != null && !"".equals(dspBannerList)){
				Map<String,Object> mapObj = this.getDspBannerList(dspBannerList, result, list, fieldInfoMap,"edit",
						Long.valueOf(paramMap.get("dspId").toString()));
				list = (List<DspBanner>) mapObj.get("list");
				result = (List<Map<String,Object>>) mapObj.get("result");
				if(!list.isEmpty()){
					dspBannerService.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()){
			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 = dspBannerService.getAll(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 参数
	 * 				bannerIds:"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 bannerIdsStr = (String) paramMap.get("request");
			if(bannerIdsStr != null && !"".equals(bannerIdsStr)){
				try {
					//解析JSONArray
					JSONArray jsonArray = JSONArray.fromObject(bannerIdsStr);
					for (int i = 0, l = jsonArray.size(); i < l; i++) {
						JSONObject obj = jsonArray.getJSONObject(i);
						if(obj.containsKey("bannerIds") && obj.get("bannerIds") != null 
							&& !"".equals(obj.get("bannerIds"))){
							List<Long> list = new ArrayList<Long>();
							String[] ids = obj.get("bannerIds").toString().split(",");
							for (int j = 0, m = ids.length; j < m; j++) {
								list.add(Long.valueOf(ids[j]));
							}
							paramMap.put("bannerIdList", list);
							result = dspBannerService.get(paramMap);
						}else{
							result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_BANNERIDS_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 bannerIdsStr = (String) paramMap.get("request");
			if(bannerIdsStr != null && !"".equals(bannerIdsStr)){
				try {
					//解析JSONArray
					JSONArray jsonArray = JSONArray.fromObject(bannerIdsStr);
					for (int i = 0, l = jsonArray.size(); i < l; i++) {
						JSONObject obj = jsonArray.getJSONObject(i);
						if(obj.containsKey("bannerIds") && obj.get("bannerIds") != null 
							&& !"".equals(obj.get("bannerIds"))){
							List<Long> list = new ArrayList<Long>();
							String[] ids = obj.get("bannerIds").toString().split(",");
							for (int j = 0, m = ids.length; j < m; j++) {
								list.add(Long.valueOf(ids[j]));
							}
							paramMap.put("bannerIdList", list);
							result = dspBannerService.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_BANNERIDS_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 dspBannerList 广告主数据集合
	 * @param result 记录的错误描述结果
	 * @param list 没有问题的数据集合
	 * @param fieldInfoMap 字段属性
	 * @return tab 标识：添加或编辑
	 */
	private Map<String,Object> getDspBannerList(String dspBannerList, List<Map<String,Object>> result,
			List<DspBanner> list, Map<String, FieldInfo> fieldInfoMap, String tab, Long dspId){
		Map<String,Object> mapObj = new HashMap<String,Object>();
		try {
			//解析JSONArray
			JSONArray jsonArray = JSONArray.fromObject(dspBannerList);
			for (int i = 0, l = jsonArray.size(); i < l; i++) {
				boolean flag = false;
				JSONObject obj = jsonArray.getJSONObject(i);
				if(!obj.containsKey("bannerId") && "edit".equals(tab)){//编辑时，没有id这下面的代码不需要执行
					result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_BANNERID_NOT_EMPTY,false,null,(i+1),"error"));
					continue;
				}
				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();  
	                if("bannerId".equals(key)){
	                	continue;
	                }
	                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){
                	list.add((DspBanner)JSONObject.toBean(obj,DspBanner.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"));
                	}
				}
			}
		}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<DspBanner> 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("DspBanner");
			//对应表名
			log.setTableName("t_dsp_banner");
			if("add".equals(tab)){
				//增加对应的id
				Long id = this.getDataMaxId(Long.valueOf(obj.get("dspId").toString()), Long.valueOf(obj.get("advertiserId").toString()), null);
				log.setRecordId(id);
				//对应操作类型
				log.setActionType("新增");
				//对应的操作
				log.setAction("新增了一个创意，路径为：" + obj.get("path").toString());
			}else if("edit".equals(tab)){
				//增加对应的id
				log.setRecordId(Long.valueOf(obj.get("id").toString()));
				//对应操作类型
				log.setActionType("编辑");
				//对应的操作
				log.setAction("编辑原来的创意，路径为：" + obj.get("path").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
	 * @param bannerId
	 * @return 返回查询的值
	 */
	private Long getDataMaxId(Long dspId,Long advertiserId,Long bannerId){
		Map<String,Long> repeatmap = new HashMap<String,Long>();
    	repeatmap.put("dspId", dspId);
		repeatmap.put("advertiserId", advertiserId);
		repeatmap.put("bannerId", bannerId);
    	Long id = dspBannerService.selectMaxId(repeatmap);
		return id;
	}
	
	/**
	 * 添加必填字段，以防对方没有传递此参数
	 */
	private void addNotEmptyField(JSONObject obj){
		if(!obj.containsKey("path")){
			obj.put("path", "");
		}
		if(!obj.containsKey("height")){
			obj.put("height", "");
		}
		if(!obj.containsKey("width")){
			obj.put("width", "");
		}
		if(!obj.containsKey("rheight")){
			obj.put("rheight", "");
		}
		if(!obj.containsKey("rwidth")){
			obj.put("rwidth", "");
		}
	}
	
	/**
	 * 解决跨域问题,校验身份
	 */
	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;
	}
}
