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

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
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.Advertiser;
import com.cloudcross.ssp.model.Industry;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.model.Message;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.IIndustryService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.IMessageService;
import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.base.web.result.AjaxResult;
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/advertiser")
public class AdvertiserController extends SimpleController {

	@Autowired
	protected IAdvertiserService advertiserService;
	@Autowired
	private ILogService logService;
	@Autowired
	private IIndustryService industryService;
	@Autowired
	private IMessageService messageService;
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	/**
	 * @return 返回到广告主管理第一页。
	 */
	@RequestMapping
	public String index(Model model) {
		model.addAttribute("status",new Long(2));
		model.addAttribute("industryId", new Integer(0));
		return redirect(page("list"));
	}
	
	/**
	 * 
	 * @param model
	 * @param paramMap
	 * @param status 投放的状态：-1（删除）【不在界面显示】，0（正常），1（停用），2（全部）【只在界面显示】
	 * @param page
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model,@RequestParam HashMap<String, Object> paramMap,@RequestParam(defaultValue="2") int status,@RequestParam(defaultValue="1") int page) {
		try {
			String searchValue = null;
			Object obj = paramMap.get("searchValue");
			if(null != obj){
				searchValue = new String(String.valueOf(obj).trim().getBytes("ISO-8859-1"),"UTF-8");
			}
			paramMap.put("searchValue", searchValue);
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
		}
		//按状态搜索用
		if (status != 2){
			//状态为0，1，按状态查询
			paramMap.put("status", new Integer(status));
			model.addAttribute("status",new Integer(status));
		}else {
			//status为2查询所有状态
			paramMap.put("status", null);
		}
		if((String)paramMap.get("industryId")!=null && !((String)paramMap.get("industryId")).equals("0")){
			
		}else{
			paramMap.put("industryId", null);
		}
		Account account = getLoginUser();
		//这个地方要注意，如果是广告主登录系统，就直接调到对应订单的哪里。如果是代理商登录系统，就把对应的广告主显示一下！
		paramMap.put("agentId", account.getAgentId());
		int totalRow = advertiserService.countByParams(paramMap);
		
		// 查询总行数
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<Advertiser> advertiserList = advertiserService.findByParams(paramMap, pager);
		if(paramMap.get("status")==null){
			paramMap.put("status", new Integer(2));
		}
		if(paramMap.get("industryId")==null){
			paramMap.put("industryId",new Long(0));
		}
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("advertiserList", advertiserList);
		return page("list");
	}
	
	/**
	 * 广告主编辑
	 * @param request
	 * @param model
	 * @param id 广告主ID
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public String edit(HttpServletRequest request,Model model, @PathVariable long id) {
		// 根据id从数据库中查询广告主对象
		//优化：可以用一条sql来查询（待做）
		Advertiser advertiser = advertiserService.findById(id);
		Industry industry = industryService.findByIndustryId(advertiser.getIndustryId());
		model.addAttribute("industryName", industry.getName());
		model.addAttribute("sessionid", request.getSession().getId());
		model.addAttribute("advertiser", advertiser);
		return page("edit");
	}	
	/**
	 * @return 创建广告主账号。
	 */
	@RequestMapping("/create")
	public String create(HttpServletRequest request,Model model) {
		model.addAttribute("sessionid", request.getSession().getId());
		Account account = getLoginUser();
		if (account != null){
			model.addAttribute("agentId",account.getAgentId());
		}
		return page("create");
	}
	
	@RequestMapping("/update")
	public String update(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam Long advertiserId,
			@RequestParam(defaultValue = "1") int page) {
	// 查询总行数
		paramMap.put("tableName", "t_advertiser");
		paramMap.put("recordId", advertiserId);
		int totalRow = logService.countByParams(paramMap,"Advertiser");		
		Pager pager = new Pager();		
		pager.setPage(page);
		pager.setTotalRow(totalRow);	
	//向修改记录的页面传logList
		List<Log> logList = logService.findByParams(paramMap, pager,"Advertiser");
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("logList", logList);
		model.addAttribute("advertiserId", advertiserId);
		return page("update");
	}
	
