package com.jingCaiBack.action;


import com.jingCaiBack.dao.AccountTradeDAO;
import com.jingCaiBack.dao.UserLoginDAO;
import com.jingCaiBack.model.AccountTrade;
import com.jingCaiBack.model.UserLogin;
import com.jingCaiBack.util.DateUtil;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class AccountTradeAction extends AbstractAction {
	private UserLoginDAO userLogindao = new UserLoginDAO();
	private AccountTradeDAO accountTradedao = new AccountTradeDAO();

	public ActionForward accountTradeList(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");

		String searchName = request.getParameter("searchName");
		String unionId = request.getParameter("unionId");
		UserLogin searchUser = this.userLogindao.getByName(searchName);
		int userId = 0;
		if (searchUser != null)
			userId = searchUser.getUserId();
		String tradeType = request.getParameter("tradeType");
		String startDate = request.getParameter("startDate");
		if (StringUtils.isEmpty(startDate))
			startDate = sdf3.format(new Date());
		String startTime = startDate.replaceAll("\\D+", "") + "000000";
		String endDate = request.getParameter("endDate");
		if (StringUtils.isEmpty(endDate))
			endDate = sdf3.format(new Date());
		String endTime = endDate.replaceAll("\\D+", "") + "235959";
		String serialNo = request.getParameter("serialNo");
		int page = getIntParameter(request, "page");
		if (page < 0)
			page = 1;
		int start = (page - 1) * 10;
		int end = page * 10;

		List accountTradeList = this.accountTradedao.getList(serialNo, userId,
				tradeType, start, end, startTime, endTime,unionId);
		int count = this.accountTradedao.getCount(serialNo, userId, tradeType,
				startTime, endTime,unionId);
		int pageCount = (count % 10 == 0) ? count / 10 : count / 10 + 1;
		double inComeSum = this.accountTradedao.getInComeSum(serialNo, userId,
				tradeType, startTime, endTime,unionId);
		double payOutSum = this.accountTradedao.getPayOutSum(serialNo, userId,
				tradeType, startTime, endTime,unionId);
		
		Date startdate=DateUtil.toDateFromYearMonthDayHourMinSsPattern(startTime);
		Date enddate=DateUtil.toDateFromYearMonthDayHourMinSsPattern(endTime);
		//销售金额
		double sellSum=this.accountTradedao.getSellSum(serialNo, userId, tradeType, startTime, endTime,unionId);
		//撤单金额
		double cancelSum=this.accountTradedao.getCancelSum(serialNo, userId, tradeType, startTime, endTime,unionId);
		//中奖金额
		double awardBetsSum=this.accountTradedao.getAwardBetsSum(serialNo, userId, tradeType, startTime, endTime,unionId);
		//方案提成金额
		double tcAwardBetsSum=this.accountTradedao.getTcAwardBetsSum(serialNo, userId, tradeType, startTime, endTime,unionId);
		//注册送5元的金额
		double bets1012Sum=this.accountTradedao.getBets1012Sum(startdate, enddate,unionId);
		//充值50送60元的金额
		double bets6001Sum=this.accountTradedao.getBets6001Sum(startdate, enddate,unionId);
		//管理员充值的金额
		double manmagerChongzhiSum=this.accountTradedao.getManmagerChongzhiSum(serialNo, userId, tradeType, startTime, endTime,unionId);
        //网银充值的金额
		double bankChongzhiSum=this.accountTradedao.getBankChongzhiSum(serialNo, userId, tradeType, startTime, endTime,unionId);
		//投注已经结算
		double jsSellSum=this.accountTradedao.getJsSellSum(serialNo, userId, startTime, endTime,unionId);
		//投注未结算
		double wjsSellSum=this.accountTradedao.getWjsSellSum(serialNo, userId, startTime, endTime,unionId);
		Map map=accountTradedao.getUserAccountSum();
        String balance=map.get("BALANCE").toString();
        String awardbets=map.get("AWARDBETS").toString();
        String freezedmoney= map.get("FREEZEDMONEY").toString();
        String bets_= map.get("BETS_").toString();

		DecimalFormat dfm = new DecimalFormat("##.##");
		String inSum = dfm.format(inComeSum);
		String paySum = dfm.format(payOutSum);

		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("items:[");
		if ((accountTradeList != null) && (accountTradeList.size() > 0)) {
			for (int i = 0; i < accountTradeList.size(); ++i) {
				AccountTrade accountTrade = (AccountTrade) accountTradeList
						.get(i);
				String userName = "";
				if (searchUser == null) {
					UserLogin user = this.userLogindao.getByUserId(accountTrade
							.getUserId());
					if (user != null)
						userName = user.getLoginName();
				} else {
					userName = searchName;
				}
				sb.append("{");
				sb.append("serialNo:'" + accountTrade.getSerialNo() + "',");
				sb.append("userName:'" + userName + "',");
				sb.append("inCome:'" + accountTrade.getInCome() + "',");
				sb.append("payOut:'" + accountTrade.getPayOut() + "',");
				sb.append("balance:'" + accountTrade.getBalance() + "',");
				sb.append("tradeType:'" + accountTrade.getTradeType() + "',");
				sb.append("tradeTime:'" + accountTrade.getTradeTime() + "'");
				sb.append("}");
				if (i == accountTradeList.size() - 1)
					continue;
				sb.append(",");
			}
		}

		sb.append("]");
		sb.append(",count:'" + count + "'");
		sb.append(",pageCount:'" + pageCount + "'");
		sb.append(",inComeSum:'" + new BigDecimal(inSum) + "'");
		sb.append(",payOutSum:'" + new BigDecimal(paySum) + "'");
		
		
		sb.append(",sellSum:'" + jsSellSum + "'");
		sb.append(",cancelSum:'" + cancelSum + "'");
		sb.append(",awardBetsSum:'" + awardBetsSum + "'");
		sb.append(",tcAwardBetsSum:'" + tcAwardBetsSum + "'");
		sb.append(",bets1012Sum:'" + bets1012Sum + "'");
		sb.append(",bets6001Sum:'" + bets6001Sum + "'");
		
		sb.append(",manmagerChongzhiSum:'" + manmagerChongzhiSum+ "'");
		sb.append(",bankChongzhiSum:'" + bankChongzhiSum + "'");
		
		sb.append(",balance:'" + balance + "'");
		sb.append(",awardbets:'" + awardbets + "'");
		sb.append(",freezedmoney:'" + freezedmoney + "'");
		sb.append(",bets_:'" + bets_ + "'");
		
		sb.append("}");

		nocache(response);
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(sb.toString());
		return null;
	}
	//Excel导出 左国斌 2014-5-20
	public ActionForward ExportAccountTradeList(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		   String[] tradeTypeArray = {
				"2023","22选5代购投注","2024","22选5代购追期","3026","22选5合买保底",
				"3012","22选5合买参与","3040","22选5合买个人撤单","3054","22选5合买系统撤单",
				"2007","36选7代购投注","2008","36选7代购追期","3017","36选7合买保底",
				"3003","36选7合买参与","3031","36选7合买个人撤单","3045","36选7合买系统撤单",
				"2009","4场进球彩代购投注","2010","4场进球彩代购追期","3019","4场进球彩合买保底",
				"3005","4场进球彩合买参与","3033","4场进球彩合买个人撤单","3047","4场进球彩合买系统撤单",
				"2011","6场半全场代购投注","2012","6场半全场代购追期","3020","6场半全场合买保底",
				"3006","6场半全场合买参与","3034","6场半全场合买个人撤单","3048","6场半全场合买系统撤单",
				"3084","CPS佣金转入","5013","半全场保底","5014","半全场参与",
				"5015","半全场个人撤单","3061","半全场合买保底","3081","半全场合买参与",
				"3066","半全场合买系统撤单","5016","半全场系统撤单","6003","保底奖金",
				"5005","比分保底","5006","比分参与","5007","比分个人撤单",
				"3060","比分合买保底","3080","比分合买参与","3070","比分合买个人撤单",
				"3065","比分合买系统撤单","5008","比分系统撤单","1001","充值",
				"6001","充值赠送10%","2017","大乐透代购投注","2018","大乐透代购追期",
				"3023","大乐透合买保底","3009","大乐透合买参与","3037","大乐透合买个人撤单",
				"3051","大乐透合买系统撤单","5029","大小分保底","5030","大小分参与",
				"5031","大小分个人撤单","5032","大小分系统撤单","1008","代购撤单返款",
				"6002","方案提成奖金","2021","福彩3D代购投注","2022","福彩3D代购追期",
				"3025","福彩3D合买保底","3011","福彩3D合买参与","3039","福彩3D合买个人撤单",
				"3053","福彩3D合买系统撤单","1004","管理员辅助充值","1005","管理员加奖",
				"1009","合买撤单返款","8001","加奖","2001","进球彩代购投注",
				"2002","进球彩代购追期","5038","竞彩足球混投参与","2015","排列5代购投注",
				"2016","排列5代购追期","3022","排列5合买保底","3008","排列5合买参与",
				"3036","排列5合买个人撤单","3050","排列5合买系统撤单","2029","排列三代购投注",
				"2030","排列三代购追期","3018","排列三合买保底","3004","排列三合买参与",
				"3032","排列三合买个人撤单","3046","排列三合买系统撤单","2027","七乐彩代购投注",
				"2028","七乐彩代购追期","3028","七乐彩合买保底","3014","七乐彩合买参与",
				"3042","七乐彩合买个人撤单","3056","七乐彩合买系统撤单","2013","七星彩代购投注",
				"2014","七星彩代购追期","3021","七星彩合买保底","3007","七星彩合买参与",
				"3035","七星彩合买个人撤单","3049","七星彩合买系统撤单","5021","让分胜负保底",
				"5022","让分胜负参与","5023","让分胜负个人撤单","5024","让分胜负系统撤单",
				"5034","让球胜平负参与","2005","任选9代购投注","2006","任选9代购追期",
				"3016","任选9合买保底","3002","任选9合买参与","3030","任选9合买个人撤单",
				"3044","任选9合买系统撤单","3059","上下单双合买保底","3079","上下单双合买参与",
				"3069","上下单双合买个人撤单","3064","上下单双合买系统撤单","7002","上线返点","2025","深圳风采代购投注","2026","深圳风采代购追期","3027","深圳风采合买保底","3013","深圳风采合买参与","3041","深圳风采合买个人撤单","3055","深圳风采合买系统撤单","5025","胜分差保底","5026","胜分差参与","5027","胜分差个人撤单","5028","胜分差系统撤单","5017","胜负保底","2003","胜负彩代购投注","2004","胜负彩代购追期","3015","胜负彩合买保底","3001","胜负彩合买参与","3029","胜负彩合买个人撤单","3043","胜负彩合买系统撤单","5018","胜负参与","5019","胜负个人撤单","5020","胜负系统撤单","5001","胜平负保底","5002","胜平负参与","5003","胜平负个人撤单","3058","胜平负合买保底","3078","胜平负合买参与","3068","胜平负合买个人撤单","3063","胜平负合买系统撤单","5004","胜平负系统撤单","7004","收款","2019","双色球代购投注","2020","双色球代购追期","3024","双色球合买保底","3010","猜冠军","3038","双色球合买个人撤单","3052","双色球合买系统撤单","1002","提现申请","3083","停赛退款","3085","停赛退款","7001","投注返点","1013","网银充值","1006","中奖派奖","1012","注册充值","7003","转款","5009","总进球保底","5010","总进球参与","5011","总进球个人撤单","3062","总进球数合买保底","3071","总进球数合买参与","3082","总进球数合买参与","3072","总进球数合买个人撤单","3067","总进球数系统撤单","5012","总进球系统撤单","5036","系统撤单","3099","猜冠军","9999","出票失败退款"
			};
		    
		   
		request.setCharacterEncoding("UTF-8");
		String searchName = request.getParameter("searchName");
		UserLogin searchUser = this.userLogindao.getByName(searchName);
		
		int userId = 0;
		if (searchUser != null)
			userId = searchUser.getUserId();
		String tradeType = request.getParameter("tradeType");
		String startDate = request.getParameter("startDate");
		if (StringUtils.isEmpty(startDate))
			startDate = sdf3.format(new Date());
		String startTime = startDate.replaceAll("\\D+", "") + "000000";
		String endDate = request.getParameter("endDate");
		if (StringUtils.isEmpty(endDate))
			endDate = sdf3.format(new Date());
		String endTime = endDate.replaceAll("\\D+", "") + "235959";
		String serialNo = request.getParameter("serialNo");
		
		 List<AccountTrade> accountTradeList=accountTradedao.getAllList(serialNo, userId,
					tradeType, startTime, endTime,"");
		  //导出到excel文件中attachment/inline打开方式两种
		    String filename = new String("彩票交易记录".getBytes("GBK"),"iso8859-1"); 
	        response.setContentType("application/vnd.ms-excel");
	        response.setHeader("Content-disposition",
	                "inline; filename="+filename
	                + DateUtil.toStringInYearMonthDayPattern(DateUtil
	                        .getNowPreciseToDay()) + ".xls");
	        ServletOutputStream os = response.getOutputStream();
	        WritableWorkbook workbook = Workbook.createWorkbook(os);
	        WritableSheet sheet = workbook.createSheet("日志", 0);

	        Label label = null;
	        label = new Label(0, 0, "交易流水号");
	        sheet.addCell(label);
	        label = new Label(1, 0, "用户名");
	        sheet.addCell(label);
	        label = new Label(2, 0, "收入");
	        sheet.addCell(label);
	        label = new Label(3, 0, "支出");
	        sheet.addCell(label);
	        label = new Label(4, 0, "余额");
	        sheet.addCell(label);
	        label = new Label(5, 0, "交易类型");
	        sheet.addCell(label);
	        label = new Label(6, 0, "交易时间");
	        sheet.addCell(label);

	        for (int i = 0; i < accountTradeList.size(); i++) {
	        	AccountTrade accountTrade = (AccountTrade) accountTradeList.get(i);
	            if (!accountTrade.equals(new AccountTrade())&&null!=log) {
	            	String userName = "";
					if (searchUser == null) {
						UserLogin user = this.userLogindao.getByUserId(accountTrade
								.getUserId());
						if (user != null)
							userName = user.getLoginName();
					} else {
						userName = searchName;
					}
	                //**交易流水号**
					label = new Label(0, i + 1, accountTrade.getSerialNo());
		            sheet.addCell(label);             
	                //**用户名**
	                label = new Label(1, i + 1, userName);
	                sheet.addCell(label);
	                //**收入**
	                label = new Label(2, i + 1, String.valueOf(accountTrade.getInCome()));
	                sheet.addCell(label);
	                //**支出**
	                label = new Label(3, i + 1, String.valueOf(accountTrade.getPayOut()));
	                sheet.addCell(label);  
	                //**余额**
	                label = new Label(4, i + 1, String.valueOf(accountTrade.getBalance()));
	                sheet.addCell(label); 
	                //**交易类型**
	                for (int j = 0; j < tradeTypeArray.length; j=j+2) {
	                	if(accountTrade.getTradeType().equals(tradeTypeArray[j])){
	                		label = new Label(5, i + 1, tradeTypeArray[j+1]);
	                		sheet.addCell(label); 
	                	}
	                }
	                //**交易时间**
	                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
	                Date date=sdf.parse(accountTrade.getTradeTime());
	                SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	                String time=sdf2.format(date);
	                label = new Label(6, i + 1, time);
	                sheet.addCell(label); 
	            }
	        }
	        workbook.write();
	        workbook.close();
	        os.close();
		return null;
	}

}
