package com.cloudcross.ssp.back.service.impl;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudcross.ssp.back.model.Advertiser;
import com.cloudcross.ssp.back.model.DeliverAnalysis;
import com.cloudcross.ssp.back.service.IAccountService;
import com.cloudcross.ssp.back.service.IAdReportService;
import com.cloudcross.ssp.back.service.IAdvertiserService;
import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.common.utils.DateUtils;
import com.cloudcross.ssp.common.utils.MapBuilder;
import com.cloudcross.ssp.common.utils.Pager;

@Service
public class AdReportService extends ObjectBase implements IAdReportService{

	@Autowired
	private GenericIBatisDao iBatisDao;
	@Autowired
	private IAdvertiserService advertiserService;
	@Autowired
	private IAccountService accountService;
	
	@Override
	public int findCountForDeliverEffectAnalysis(Map<String, Object> paramMap) {
		return iBatisDao.get("back.adReportSqlMapper.findCountForDeliverEffectAnalysis", paramMap);
	}
	
	
	@Override
	public int findCountForDeliverEffectAnalysis2(Map<String, Object> paramMap) {
		return iBatisDao.get("back.adReportSqlMapper.findCountForDeliverEffectAnalysis2", paramMap);
	}



	
	@Override
	public int findCountForLocation(Map<String, Object> paramMap) {
		return iBatisDao.get("back.adReportSqlMapper.findCountForLocation", paramMap);
	}

	
	@Override
	public int findCountForOs(Map<String, Object> paramMap) {
		return iBatisDao.get("back.adReportSqlMapper.findCountForOs", paramMap);
	}
	
	
	@Override
	public int findCountForScene(Map<String, Object> paramMap) {
		return iBatisDao.get("back.adReportSqlMapper.findCountForScene", paramMap);
	}

	
	//list页面测试
	
	@Override
	public List<DeliverAnalysis> findByTotalReport(Map<String, Object> paramMap, Pager pager) {
		paramMap.put("pager", pager);
		return iBatisDao.getList("back.adReportSqlMapper.findByTotalReport", paramMap);
	}
	
	
	@Override
	public List<DeliverAnalysis> findByTotalReport2(
			Map<String, Object> paramMap, Pager pager) {
		paramMap.put("pager", pager);
		return iBatisDao.getList("back.adReportSqlMapper.findByTotalReport2", paramMap);
	}
	
	
	
	
	@Override
	public List<DeliverAnalysis> findByLocation(Map<String, Object> paramMap,Pager pager) {
		paramMap.put("pager", pager);
		return iBatisDao.getList("back.adReportSqlMapper.findByLocation", paramMap);
	}

	@Override
	public List<DeliverAnalysis> findByOs(Map<String, Object> paramMap,Pager pager) {
		paramMap.put("pager", pager);
		return iBatisDao.getList("back.adReportSqlMapper.findByOs", paramMap);
	}

	
	
	@Override
	public List<DeliverAnalysis> findByPlaceName(Map<String, Object> paramMap, Pager pager) {
		paramMap.put("pager", pager);
		return iBatisDao.getList("back.adReportSqlMapper.findByPlaceName", paramMap);
		
	}