	/**
	 * 添加或修改的保存
	 * @param model
	 * @param t
	 * @param request
	 * @return
	 */
	@RequestMapping("/save")
	public String save(Model model,@ModelAttribute("form") Advertiser t,HttpServletRequest request) {
		// 校验参数
	
		//添加用户
		//添加广告主ID为空
		if (t.getId() == null) {
			Account account = getLoginUser();
			if (account.getOperatorId()!=0) {
				//如果获取的当前执行操作的账号的operatorId不等于0，那么，对应的广告主也要插入不等于0的operatorId。
				t.setOperatorId(account.getOperatorId());
			}
			else {
				t.setOperatorId(new Long(0));
			}
			if (advertiserService.add(t)) {
				//添加广告主后的资质审核消息
				Message message = new Message();
				Boolean flag = ("".equals(t.getCpiPath())&&"".equals(t.getIdPath())&&"".equals(t.getLicencePath())&&"".equals(t.getOrgPath()));
				if(!flag) {
					message.setContent("有一条新的广告主资质需要审核");
					message.setType(1);//类型（1-审核，2-提现，3-其他）
					messageService.add(message);
				}

				Log log =new Log();
				log.setModule("Advertiser");//对应模块
				log.setTableName("t_advertiser");//对应的表名
				//从表中查到新增advertiser的id
				long newId= advertiserService.findByName(t.getName());
				log.setRecordId(newId);//对应广告主id
				log.setActionType("新增");
				log.setAction("新增广告主: "+t.getName());
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				log.setActionTime("100");
				log.setAccountId(Long.valueOf(getLoginUser().getId()));
				log.setUserIp(Common.toIpAddr(request));
				log.setAccountName(getLoginUser().getAccountName());
				logService.add(log);
				
				
			}
		} else {
			Advertiser formerAdvertiser = advertiserService.findById(t.getId());
			Industry formerIndustry = industryService.findByIndustryId(formerAdvertiser.getIndustryId());
			if (advertiserService.edit(t)){
				String s =t.getName()+"：";
				if (!formerAdvertiser.getName().equals(t.getName())) {
					s=s.concat("广告主名  "+formerAdvertiser.getName()+" > "+t.getName()+" / ");
					}
				
				if (!formerIndustry.getName().equals(t.getName())) {
					s=s.concat("行业  "+formerIndustry.getName()+" > "+t.getName()+" / ");
					}
				
				if (!formerAdvertiser.getHomePage().equals(t.getHomePage())) {
					s=s.concat("网址  "+formerAdvertiser.getHomePage()+" > "+t.getHomePage()+" / ");
					}
				
				if (!formerAdvertiser.getRegName().equals(t.getRegName())) {
					s=s.concat("公司名  "+formerAdvertiser.getRegName()+" > "+t.getRegName()+" ");
					}
				
				if (!formerAdvertiser.getContacts().equals(t.getContacts())) {
					s=s.concat("联系人  "+formerAdvertiser.getContacts()+" > "+t.getContacts()+" / ");
					}
				if (!formerAdvertiser.getTel().equals(t.getTel())) {
					s=s.concat("电话  "+formerAdvertiser.getTel()+" > "+t.getTel()+" / ");
					}
				
				if (!formerAdvertiser.getEmail().equals(t.getEmail())) {
					s=s.concat("邮箱  "+formerAdvertiser.getEmail()+" > "+t.getEmail()+" / ");
					}
				
				if (!formerAdvertiser.getMemo().equals(t.getMemo())) {
					s=s.concat("备注  "+formerAdvertiser.getMemo()+" > "+t.getMemo());
				}
				//如果编辑广告主成功，向log数据库中插入记录
				Log logModify= new Log();
				logModify.setModule("Advertiser");//对应模块
				logModify.setTableName("t_advertiser");//对应的表名
				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"));
	}
	@RequestMapping("enable")
	public @ResponseBody String enable(Long[] id,HttpServletRequest request) {
		Date date = null;
		if (ArrayUtils.isNotEmpty(id)) {
			List<String> list =new ArrayList<String>();
			for (int i = 0; i < id.length; i++) {
				Advertiser advertiser = advertiserService.findById(new Long(id[i]));
				list.add(advertiser.getName());
			}
			//获取当前系统时间，向后台传，确保所有的时间保持一致
			date = new Date();
			if (advertiserService.updateStatus(LangUtil.array2List(id),Status.enable.value)){
				advertiserService.updateSupdatedAll(LangUtil.array2List(id),date);
				for (int i = 0; i < list.size(); i++) {
					Log log =new Log();
					log.setModule("Advertiser");//对应模块
					log.setTableName("t_advertiser");//对应的表名
					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++) {
				Advertiser advertiser = advertiserService.findById(new Long(id[i]));
				list.add(advertiser.getName());
			}
			date = new Date();
			if( advertiserService.updateStatus(LangUtil.array2List(id),Status.disable.value) ) {
				advertiserService.updateSupdatedAll(LangUtil.array2List(id),date);
				//如果禁用订单成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log log= new Log();
				log.setModule("Advertiser");//对应模块
				log.setTableName("t_advertiser");//对应的表名
				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++) {
				Advertiser a = advertiserService.findById(new Long(id[i]));
				list.add(a.getName());
			}
			
			if(advertiserService.updateStatusAll(LangUtil.array2List(id),Status.delete.value) ) {
				//如果删除订单成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log logDel= new Log();
				logDel.setModule("Advertiser");//对应模块
				logDel.setTableName("t_advertiser");//对应的表名
				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;
	}
	
	
	//导出advertiser列表页Excel用
	
		@RequestMapping("/exportDataReportExcel")
		public void exportDataReportExcel(Model model,HttpServletRequest request,
				HttpServletResponse response,
				@RequestParam(defaultValue="2") int status,
				@RequestParam Map<String, Object> paramMap) {
				//model.addAttribute("advertiserId", advertiserId);
			//按状态搜索用
			if (status != 2){
					paramMap.put("status", new Integer(status));
			}else {
				paramMap.put("status", null);
			}
			/**
			 * 参数和list里要一样
			 */
			List<Advertiser> reportList = advertiserService.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 = "Report" + 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("advertiserName", "广告主列表");
			paramMap.put("startDate", "2015-04-01");
			paramMap.put("endDate", "2015-06-01");
			String excelOrder = templateProcessor.processTemplate("excel/advertiserDataReport.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 advertiserId) {
						model.addAttribute("advertiserId", advertiserId);
						paramMap.put("tableName", "t_advertiser");
						paramMap.put("recordId", advertiserId);
					/*
					 * 参数和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 = "advertiserModify" + 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("advertiserName", "广告主修改记录");
					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();
					}
				}
		
		
				/**
				 * 上传
				 * 创建人：周俊
				 * 创建时间：2015-10-16 11：48
				 * @return
				 */
				@RequestMapping("/fileUpload")
				@ResponseBody
				public AjaxResult fileUpload(HttpServletRequest request,HttpServletResponse response) {
					return this.advertiserService.fileUpload(request, response);
					
				}
	
	
}
