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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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.base.web.SimpleController;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.model.Order;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.IOrderService;

@Controller("operator.orderController")
@RequestMapping("/operator/main/ad/order")
public class OrderController extends SimpleController{
	
	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private ILogService logService;
	
	/**
	 * @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 Long advertiserId,
			@RequestParam(defaultValue = "2") Integer status,
			@RequestParam(defaultValue = "1") int page) {
		model.addAttribute("advertiserId", advertiserId);
		
		if(status!=2) {
			paramMap.put("status", new Integer(status));
		}
		else {
			paramMap.put("status",null);
		}
		// 查询总行数
		int totalRow = orderService.countByParamsOperator(paramMap);
		System.out.println(totalRow);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<Order> orderList = orderService.findByParamsOperator(paramMap, pager);
		
		System.out.println("aaaa1" + orderList);
		model.addAllAttributes(paramMap);
		System.out.println(pager);
		model.addAttribute("pager", pager);
		model.addAttribute("orderList", orderList);
		model.addAttribute("advertiserId", advertiserId);
		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);
		int totalRow = logService.countByParams(paramMap,"Order");
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);		
	List<Log> logList = logService.findByParams(paramMap, pager,"Order");
	System.out.println("-------"+logList);
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("logList", logList);
		model.addAttribute("orderId", orderId);
		return page("update");
	}
	
	
	/**
	 * @return 创建订单。
	 */
	@RequestMapping("/create")
	public String create(Model model, @RequestParam Long advertiserId) {
		model.addAttribute("advertiserId", advertiserId);
		return page("create");
	}
	
	/**
	 * 单个或者批量启用功能。
	 * 
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("enable")
	public @ResponseBody String enable(Long[] id) {
		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());
			}
			if( orderService.updateStatus(LangUtil.array2List(id),Status.enable.value) ) {
				//如果开启订单成功，向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(new Long(2));
				log.setUserIp("192.168.1.145");
				log.setAccountName("香蕉");
				logService.add(log);
				}
			}
		}
		return OK;
	}
	
	/**
	 * 单个或者批量禁用功能。 
	 * 
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("disable")
	public @ResponseBody String disable(Long[] id) {
		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());
			}
			if( orderService.updateStatus(LangUtil.array2List(id),Status.disable.value) ) {
				//如果禁用订单成功，向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(new Long(1));
				log.setUserIp("192.168.1.145");
				log.setAccountName("小苹果");
			
				logService.add(log);
				}
			}
		}
		return OK;
	}
	
	
	
	/**
	 * @return 保存订单，返回到订单管理。
	 */
	@RequestMapping("/save")
	public String save(Model model,@ModelAttribute("form") Order t) {
		model.addAttribute("advertiserId", t.getAdvertiserId());
	
		if(t.getId() == null) {
			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(new Long(1));
				logAdd.setUserIp("122.123.165.11");
				logAdd.setAccountName("猴子");
				logService.add(logAdd);
			}
		}
		else {
			Order formerOrder = orderService.findById(t.getId());
			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(new Long(2));
				logModify.setUserIp("192.168.1.145");
				logModify.setAccountName("葡萄");
				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);
		return page("edit");
	}
	
	/**
	 * @return 删除订单将其状态改为-1。
	 */
	@RequestMapping("delete")
	public @ResponseBody String delete(Long[] id) {
		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.updateStatus(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(new Long(1));
				logDel.setUserIp("192.168.1.145");
				logDel.setAccountName("西瓜");
				logService.add(logDel);
				}
			}
		}
		return OK;
	}
}
