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

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

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

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Message;
import com.cloudcross.ssp.model.OperatorBalance;
import com.cloudcross.ssp.model.RptZone;
import com.cloudcross.ssp.service.IMessageService;
import com.cloudcross.ssp.service.IOperatorBalanceService;
import com.cloudcross.ssp.service.IOperatorService;
import com.cloudcross.ssp.service.IRptZoneService;
import com.cloudcross.ssp.service.IZoneService;

/**
 * 财务管理相关的控制器
 * @author chenyou
 *
 */
@Controller("operator.financialManagementController")
@RequestMapping("/operator/main/financial/financial-management")
public class FinancialManagementController  extends SimpleController {
	private static final Logger LOG = Logger.getLogger(FinancialManagementController.class);
	
	@Autowired
	private IRptZoneService rptZoneService;
	@Autowired
	private IOperatorBalanceService operatorBalanceService;
	@Autowired
	private IOperatorService operatorService;
	@Autowired
	private IZoneService zoneService;
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	@Autowired
	private IMessageService messageService;
	/**
	 * 财务管理的列表页，默认的话不用向后端传递值，这里如果广告位id为-1表示的是要查询所有广告主的信息
	 * @param model
	 * @param paramMap 这里面应该包含两个参数，一个是广告位id,一个是选择的时间段，时间段的格式为“yyyyy-MM-dd to yyyy-MM-dd”
	 * 注意：paramMap为空值的时候表示两个参数都为默认的值，如果有一个参数有值另一个没有值则就按默认值进行查询
	 * @param page
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model, @RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue = "1") int page) {
		
		//通过当前登录用户，得到运营商id
		Account account = getLoginUser();
		Long operatorId = account.getOperatorId();
		//广告位id
		Long zoneId = null;
		String startDate = null;
		String endDate = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		/**
		 * 下面是对传递过来的两个参数进行处理，如果两个参数都为空值则两个参数都设为默认值，如果有一个参数有值另一个参数为空值，则
		 * 把空值的参数设置为默认值
		 * 广告位id的默认值为空即“null”,时间的默认值为昨天
		 */
		if(null != paramMap) {
			if(null == paramMap.get("selectedZoneId") || "".equals(paramMap.get("selectedZoneId"))) {
				zoneId = null;
			} else {
				//如果要查询的是所有广告位则让广告位id为空
				if(-1 == Long.parseLong((String)paramMap.get("selectedZoneId"))) {
					zoneId = null;
				} else {
					zoneId = Long.parseLong((String)paramMap.get("selectedZoneId"));
				}
			}
			
			if(null == paramMap.get("dateRangePicker") || "".equals(paramMap.get("dateRangePicker"))) {
				startDate = endDate = sdf.format(new Date((new Date()).getTime()
						- 24 * 60 * 60 * 1000));
			} else {
				String[] choosedDate = ((String)paramMap.get("dateRangePicker")).split("to");
					startDate = choosedDate[0].trim();
					endDate = choosedDate[1].trim();
			}
		} else {
			zoneId = null;
			startDate = endDate = sdf.format(new Date((new Date()).getTime()
					- 24 * 60 * 60 * 1000));
		}
		
		paramMap.put("zoneId", zoneId);
		paramMap.put("startDate", startDate);
		paramMap.put("endDate", endDate);
		paramMap.put("operatorId", operatorId);
		
		int totalRow = 0;
		Pager pager = null;
		pager = new Pager();
		
		// 统计符合条件的rptZone总数
		totalRow = rptZoneService.countByParams(paramMap);
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		List<RptZone> rptZoneList = rptZoneService.findByParams(paramMap, pager);
		
