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

import java.io.IOException;
import java.io.PrintWriter;
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.PathVariable;
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.model.Account;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.model.Order;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.IOrderService;
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;

@Controller
@RequestMapping("/advertiser/main/ad/order")
public class OrderController extends SimpleController{
	
	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	
	@Autowired
	private ILogService logService;
	
	@Autowired
	private IAdvertiserService advertiserService;
	
	/**
	 * @return 返回到订单管理第一页。
	 */
	@RequestMapping
	public String index(Model model,@RequestParam Long advertiserId) {
		model.addAttribute("advertiserId", advertiserId);
		return redirect(page("list"));
	}
	
	@RequestMapping("/list")
	public String list(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue = "2") Integer status,
			@RequestParam(defaultValue = "1") int page) {

		Account account = getLoginUser();
		paramMap.put("agentId", account.getAgentId());
		
		//下拉框选择。默认传进来有advertiserId。 若是选择全部，advertiserId=-1 ，此时标记adMark = “全部”；
        //在mapper里面需要判断
		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);
		}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 = orderService.countByParams(paramMap);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<Order> orderList = orderService.findByParams(paramMap, pager);
		if(status==2){
			paramMap.put("status", new Long(2));
		}
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("orderList", orderList);
		return page("list");
	}
	
	
	@RequestMapping("/update")
	public String update(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam Long orderId,
			@RequestParam(defaultValue = "1") int page) {
		// 查询总行数
		paramMap.put("tableName", "t_order");
		paramMap.put("recordId", orderId);
		Order order = orderService.findById(orderId);
		model.addAttribute("advertiserId",order.getAdvertiserId() );
		int totalRow = logService.countByParams(paramMap,"Order");
	
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);		
	List<Log> logList = logService.findByParams(paramMap, pager,"Order");
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("logList", logList);
		model.addAttribute("orderId", orderId);
		model.addAttribute("order", order);
		return page("update");
	}
	
	
	/**
	 * @return 创建订单。
	 */
	@RequestMapping("/create")
	public String create(Model model, @RequestParam Long advertiserId) {
		model.addAttribute("advertiserId", advertiserId);
		Account account = getLoginUser();
		model.addAttribute("agentId", account.getAgentId());
		
		//得到该广告主的余额
		Float balance = advertiserService.findById(advertiserId).getBalance();
		model.addAttribute("balance", balance);
		
		return page("create");
	}
	
	/**
	 * 单个或者批量启用功能。
	 * 
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("enable")
	public @ResponseBody String enable(Long[] id,HttpServletRequest request) {
		Date date = null;//保存当前系统时间
		/*for (int i = 0; i < id.length; i++) {
			System.out.println("zhangbaooooorder"+id[i]);
		}*/
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到订单名称（批量或者单个都可以）__为了插入log记录的时候显示订单名称！
			List<String> list = new ArrayList<String>();
			for (int i = 0;i<id.length;i++) {
				Order order = orderService.findById(new Long(id[i]));
				list.add(order.getName());
			}
			date = new Date();
			if( orderService.updateStatus(LangUtil.array2List(id),Status.enable.value) ) {
				orderService.updateSupdatedAll(LangUtil.array2List(id),date);
				//如果开启订单成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log log= new Log();
				log.setModule("Order");//对应模块
				log.setTableName("t_order");//对应的表名
				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;
	}
	
	
	/**
	 * 单个或者批量禁用功能。 
	 * 
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("disable")
	public @ResponseBody String disable(Long[] id
			,HttpServletRequest request) {
		System.out.println("zhangbao"+id);
		Date date = null;
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到订单名称（批量或者单个都可以）___为了插入log记录的时候显示订单名称！_
			List<String> list = new ArrayList<String>();
			for (int i = 0;i < id.length;i++) {
				Order order = orderService.findById(new Long(id[i]));
				list.add(order.getName());
			}
			date = new Date();
			if( orderService.updateStatus(LangUtil.array2List(id),Status.disable.value) ) {
				
				orderService.updateSupdatedAll(LangUtil.array2List(id),date);
				//如果禁用订单成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log log= new Log();
				log.setModule("Order");//对应模块
				log.setTableName("t_order");//对应的表名
				System.out.println(id[i]+"123");
				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;
	}
	
	
	
	/**
	 * @return 保存订单，返回到订单管理。
	 */
	@RequestMapping("/save")
	public String save(Model model,@ModelAttribute("form") Order t,HttpServletRequest request) {
		model.addAttribute("advertiserId", t.getAdvertiserId());
		model.addAttribute("agentId",t.getAgentId());
		Account account = getLoginUser();
		if(t.getId() == null) {
			if (account.getOperatorId()!=0) {
				t.setOperatorId(account.getOperatorId());
			}else
			{
				t.setOperatorId(new Long(0));
			}
			if(orderService.add(t)){
				//如果添加订单成功，向log数据库中插入记录！！
				Log logAdd= new Log();
				logAdd.setModule("Order");//对应模块儿
				logAdd.setTableName("t_order");//对应的表名
				
				long newId= orderService.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 {
			Order formerOrder = orderService.findById(t.getId());
			System.out.println("!!!!"+formerOrder.getAdvertiserId());
			if (orderService.edit(t)) {
				String s =t.getName()+"：";
				if (!formerOrder.getName().equals(t.getName())) {
				s=s.concat("订单名称  "+formerOrder.getName()+" > "+t.getName()+" / ");
				}
				
				if (formerOrder.getBudget()!=(t.getBudget())) {
					s=s.concat("总预算  "+formerOrder.getBudget()+" > "+t.getBudget()+" / ");
				}
				if (!formerOrder.getComment().equals(t.getComment())) {
					s=s.concat("备注  "+formerOrder.getComment()+" > "+t.getComment());
				}
				
				//如果编辑订单成功，向log数据库中插入记录
				Log logModify= new Log();
				logModify.setModule("Order");//对应模块
				logModify.setTableName("t_order");//对应的表名
				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"));
	}
	
	/**
	 * @return 编辑订单
	 */
	@RequestMapping("/edit/{id}")
	public String edit(Model model, @PathVariable Long id) {
		Order order = orderService.findById(id);	
		model.addAttribute("order", order);
		
		//得到该广告主的余额
		Float balance = advertiserService.findById(order.getAdvertiserId()).getBalance();
		model.addAttribute("balance", balance);
		
		return page("edit");
	}
	
	/**
	 * @return 删除订单将其状态改为-1。
	 */
	@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++) {
				System.out.println("测试"+id[i]);
				Order order = orderService.findById(new Long(id[i]));
				System.out.println("测试"+order.getName());
				list.add(order.getName());
			}
			System.out.println(list);
			//____________________________________________________________________

			if( orderService.updateStatusAll(LangUtil.array2List(id),Status.delete.value) ) {
				//如果删除订单成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log logDel= new Log();
				logDel.setModule("Order");//对应模块
				logDel.setTableName("t_order");//对应的表名
				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;
	}
	
	//导出order列表页Excel用
	
	@RequestMapping("/exportDataReportExcel")
	public void exportDataReportExcel(Model model,HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam Map<String, Object> paramMap
			,@RequestParam Long advertiserId) {
			model.addAttribute("advertiserId", advertiserId);
		/**
		 * 参数和list里要一样
		 */
		List<Order> reportList = orderService.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 = "orderReport" + 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/orderReport.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 exportLogExcel(Model model,HttpServletRequest request,
					HttpServletResponse response,
					@RequestParam Map<String, Object> paramMap
					,@RequestParam Long orderId) {
					model.addAttribute("orderId", orderId);
					paramMap.put("tableName", "t_order");
					paramMap.put("recordId", orderId);
				/**
				 * 参数和list里要一样
				 */
				
				List<Log> reportList = logService.findDeliverEffectAnalysis(paramMap);
				
				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 = "orderModify" + 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();
				}
			}
	
	

}

	
	
	
	
	
	
	
	

