package com.cloudcross.ssp.web.advertiser.main.ad.target;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.Common;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.Campaign;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.ICampaignService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.IOrderService;

/**
 * 广告投放-活动页面控制。
 * 
 */
@Controller
@RequestMapping("/advertiser/main/ad/target/campaign")
public class CampaignController extends SimpleController {
	
    @Autowired
    private ICampaignService campaignService;
    
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
    @Autowired
	private ILogService logService;
    
    @Autowired
	private IAdvertiserService advertiserService;
    
    @Autowired
	private IOrderService orderService;
    
	@RequestMapping
	public String index(Model model, @RequestParam Long orderId) {
		//下行的命令可以删去？待验证
		model.addAttribute("orderId", orderId);
		return redirect(page("list"));
	}
	@RequestMapping("/list")
	public String list(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="2") int status,
			@RequestParam(defaultValue = "1") int page) {
		
//		paramMap.put("orderId", orderId);
//		model.addAttribute("orderId", orderId);
		
        //得到代理商Id
		Account account = getLoginUser();
		paramMap.put("agentId", account.getAgentId());
		/**
		 * 首先判断广告主选择与否，选择了的话则传一个广告主Id；再进行判断订单选择与否，同样的，选择了传一个订单Id
		 * 未进行第一层判断第二层无需判断；
		 * 未选择或者选择为空时该项值为默认或全部
		 */
		if (paramMap.get("advertiserId")!=null && !"".equals(paramMap.get("advertiserId")) 
				&& !"-1".equals(paramMap.get("advertiserId"))){
			paramMap.put("advMark", null);
			model.addAttribute("advertiserId", paramMap.get("advertiserId"));
			String advertiserName = advertiserService.selectAdvertiserNameById(Long.valueOf(paramMap.get("advertiserId").toString()));
			model.addAttribute("selectedadvertiserName", advertiserName);
			if(paramMap.get("orderId")!=null && !"".equals(paramMap.get("orderId")) 
					&& !"-1".equals(paramMap.get("orderId"))){
				paramMap.put("orderMark", null);
				model.addAttribute("orderId",paramMap.get("orderId"));
				String orderName = orderService.selectOrderNameById(Long.valueOf(paramMap.get("orderId").toString()));
				model.addAttribute("selectedorderName", orderName);
			}else {
				paramMap.put("orderId", -1l);
				paramMap.put("selectedorderName", "全部订单");
				paramMap.put("orderMark", "全部");
				System.out.println("haoshuai" + paramMap);
			}
		}else {
			paramMap.put("advertiserId", -1l);
			paramMap.put("selectedadvertiserName", "全部广告主");
			paramMap.put("advMark", "全部");
		}
		
		//状态判断
		if (status != 2) {
			paramMap.put("status", new Integer(status));
	        }else {
		paramMap.put("status", null);
	    }
		// 根据活动名称模糊查询活动总记录数。
		int totalRow = campaignService.countByParams(paramMap);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		// 根据活动名称模糊查询活动
		List<Campaign> campaignList = campaignService.findByParams(paramMap,pager);
		if(status==2){
			paramMap.put("status", new Long(2));
		}
		
		model.addAllAttributes(paramMap);
		model.addAttribute("advertiserId",paramMap.get("advertiserId"));
		model.addAttribute("pager", pager);
		model.addAttribute("campaignList", campaignList);
		return page("list");
	}
   
	@RequestMapping("/update")
	public String update(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam Long campaignId,
			@RequestParam(defaultValue = "1") int page) {
		// 查询总行数
		paramMap.put("tableName", "t_campaign");
		paramMap.put("recordId", campaignId);
		int totalRow = logService.countByParams(paramMap,"Campaign");
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);		
	List<Log> logList = logService.findByParams(paramMap, pager,"Campaign");
	 
	 Campaign c1= campaignService.findById(campaignId);
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("logList", logList);
		model.addAttribute("campaignId", campaignId);
		model.addAttribute("orderId", c1.getOrderId());
		return page("update");
	}
	
	/**
	 * @return 创建活动。
	 */
	@RequestMapping("/create")
	public String create(Model model, @RequestParam(required = false) Long orderId
			,@RequestParam(required = false) Long advertiserId) {
		model.addAttribute("advertiserId", advertiserId);
		model.addAttribute("orderId", orderId);
		//加上登录代理商Id
		Account account = getLoginUser();
		model.addAttribute("agentId", account.getAgentId());
		
		//得到该订单的总预算
		Float totalBudget = orderService.findById(orderId).getBudget();
		model.addAttribute("orderTotalBudget", totalBudget);
		return page("create");
	}
	
	
	/**
	 * 在保存对象前要验证数据是否合法,此时调试并未进行验证
	 * 
	 * @param model
	 * @return 保存成功返回"OK"
	 */
	@RequestMapping("/save")
	public String save(Model model, @ModelAttribute("form") Campaign t,
			@RequestParam String pickTime,HttpServletRequest request,
			@RequestParam Map<String, Object> paramMap) {
//		model.addAttribute("advertiserId", paramMap.get("advertiserId"));
		model.addAttribute("orderId", t.getOrderId());
		model.addAttribute("advertiserId", t.getAdvertiserId());
		model.addAttribute("agentId",t.getAgentId());
		if (t.getId() == null) {
			//选择活动的周期
			String dateRange =(String) paramMap.get("pickTime");
			
			String[] tmpDate = dateRange.split("to");
			String startDateFront = tmpDate[0].trim() + " 00:00:00";
			String endDateFront = tmpDate[1].trim() + " 23:59:59";
			java.text.SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd ");
	
			try {
				t.setActiveTime(formatter.parse(startDateFront));
			} catch (ParseException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			try {
				t.setExpireTime(formatter.parse(endDateFront));
			} catch (ParseException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}	
			try {
				//如果登录用户的operatorId不是0，那么对应的插入operatorId
				if (getLoginUser().getOperatorId()!=0) {
					t.setOperatorId(getLoginUser().getOperatorId());
				}
				else {
					t.setOperatorId(new Long(0));
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			if (campaignService.add(t)) {
				//如果添加活动成功，向log数据库中插入记录
				Log logAdd= new Log();
				logAdd.setModule("Campaign");//对应模块
				logAdd.setTableName("t_campaign");//对应的表名
				long newId = campaignService.findByName(t.getName());
				logAdd.setRecordId(newId);//对应活动id
				logAdd.setActionType("新增");
				logAdd.setAction("新增活动: "+t.getName());
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				logAdd.setActionTime("100");
				logAdd.setAccountId(Long.valueOf(getLoginUser().getId()));
				logAdd.setUserIp(Common.toIpAddr(request));
				logAdd.setAccountName(getLoginUser().getAccountName());

				logService.add(logAdd);
			}	
		}
		//下面是编辑控制
		else {
			Campaign formerCampaign = campaignService.findById(t.getId());
			//下面是得到要编辑的活动的开始日期和结束日期，传到前端
			//开始时显示的是这个日期，需要在中间加‘至’
//			model.addAttribute("activeTime",formerCampaign.getActiveTime());
//			model.addAttribute("expireTime",formerCampaign.getExpireTime());			
//			paramMap.put("activeTime",formerCampaign.getActiveTime());
//			paramMap.put("expireTime",formerCampaign.getExpireTime());
			
			//下面是得到要编辑的活动的开始日期和结束日期，传到前端
			//开始时显示的是这个日期，需要在中间加‘至’,此时的值为choosedTime
//			Date activeTime = formerCampaign.getActiveTime();
//			Date expireTime = formerCampaign.getExpireTime();
//			System.out.println("yyyyyyyyyyyyy" + activeTime);
//			String choosedTime =(String)( activeTime + "至" + expireTime);
//			model.addAttribute("choosedTime",choosedTime);
//          System.out.println("89898989898989" + choosedTime + "121212121212" + activeTime);
			
			//同样的，得到编辑后的时间周期，并将其分割
			String dateRange =(String) paramMap.get("pickTime");
			String[] tmpDate = dateRange.split("to");
			String startDateFront = tmpDate[0].trim() + " 00:00:00";
			String endDateFront = tmpDate[1].trim() + " 23:59:59";
			java.text.SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd ");	
			try {
				t.setActiveTime(formatter.parse(startDateFront));
			} catch (ParseException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			try {
				t.setExpireTime(formatter.parse(endDateFront));
			} catch (ParseException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}	
									
			if(campaignService.edit(t)) {				
				String s =t.getName()+"：";
				if (!formerCampaign.getName().equals(t.getName())) {
					s=s.concat("活动名  "+formerCampaign.getName()+" > "+t.getName()+" / ");
					}
				
				if (formerCampaign.getTotalBudget()!=(t.getTotalBudget())) {
					s=s.concat("总预算  "+formerCampaign.getTotalBudget()+" > "+t.getTotalBudget()+" / ");
					}
				
				if (formerCampaign.getDailyBudget()!=(t.getDailyBudget())) {
					s=s.concat("每日预算 "+formerCampaign.getDailyBudget()+" > "+t.getDailyBudget()+" / ");
					}
				
				if (formerCampaign.getImpression()!=(t.getImpression())) {
					s=s.concat("曝光总上限  "+formerCampaign.getImpression()+" > "+t.getImpression()+" / ");
					}
				
				if (formerCampaign.getClick()!=(t.getClick())) {
					s=s.concat("点击总上限  "+formerCampaign.getClick()+" > "+t.getClick()+" / ");
					}
				
				if (formerCampaign.getConversion()!=(t.getConversion())) {
					s=s.concat("转化总上限  "+formerCampaign.getConversion()+" > "+t.getConversion()+" / ");
					}
				
				if (formerCampaign.getDailyImpression()!=(t.getDailyImpression())) {
					s=s.concat("每日曝光上限  "+formerCampaign.getDailyImpression()+" > "+t.getDailyImpression()+" / ");
					}
				
				if (formerCampaign.getDailyClick()!=(t.getDailyClick())) {
					s=s.concat("每日点击上限  "+formerCampaign.getDailyClick()+" > "+t.getDailyClick()+" / ");
					}
				
				if (formerCampaign.getDailyConversion()!=(t.getDailyConversion())) {
					s=s.concat("每日转换上限  "+formerCampaign.getDailyConversion()+" > "+t.getDailyConversion()+" / ");
					}
				if (!formerCampaign.getMemo().equals(t.getMemo())) {
					s=s.concat("备注  "+formerCampaign.getMemo()+" > "+t.getMemo());
					}
				//如果编辑活动成功，向log数据库中插入记录
				Log logModify= new Log();
				logModify.setModule("Campaign");//对应模块
				logModify.setTableName("t_campaign");//对应的表名
				logModify.setRecordId(t.getId());//对应活动id
				logModify.setActionType("编辑");	//操作类型
				logModify.setAction(s);//变更详情
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				logModify.setActionTime("100");
				logModify.setAccountId(Long.valueOf(getLoginUser().getId()));
				logModify.setUserIp(Common.toIpAddr(request));
				logModify.setAccountName(getLoginUser().getAccountName());

				logService.add(logModify); 
			}
		}

		return redirect(page("list"));
	}
	
	
	/**
	 * @param id
	 *            活动ID
	 * @return 活动编辑页面。
	 */
	@RequestMapping("/edit")
	public String edit(Model model, @RequestParam Long id,@RequestParam Long advertiserId) {
		// 根据id从数据库中查询活动对象。
		//campaignGroup活动和advertiser广告主暂时未加入
		Campaign campaign = campaignService.findById(id);
		Long orderId = campaign.getOrderId();
		model.addAttribute("advertiserId", advertiserId);
		model.addAttribute("orderId", orderId);
		model.addAttribute("campaign", campaign);
		
		//得到该订单的总预算
		Float totalBudget = orderService.findById(orderId).getBudget();
		model.addAttribute("orderTotalBudget", totalBudget);
		
		return page("edit");
	}
	
	@RequestMapping("/enable")
	public @ResponseBody
	String enable(Long[] id,HttpServletRequest request) {
		Date date = null;
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到活动名称（批量或者单个都可以）___为了插入log记录的时候显示活动名称！_
			List<String> list = new ArrayList<String>();
			for (int i = 0;i < id.length;i++) {
				Campaign campaign = campaignService.findById(new Long(id[i]));
				list.add(campaign.getName());
			}
			date = new Date();
			if( campaignService.updateStatus(LangUtil.array2List(id),Status.enable.value) ) {
				campaignService.updateSupdatedAll(LangUtil.array2List(id),date);
				//如果禁用活动成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log log= new Log();
				log.setModule("Campaign");//对应模块
				log.setTableName("t_campaign");//对应的表名
				log.setRecordId(id[i]);//对应活动id
				log.setActionType("开启");//操作类型
				log.setAction("开启活动: "+list.get(i));//变更详情,活动名称
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				log.setActionTime("100");
				log.setAccountId(Long.valueOf(getLoginUser().getId()));
				log.setUserIp(Common.toIpAddr(request));
				log.setAccountName(getLoginUser().getAccountName());
				logService.add(log);
				}
			}
		}
		return OK;
	}

	@RequestMapping("/disable")
	public @ResponseBody String disable(Long[] id,HttpServletRequest request) {
		Date date = null;
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到活动名称（批量或者单个都可以）___为了插入log记录的时候显示活动名称！_
			List<String> list = new ArrayList<String>();
			for (int i = 0;i < id.length;i++) {
				Campaign campaign = campaignService.findById(new Long(id[i]));
				list.add(campaign.getName());
			}
			date = new Date();
			if( campaignService.updateStatus(LangUtil.array2List(id),Status.disable.value) ) {
				campaignService.updateSupdatedAll(LangUtil.array2List(id),date);
				//如果禁用活动成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log log= new Log();
				log.setModule("Campaign");//对应模块
				log.setTableName("t_campaign");//对应的表名
				log.setRecordId(id[i]);//对应活动id
				log.setActionType("停用");	//操作类型
				log.setAction("停用活动: "+list.get(i));//变更详情,活动名称
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				log.setActionTime("100");
				log.setAccountId(Long.valueOf(getLoginUser().getId()));
				log.setUserIp(Common.toIpAddr(request));
				log.setAccountName(getLoginUser().getAccountName());
				logService.add(log);
				}
			}
		}
		return OK;
	}

	@RequestMapping("/delete")
	public @ResponseBody
	String delete(Long[] id,HttpServletRequest request) {
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到活动名称（批量或者单个都可以）_________为了插入log记录的时候显示活动名称！
			List<String> list = new ArrayList<String>();
			for (int i = 0;i < id.length;i++) {
				Campaign campaign = campaignService.findById(new Long(id[i]));
				list.add(campaign.getName());
			}
			
			if( campaignService.updateStatusAll(LangUtil.array2List(id),Status.delete.value) ) {
				//如果删除活动成功，向log数据库中插入记录！
					for (int i = 0;i < id.length;i++) {
					Log logDel= new Log();
					logDel.setModule("Campaign");//对应模块
					logDel.setTableName("t_campaign");//对应的表名
					logDel.setRecordId(id[i]);//对应活动id
					logDel.setActionType("删除");	//操作类型
					logDel.setAction("删除了活动:"+list.get(i));//变更详情
					//下面这几个字段目前后端数据没有得到。所以仅作测试用！
					logDel.setActionTime("100");
					logDel.setAccountId(Long.valueOf(getLoginUser().getId()));
					logDel.setUserIp(Common.toIpAddr(request));
					logDel.setAccountName(getLoginUser().getAccountName());
					logService.add(logDel);
				}
			}
		}
		return OK;
	}
	//导出campaign列表页Excel用
	
	@RequestMapping("/exportDataReportExcel")
	public void exportReportExcel(Model model,HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam Map<String, Object> paramMap
			,@RequestParam Long orderId) {
			model.addAttribute("orderId", orderId);
		/**
		 * 参数和list里要一样
		 */
		List<Campaign> reportList = campaignService.findDeliverEffectAnalysis(paramMap);
		
		System.out.println("aaa"+reportList.toString());
		paramMap.put("dataList", reportList);
		response.reset();
		// Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
		response.setContentType("application/vnd.ms-excel;charset=utf8");
		// 设置excel文件名称
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "campaignReport" + df2.format(new Date());
		response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName + ".xls");
		// 需要对excel的列和行的总数进行指定
		int column = 9;
		paramMap.put("dataSize", reportList.size());
		paramMap.put("column", column);
		paramMap.put("campaignName", "活动表");
		paramMap.put("startDate", "2015-04-01");
		paramMap.put("endDate", "2015-06-01");
		String excelOrder = templateProcessor.processTemplate(
				"excel/campaignReport.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelOrder);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	//导出日志Excel用
	
		@RequestMapping("/exportLogExcel")
		public void exportDataReportExcel(Model model,HttpServletRequest request,
				HttpServletResponse response,
				@RequestParam Map<String, Object> paramMap
				,@RequestParam Long campaignId) {
				model.addAttribute("campaignId", campaignId);
				paramMap.put("tableName", "t_campaign");
				paramMap.put("recordId", campaignId);
			/**
			 * 参数和list里要一样
			 */
				System.out.println("aaa1"+paramMap.toString());
			List<Log> reportList = logService.findDeliverEffectAnalysis(paramMap);
			System.out.println("aaa"+reportList.toString());
			paramMap.put("dataList", reportList);
			response.reset();
			// Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
			response.setContentType("application/vnd.ms-excel;charset=utf8");
			// 设置excel文件名称
			SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = "campaignModify" + df2.format(new Date());
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName + ".xls");
			// 需要对excel的列和行的总数进行指定
			int column = 9;
			paramMap.put("dataSize", reportList.size());
			paramMap.put("column", column);
			paramMap.put("orderName", "活动修改记录");
			paramMap.put("startDate", "2015-04-01");
			paramMap.put("endDate", "2015-06-01");
			String excelOrder = templateProcessor.processTemplate(
					"excel/logReport.ftl", paramMap);
			try {
				PrintWriter out = response.getWriter();
				out.write(excelOrder);
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	
	
}