	@Override
	public DeliverAnalysis findById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int countByParams(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<DeliverAnalysis> findByParams(Map<String, Object> paramMap,
			Pager pager) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean add(DeliverAnalysis t) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean edit(DeliverAnalysis t) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean updateStatus(List<Long> idList, int status) {
		// TODO Auto-generated method stub
		return false;
	}

	
	@Override
	public Map<String, Object> findCompare(Map<String, Object> paramMap) {
		
		Long advertiserId = null;
		Long agentId = null;
		
		/**
		 * 判断下是广告主，还是代理商
		 */
		if (!paramMap.containsKey("advertiserId")) {
			advertiserId = null;
		} else {
			if (paramMap.get("advertiserId") != null
					&& !"".equals(paramMap.get("advertiserId"))) {
				advertiserId = Long.parseLong((String) paramMap
						.get("advertiserId"));
			} else {
				advertiserId = null;
			}
		}
		
		
		if (!paramMap.containsKey("agentId")) {
			agentId = null;
		} else {
			if (paramMap.get("agentId") != null
					&& !"".equals(paramMap.get("agentId"))) {
				System.out.println("chenyou:paramMap" + paramMap );
				
				agentId = Long.parseLong(String.valueOf(paramMap.get("agentId")));
			} else {
				agentId = null;
			}
		}
		
		//查询用户当前余额
		//格式化
		DecimalFormat df = (DecimalFormat)NumberFormat.getInstance(Locale.CHINESE);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		df.applyPattern("0.00");
		Map<String,Object> compareMap = new HashMap<String,Object>();
		/**
		 * 先判断传递进来的是一个广告主id，还是代理商id
		 */
		if(null != advertiserId) {
			Map<String, Object> map = null;
			paramMap.put("advertiserId", advertiserId);
			Advertiser advertiser = advertiserService.findById(advertiserId);
			
			/**
			 * 下面是查找该广告主下的昨天和前天的曝光数和点击数
			 */
			paramMap.put("date", sdf.format(new Date().getTime() - 24 * 60 * 60 * 1000));
			Long yesterdayImpressionSum = null;
			Long yesterdayClickSum = null;
			
			map = findTotalImpressionAndClickByAgentId(paramMap);
			
			/**
			 * 对于查询的结果进行判断，如果m找到的结果是空的，则两个值都设为0
			 * 如果找到其中的一个值为空就把这个值设为0
			 */
			if(null == map) {
				yesterdayClickSum = new Long(0);
				yesterdayImpressionSum = new Long(0);
			} else {
				yesterdayClickSum = Long.parseLong(map.get("totalClick").toString());
				yesterdayImpressionSum = Long.parseLong(map.get("totalImpression").toString());
			}
			
			compareMap.put("totalImpression", yesterdayImpressionSum);
			compareMap.put("totalClick", yesterdayClickSum);
			
			paramMap.put("date", sdf.format(new Date().getTime() - 2 * 24 * 60 * 60 * 1000));
			Long beforeYesterdayImpressionSum = null;
			Long beforeYesterdayClickSum = null;
			map = findTotalImpressionAndClickByAgentId(paramMap);
			
			/**
			 * 对于查询的结果进行判断，如果m找到的结果是空的，则两个值都设为0
			 * 如果找到其中的一个值为空就把这个值设为0
			 */
			if(null == map) {
				beforeYesterdayClickSum = new Long(0);
				beforeYesterdayImpressionSum = new Long(0);
			} else {
				beforeYesterdayClickSum = Long.parseLong(map.get("totalClick").toString());
				beforeYesterdayImpressionSum = Long.parseLong(map.get("totalImpression").toString());
			}
			
			/**
			 * 通过比对昨天和前天的数据大小判断箭头
			 */
			if((yesterdayImpressionSum - beforeYesterdayImpressionSum) > 0) {
				compareMap.put("impressionStatus", "up");
			} else if((yesterdayImpressionSum == beforeYesterdayImpressionSum)) {
				compareMap.put("impressionStatus", "equal");
			} else {
				compareMap.put("impressionStatus", "down");
			}
			
			if((yesterdayClickSum - beforeYesterdayClickSum) > 0) {
				compareMap.put("clickStatus", "up");
			} else if((yesterdayClickSum == beforeYesterdayClickSum)) {
				compareMap.put("clickStatus", "equal");
			} else {
				compareMap.put("clickStatus", "down");
			}
			
			
			compareMap.put("balance",df.format(advertiser.getBalance()));
		}
		
		if(null != agentId) {
			paramMap.put("agentId", agentId);
			Double balance = advertiserService.sumBalanceById(paramMap);
			Map<String, Object> map = null;
			/**
			 * 下面是查找该代理商下的所有广告主的昨天和前天的曝光数和点击数
			 */
			paramMap.put("date", sdf.format(new Date().getTime() - 24 * 60 * 60 * 1000));
			
			Long yesterdayImpressionSum = null;
			Long yesterdayClickSum = null;
			map = findTotalImpressionAndClickByAgentId(paramMap);
			
			/**
			 * 对于查询的结果进行判断，如果没找到的结果是空的，则两个值都设为0
			 * 如果找到其中的一个值为空就把这个值设为0
			 */
			if(null == map) {
				yesterdayClickSum = new Long(0);
				yesterdayImpressionSum = new Long(0);
			} else {
				System.out.println("chenyou:map" + map);
				yesterdayClickSum = Long.parseLong(map.get("totalClick").toString());
				yesterdayImpressionSum = Long.parseLong(map.get("totalImpression").toString());
			}
			
			compareMap.put("totalImpression", yesterdayImpressionSum);
			compareMap.put("totalClick", yesterdayClickSum);
			
			paramMap.put("date", sdf.format(new Date().getTime() - 2 * 24 * 60 * 60 * 1000));
			Long beforeYesterdayImpressionSum = null;
			Long beforeYesterdayClickSum = null;
			map = findTotalImpressionAndClickByAgentId(paramMap);
			
			/**
			 * 对于查询的结果进行判断，如果m找到的结果是空的，则两个值都设为0
			 * 如果找到其中的一个值为空就把这个值设为0
			 */
			if(null == map) {
				beforeYesterdayClickSum = new Long(0);
				beforeYesterdayImpressionSum = new Long(0);
			} else {
				beforeYesterdayClickSum = Long.parseLong(map.get("totalClick").toString());
				beforeYesterdayImpressionSum = Long.parseLong(map.get("totalImpression").toString());
			}
			
			
			/**
			 * 通过比对昨天和前天的数据大小判断箭头
			 */
			if((yesterdayImpressionSum - beforeYesterdayImpressionSum) > 0) {
				compareMap.put("impressionStatus", "up");
			} else if((yesterdayImpressionSum == beforeYesterdayImpressionSum)) {
				compareMap.put("impressionStatus", "equal");
			} else {
				compareMap.put("impressionStatus", "down");
			}
			
			if((yesterdayClickSum - beforeYesterdayClickSum) > 0) {
				compareMap.put("clickStatus", "up");
			} else if((yesterdayClickSum == beforeYesterdayClickSum)) {
				compareMap.put("clickStatus", "equal");
			} else {
				compareMap.put("clickStatus", "down");
			}
			
			
			compareMap.put("balance",df.format(balance));
		}
		
		return compareMap;
	}
	
	
	@Override
    public List<HashMap<String, Object>> findChart(String startDate, String endDate, Long advertiserId) {
        String today = DateUtils.getCurrentFormatDate("yyyy/MM/dd");
        String yesterday = DateUtils.subtract(1, "yyyy/MM/dd");
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        
        try {
			startDate = sdf.format(sdf1.parse(startDate));
			endDate = sdf.format(sdf1.parse(endDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        //判断查询的是今天或者昨天
        if (startDate.equals(endDate) && (startDate.equals(today) || startDate.equals(yesterday))) {          
            return findChartFormRedis(advertiserId);
        } else { 
        	/**
        	 * 这里查询分为如果是以前的一段时间和以前的某一天时间
        	 */
        	if(startDate.equals(endDate)){
        		return iBatisDao.getList("back.adReportSqlMapper.findByAdvertiser1", MapBuilder.create(HashMap.class).add("startDate", startDate)
                         .add("advertiserId", advertiserId).map());
        	} else {
        		 return iBatisDao.getList("back.adReportSqlMapper.findByAdvertiser", MapBuilder.create(HashMap.class).add("startDate", startDate)
                         .add("endDate", endDate).add("advertiserId", advertiserId).map());      
        	}
  		
        }
    }
	
	
	  /**
	   * 用redis的先不做，先注释掉
	   * @param advertiserId
	   * @return
	   */
	  private List<HashMap<String, Object>> findChartFormRedis(Long advertiserId) {
		    //获取adgroup
//	        List<Map<String, Object>> adgroupList = iBatisDao.getList("back.adGroupSqlMapper.findAdgroupByAdvertiserId_Dashboard", advertiserId);
//	        
//	        List<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
//	        Jedis jedis = null;
//	        try {
//	            jedis = RedisUtils.redisPool.getResource();
//	            String today = DateUtils.getCurrentFormatDate("yyyy/MM/dd");
//	            String yesterday = DateUtils.subtract(1, "yyyy/MM/dd");
//	            String adgroupId = null;
//	            String key_today = null;
//	            String key_yesterday=null;
//	            String hour = null;
//	           
//              
//	            for (int i = 0; i < 24; i++) {
//	            	
//	                long shows_today = 0;
//	                long clicks_today = 0;
//	                double cost_today = 0;
//	                
//	                long shows_yesterday = 0;
//	                long clicks_yesterday = 0;
//	                double cost_yesterday = 0;
//	                
//	                /**
//	                 * 
//	                 */
//	                hour = String.format("%02d", i);
//	                for (Map<String, Object> map : adgroupList) {
//	                  Object  obj =  map.get("adGroupId");
//	                  
//	                  adgroupId = String.valueOf(obj);
//	                  
//	                    //获取今天数据
//	                    key_today = "solution_".concat(today).concat(hour).concat("_").concat(adgroupId);
//	                    //获取昨天数据
//	                    key_yesterday = "solution_".concat(yesterday).concat(hour).concat("_").concat(adgroupId);
//	                    	                   
//	                    try {
//	                    	
//	                    shows_today +=getLong(jedis.hget(key_today, "real_show"));
//	                    
//	                    clicks_today +=getFloat(jedis.hget(key_today, "real_click"));
//	                    
//	                    cost_today  += getDouble(jedis.hget(key_today, "real_cost"));
//	                    
//	                    
//	                    
//	                    shows_yesterday +=getLong(jedis.hget(key_yesterday, "real_show"));
//	                    
//	                    clicks_yesterday +=getLong(jedis.hget(key_yesterday, "real_click"));
//	                    
//	                    cost_yesterday  += getDouble(jedis.hget(key_yesterday, "real_cost"));
//	                    
//	                    
//	                    
//	                    } catch (Exception e) {
//	                    	
//	                    	;
//	                    }
//	                }
//	                
//	        		DecimalFormat df = (DecimalFormat)NumberFormat.getInstance(Locale.CHINESE);
//	        		df.applyPattern("0.00");
//	        		
//                  HashMap<String, Object> item = new HashMap<String, Object>();
//                  item.put("advertiserAccount", accountName);
//                  item.put("reportDate", hour);
//                  item.put("shows", shows_today);
//                  item.put("clicks", clicks_today);
//                  item.put("cost", df.format(cost_today/100.00));
//                  if (shows_today != 0) {
//                      item.put("clickRate",(double) clicks_today/shows_today);
//                  } else {
//                      item.put("clickRate", 0);
//                  }
//                  result.add(item);
//                  
//                  HashMap<String, Object> item_yesterday = new HashMap<String, Object>();
//                  item_yesterday.put("advertiserAccount2", accountName);
//                  item_yesterday.put("reportDate2", hour);
//                  item_yesterday.put("shows2", shows_yesterday);
//                  item_yesterday.put("clicks2", clicks_yesterday);
//                  item_yesterday.put("cost2", df.format(cost_yesterday/100.00));
//                  if (shows_yesterday != 0) {
//                      item_yesterday.put("clickRate2",(double) clicks_yesterday/shows_yesterday);
//                  } else {
//                      item_yesterday.put("clickRate2", 0);
//                  }                    
//                  result.add(item_yesterday);     
//                              
//	            }
//	        } catch (Exception e) {
//	        	//e.printStackTrace();
//	        } finally {
//	            if (jedis != null) {
//	                try {
//	                RedisUtils.redisPool.returnResource(jedis);
//	                }catch(Exception e){}
//	            }
//	        }	
//	        
//	        if(result.size()<=0){
//	        	List<HashMap<String, Object>> fasleData = new ArrayList<HashMap<String, Object>>();
//	        	for (int i = 0; i < 24; i++){
//	        		
//	        		String hour = String.format("%02d", i);
//	        		
//                  HashMap<String, Object> item = new HashMap<String, Object>();
//                  item.put("advertiserAccount", accountName);
//                  item.put("reportDate",hour);                    
//                  item.put("shows", 0);
//                  item.put("clicks", 0);
//                  item.put("cost", 0);
//                  item.put("clickRate", 0);
//                  
//					fasleData.add(item);
//					
//                  HashMap<String, Object> item2 = new HashMap<String, Object>();
//                  item2.put("advertiserAccount2", accountName);
//                  item2.put("reportDate2",hour); 
//                  item2.put("shows2", 0);
//                  item2.put("clicks2", 0);
//                  item2.put("cost2", 0);
//                  item2.put("clickRate2", 0); 
//                  
//                  fasleData.add(item2);
//				}	        	
//	        	return fasleData;
//	        } 
//	       
//	     
		  return null;
	  }


	@Override
	public int findCountForChart(String startDate, String endDate,
			Long advertiserId) {
		String today = DateUtils.getCurrentFormatDate("yyyy/MM/dd");
        String yesterday = DateUtils.subtract(1, "yyyy/MM/dd");
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        
        try {
			startDate = sdf.format(sdf1.parse(startDate));
			endDate = sdf.format(sdf1.parse(endDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        /**
         * 今天或昨天的没有做，这里随便返回了个值
         */
        //判断查询的是今天或者昨天
        if (startDate.equals(endDate) && (startDate.equals(today) || startDate.equals(yesterday))) {          
            return 24;
        } else { 
        	/**
        	 * 这里查询分为如果是以前的一段时间和以前的某一天时间
        	 */
        	if(startDate.equals(endDate)){
        		return iBatisDao.get("back.adReportSqlMapper.findCountForChart1", MapBuilder.create(HashMap.class).add("startDate", startDate)
                         .add("advertiserId", advertiserId).map());
        	} else {
        		 return iBatisDao.get("back.adReportSqlMapper.findCountForChart", MapBuilder.create(HashMap.class).add("startDate", startDate)
                         .add("endDate", endDate).add("advertiserId", advertiserId).map());      
        	}
  		
        }
	}


	@Override
	public List<HashMap<String, Object>> findChart(String startDate,
			String endDate, Long advertiserId, Pager pager) {
		String today = DateUtils.getCurrentFormatDate("yyyy/MM/dd");
        String yesterday = DateUtils.subtract(1, "yyyy/MM/dd");
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        
        try {
			startDate = sdf.format(sdf1.parse(startDate));
			endDate = sdf.format(sdf1.parse(endDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        //判断查询的是今天或者昨天
        if (startDate.equals(endDate) && (startDate.equals(today) || startDate.equals(yesterday))) {          
            return findChartFormRedis(advertiserId);
        } else { 
        	/**
        	 * 这里查询分为如果是以前的一段时间和以前的某一天时间
        	 */
        	if(startDate.equals(endDate)){
        		return iBatisDao.getList("back.adReportSqlMapper.findByAdvertiser2", MapBuilder.create(HashMap.class).add("startDate", startDate)
                         .add("advertiserId", advertiserId).add("pager", pager).map());
        	} else {
        		 return iBatisDao.getList("back.adReportSqlMapper.findByAdvertiser3", MapBuilder.create(HashMap.class).add("startDate", startDate)
                         .add("endDate", endDate).add("advertiserId", advertiserId).add("pager", pager).map());      
        	}
  		
        }
	}

	@Override
	public HashMap<String, Object> findTotalImpressionAndClickByAdvertiserId(
			Map<String, Object> paramMap) {
		return iBatisDao.get("back.adReportSqlMapper.findTotalImpressionAndClickByAdvertiserId", paramMap);
	}


	@Override
	public HashMap<String, Object> findTotalImpressionAndClickByAgentId(
			Map<String, Object> paramMap) {
		return iBatisDao.get("back.adReportSqlMapper.findTotalImpressionAndClickByAgentId", paramMap);
	}


	@Override
	public List<DeliverAnalysis> findByTotalReport(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return iBatisDao.getList("back.adReportSqlMapper.findByTotalForExcel", paramMap);
	}


	@Override
	public List<DeliverAnalysis> findByPlaceName(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return iBatisDao.getList("back.adReportSqlMapper.findByPlaceNameForExcel", paramMap);
	}


	@Override
	public List<DeliverAnalysis> findByLocation(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return iBatisDao.getList("back.adReportSqlMapper.findByLocationForExcel", paramMap);
	}


	@Override
	public List<DeliverAnalysis> findByOs(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return iBatisDao.getList("back.adReportSqlMapper.findByOsForExcel", paramMap);
	}

}