		if(null == paramMap.get("zoneId")) {
			paramMap.put("selectedZoneId", "-1");
		} else {
			paramMap.put("selectedZoneId", paramMap.get("zoneId"));
		}
		model.addAttribute("pager",pager);
		model.addAllAttributes(paramMap);
		model.addAttribute("rptZoneList", rptZoneList);
		 return page("list");
	}
	
	/**
	 * 
	 * @param model
	 * @param paramMap 这里面包含了提现的金额的参数，提现的金额不能小于0,还有一个可提现的金额
	 * @param page
	 * @return
	 */
	@RequestMapping("/withdraw-deposit")
	public String withdrawDeposit(Model model,@RequestParam HashMap<String, Object> paramMap) {
		
		//根据登录用户得到运营商的id
		Account account = getLoginUser();
		long operatorId = account.getOperatorId();
		paramMap.put("operatorId", operatorId);
		
		//得到从前端传递过来的提现金额
		Float money = Float.parseFloat((String)paramMap.get("money"));
		//从前端传递过来的可提现金额
		Float availableMoney = Float.parseFloat((String)paramMap.get("availableMoney"));
		
		System.out.println("chenyou:" + money);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS");
		/**
		 * 将提现的记录写进数据库
		 */
		OperatorBalance operatorBalance = new OperatorBalance();
		operatorBalance.setActTime(new Date());
		operatorBalance.setAmount(money);
		operatorBalance.setNum(sdf.format(operatorBalance.getActTime()));
		operatorBalance.setOperatorId(operatorId);
		operatorBalance.setState(1);
		//这里提现之后可提现金额就要减掉现在提现的金额
		operatorBalance.setBalance(new Float(availableMoney - money));
		operatorBalanceService.add(operatorBalance);
		
		/**
		 * 写入提现消息
		 * Author 刘向
		 */
		Message message = new Message();
		message.setContent(account.getAccountName()+"申请提现："+money+"元");
		message.setType(2);//类型（1-审核，2-提现，3-其他）
		messageService.add(message);
		
		return redirect(page("/withdraw-deposit/list"));
	}
	
	@RequestMapping("/withdraw-deposit/list")
	public String withdrawDepositList(Model model, @RequestParam(defaultValue = "1") int page) {
		
		//根据登录用户得到运营商的id
		Account account = getLoginUser();
		long operatorId = account.getOperatorId();
		
		/**
		 * 得到上一条记录的可提现金额
		 */
		Float availableMoney = operatorBalanceService.findAvailableMoney(operatorId);
		
		//如果得到的可提现金额为空，则让它为0
		if(null == availableMoney) {
			availableMoney = 0f;
		}
		
		//格式化
		DecimalFormat df = (DecimalFormat)NumberFormat.getInstance(Locale.CHINESE);
		df.applyPattern("0.00");
		
		model.addAttribute("availableMoney", df.format(availableMoney.floatValue()));
		
		/**
		 * 获取提现记录
		 */
		List<OperatorBalance> operatorBalanceList = new ArrayList<OperatorBalance>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		int totalRow = 0;
		Pager pager = null;
		pager = new Pager();
		paramMap.put("operatorId", operatorId);
		// 统计符合条件的OperatorBalance总数
		totalRow = operatorBalanceService.countByParamsOperator(paramMap);
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		operatorBalanceList = operatorBalanceService.findByParamsOperator(paramMap, pager);
		
		model.addAttribute("operatorBalanceList", operatorBalanceList);
		model.addAttribute("pager",pager);
		return page("withdraw-deposit");
	}
	
	/**
	 * 财务管理列表页的导出excel功能
	 * 前端要传递两个变量，一个为广告位变量名为selectedZoneId，一个日期变量dateRangePicker
	 * 如果没有传，则表示按默认的，广告位默认的为全部广告位，设为空值就行，日期默认为昨天
	 * @param request
	 * @param response
	 * @param paramMap
	 */
	@RequestMapping("/list/exportExcel")
	public void exportFinanceListExcel(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam Map<String, Object> paramMap) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String startDate = null;
		String endDate = null;
		// 广告位id
		Long zoneId = null;
		
		/**
		 * 下面是对传递过来的两个参数进行处理，如果两个参数都为空值则两个参数都设为默认值，如果有一个参数有值另一个参数为空值，则
		 * 把空值的参数设置为默认值 广告位id的默认值为空即“null”,时间的默认值为昨天
		 */
		if (null != paramMap) {
			if (null == paramMap.get("selectedZoneId")
					|| "".equals(paramMap.get("selectedZoneId"))) {
				zoneId = null;
			} else {
				// 如果要查询的是所有广告位则让广告位id为空
				if ("null".equals((String)paramMap.get("selectedZoneId")) || -1 == Long.parseLong((String) paramMap
						.get("selectedZoneId"))) {
					zoneId = null;
				} else {
					zoneId = Long.parseLong((String) paramMap
							.get("selectedZoneId"));
				}
			}

			if (null == paramMap.get("dateRangePicker")
					|| "".equals(paramMap.get("dateRangePicker"))) {
				startDate = endDate = sdf.format(new Date((new Date())
						.getTime() - 24 * 60 * 60 * 1000));
			} else {
				String[] choosedDate = ((String) paramMap
						.get("dateRangePicker")).split("to");
				startDate = choosedDate[0].trim();
				endDate = choosedDate[1].trim();
			}
		} else {
			zoneId = null;
			startDate = endDate = sdf.format(new Date((new Date()).getTime()
					- 24 * 60 * 60 * 1000));
		}
		
		//根据登录用户得到运营商的id
		Account account = getLoginUser();
		long operatorId = account.getOperatorId();
		paramMap.put("operatorId", operatorId);
		paramMap.put("startDate", startDate);
		paramMap.put("endDate", endDate);
		paramMap.put("zoneId", zoneId);
		List<RptZone> rptZoneList = rptZoneService.findByParams(paramMap);
		
		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 = 5;
		paramMap.put("dataSize", rptZoneList.size());
		paramMap.put("column", column);
		paramMap.put("startDate", paramMap.get("startDate"));
		paramMap.put("endDate", paramMap.get("endDate"));
		paramMap.put("dataList", rptZoneList);

		String excelTemplate = templateProcessor.processTemplate(
				"excel/financeListExcel.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	@RequestMapping("/withdraw-deposit/list/exportExcel")
	public void exportFinanceWithdrawDepositExcel(HttpServletRequest request,
			HttpServletResponse response) {
		//根据登录用户得到运营商的id
		Account account = getLoginUser();
		long operatorId = account.getOperatorId();
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("operatorId", operatorId);
		
		List<OperatorBalance> operatorBalanceList = operatorBalanceService.findByParams(paramMap);
		
		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 = 5;
		paramMap.put("dataSize", operatorBalanceList.size());
		paramMap.put("column", column);
		paramMap.put("startDate", paramMap.get("startDate"));
		paramMap.put("endDate", paramMap.get("endDate"));
		paramMap.put("dataList", operatorBalanceList);

		String excelTemplate = templateProcessor.processTemplate(
				"excel/financeWithdrawDepositExcel.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
