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

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * 类名称：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 ILogService logService;
	
	/**
	 * 批量添加创意
	 * @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<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");
			list = (List<DspBanner>) mapObj.get("list");
			result = (List<Map<String,Object>>) mapObj.get("result");
			if(!list.isEmpty()){
				dspBannerService.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,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		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");
			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<DspBanner> getAll(HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
		List<DspBanner> result = new ArrayList<DspBanner>();
		if(paramMap.get("dspId") != null && !"".equals(paramMap.get("dspId")) &&
				paramMap.get("advertiserIds") != null && !"".equals(paramMap.get("advertiserIds"))){
			List<Long> list = new ArrayList<Long>();
			String[] ids = paramMap.get("advertiserIds").toString().split(",");
			for (int i = 0, l = ids.length; i < l; i++) {
				list.add(Long.valueOf(ids[i]));
			}
			paramMap.put("advertiserIdList", list);
			result = dspBannerService.getAll(paramMap);
		}
		return result;		
	}
	
	/**
	 * 根据id，批量查询创意
	 * 
	 * @param paramMap 参数
	 * 				bannerIds:"1,2"  以逗号分隔的字符串
	 * @return
	 */
	@RequestMapping("/get")
	public @ResponseBody List<DspBanner> get(HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
		List<DspBanner> result = new ArrayList<DspBanner>();
		if(paramMap.get("bannerIds") != null && !"".equals(paramMap.get("bannerIds"))){
			List<Long> list = new ArrayList<Long>();
			String[] ids = paramMap.get("bannerIds").toString().split(",");
			for (int i = 0, l = ids.length; i < l; i++) {
				list.add(Long.valueOf(ids[i]));
			}
			paramMap.put("bannerIdList", list);
			result = dspBannerService.get(paramMap);
		}
		return result;		
	}
	
	/**
	 * 根据id，批量查询状态
	 * 
	 * @param paramMap 参数
	 * 				advertiserIds:"1,2"  以逗号分隔的字符串
	 * @return
	 */
	@RequestMapping("/queryState")
	public @ResponseBody List<Map<String,Object>> queryState(HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		if(paramMap.get("bannerIds") != null && !"".equals(paramMap.get("bannerIds"))){
			List<Long> list = new ArrayList<Long>();
			String[] ids = paramMap.get("bannerIds").toString().split(",");
			for (int i = 0, l = ids.length; i < l; i++) {
				list.add(Long.valueOf(ids[i]));
			}
			paramMap.put("bannerIdList", list);
			result = dspBannerService.queryState(paramMap);
			for (int i = 0, l = result.size(); i < l; i++) {
				Map<String,Object> map = result.get(i);
				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", "检查未通过");
				}
			}
		}
		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){
		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("id") && "edit".equals(tab)){//编辑时，没有id这下面的代码不需要执行
					result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_BANNERID_NOT_EMPTY,false,null,(i+1),"error"));
					continue;
				}
				if(!obj.containsKey("dspId")){//没有dspId这下面的代码不需要执行
					result.add(FieldInfo.getErrorMessage(FieldValidate.CHECK_DSPID_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();  
	                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 bannerId = null;
					if("edit".equals(tab)){
						bannerId = Long.valueOf(obj.get("id").toString());
					}
					Long id = this.getDataMaxId(Long.valueOf(obj.get("dspId").toString()), Long.valueOf(obj.get("advertiserId").toString()), bannerId);
                	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((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(new Long(getLoginUser().getId()));
			log.setUserIp(Common.toIpAddr(request));
			log.setAccountName(getLoginUser().getAccountName());
			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", "");
		}
	}
	
}
