package com.letousky.lottery.action;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.DOMReader;
import org.dom4j.io.SAXReader;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


import com.letoula.data.util.ZHConverter;
import com.letoula.data.wozhongla.Analysis;
import com.letoula.data.wozhongla.IssueMatch;
import com.letoula.data.wozhongla.League;
import com.letoula.data.wozhongla.Leaguetable;
import com.letoula.data.wozhongla.Matchlist;
import com.letoula.data.wozhongla.Odds;
import com.letousky.connector.MessageTool;
import com.letousky.exception.LotteryException;
import com.letousky.lottery.delegate.AbstractDelegate;
import com.letousky.lottery.delegate.WinsFlat;
import com.letousky.lottery.util.AnalysisOfXmlUtil;
import com.letousky.lottery.util.OperaterCode;
import com.letousky.lottery.util.TimeUtil;

public class AuxiliaryData extends AbstractDelegate{
	
	public List guessChipin(){
		String results=helpMessage(null, "C0203");
		List list=new MessageTool().splits(results);
		
        List resultList=new ArrayList();
        
		for (int i = 0; i < list.size(); i++) {
			Map map =new HashMap();
			String[] strArray=(String[])list.get(i);
			map.put("guessChipinID", strArray[0]);//ID
			map.put("guessChipinCode", strArray[1]);//编号
			map.put("guessChipinIssue", strArray[2]);//期号
			try {
				map.put("guessChipinName", java.net.URLDecoder.decode(strArray[3],"utf-8"));//队名
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			map.put("guessChipinSpValue", strArray[4]);//赔率
			map.put("guessChipinSupport", strArray[5]);//支持率
			map.put("guessChipinStatus", strArray[6]);//状态1:出售,-1过期
			resultList.add(map);
		}
		return resultList;
	}
	
	/*
	 * 赛果开奖  足球
	 * 
	 * request   results_the_lottery.jsp
	 * */
	public List resultsTheLottery(String[] params)throws LotteryException {
		List list=new ArrayList();
		String results = helpMessage(params, OperaterCode.RESULTS_THE_LOTTERY); //赛果开奖集合
		String record=	helpMessage(new String[]{params[0]}, OperaterCode.RESULTS_LOTTERY_STRIP); //总记录数
		list.add(new MessageTool().splits(results));
		list.add(new MessageTool().split(record));
		return list;
	}
	
	/*
	 * 中奖查询
	 * 
	 * request   results_the_Zhanji.jsp
	 * */
	public List resultsZhongjiang(String[] params)throws LotteryException {
		List list=new ArrayList();
		String results = helpMessage(params, OperaterCode.GGTJ); //中奖信息集合
		String record=	helpMessage(new String[]{params[0],params[1],params[2],params[3]}, OperaterCode.GGTJ_SUM); //总记录数
		list.add(new MessageTool().splits(results));
		list.add(new MessageTool().split(record));
		return list;
	}
	/*
	 * 赛果开奖  篮球
	 * 
	 * request   results_the_lottery.jsp
	 * */
	public List resultsTheBakLottery(String[] params)throws LotteryException {
		List list=new ArrayList();
		String results = helpMessage(params, OperaterCode.RESULTS_THE_BAKLOTTERY); //赛果开奖集合
		String record=	helpMessage(new String[]{params[0]}, OperaterCode.RESULTS_THE_BAKSTRIP); //总记录数
		list.add(new MessageTool().splits(results));
		list.add(new MessageTool().split(record));
		return list;
	}
	
	/*
	 * 赛果开奖  北单
	 * 
	 * request   results_the_lottery.jsp
	 * */
	public List resultsThedcLottery(String[] params)throws LotteryException {
		String results = helpMessage(params, OperaterCode.RESULTS_THE_DCLOTTERY); //赛果开奖集合
		return new MessageTool().splits(results);
	}
	
	/*
	 * 战绩集合
	 * 
	 * request   results_the_Zhanji.jsp
	 * */
	public List resultsZhanJi(String[] params)throws LotteryException {
		List list=new ArrayList();
		String results = helpMessage(params, OperaterCode.RESULTS_USER_ZHANJI); //中奖信息集合
		String record=	helpMessage(new String[]{params[0]}, OperaterCode.RESULTS_USER_ZJSTRIP); //总记录数
		list.add(new MessageTool().splits(results));
		list.add(new MessageTool().split(record));
		return list;
	}
	
	/*
	 * 出票详情
	 * 
	 * request   results_the_tchipintemp.jsp
	 * */
	public List t_chipin_temp(String[] params)throws LotteryException {
		List list=new ArrayList();
		String results = helpMessage(params, OperaterCode.TARY_TEMP_DETAIL); //出票集合
		String record=	helpMessage(new String[]{params[0]}, OperaterCode.TARY_TEMP_DETAIL_COUNT); //总记录数
		list.add(new MessageTool().splits(results));
		list.add(new MessageTool().split(record));
		return list;
	}
	
	/*
	 * 前一天中奖查询  中奖播报
	 * 
	 * 
	 * */
	public List winsSel(String[] params)throws LotteryException {
		String results = helpMessage(params, OperaterCode.WINSITEM); //中奖信息集合
		return new MessageTool().splits(results);
	}
	
	/**
	 * 传统足球获取可销售期号
	 * @return
	 * @throws LotteryException
	 */
	public List getZucaiIssue(String[] params)throws LotteryException{
		String reuslts = helpMessage(params,OperaterCode.WINS_ISSUE_TRADE);
		return new MessageTool().splits(reuslts);
	}
	
	/**
	 * 传统足球开奖信息
	 * @return
	 * @throws LotteryException
	 */
	public String[] getZucaiKaiJiang(String[] params)throws LotteryException{
		String reuslts = helpMessage(params,OperaterCode.WINS_WIN_TRADE);
		return new MessageTool().split(reuslts);
	}
	
	/**
	 * 传统足球赛果
	 * @return
	 * @throws LotteryException
	 */
	public List ctReuslts(String[] params)throws LotteryException{
		String reuslts = helpMessage(params,OperaterCode.CT_RESULTS);
		return new MessageTool().splits(reuslts);
	}
	
	/**
	 * 竞彩足球比分
	 * @return
	 * @throws LotteryException
	 */
	public List footBallBifen(String[] params)throws LotteryException{
		String reuslts = helpMessage(params,OperaterCode.RESULTS_FOOTBALL_SCORE);
		return new MessageTool().splits(reuslts);
	}
	
	/**
	 * 北京单场比分
	 * @return
	 * @throws LotteryException
	 */
	public List footBallDcBifen(String[] params)throws LotteryException{
		String reuslts = helpMessage(params,OperaterCode.RESULTS_FOOTBALLDC_SCORE);
		return new MessageTool().splits(reuslts);
	}
	
	/**
	 * 篮球比分
	 * @return
	 * @throws LotteryException
	 */
	public List baskedBallBifen(String[] params)throws LotteryException{
		String reuslts = helpMessage(params,OperaterCode.RESULTS_BASKEDBALLDC_SCORE);
		return new MessageTool().splits(reuslts);
	}
	/**
	 * 查询当前期号
	 * @param params
	 * @return
	 * @throws LotteryException
	 */
	public String[] nowIssue(String[] params)throws LotteryException{
		String nowIssue = helpMessage(params,OperaterCode.NOW_ISSUE);
		return new MessageTool().split(nowIssue);
	}
	
	/*
	 * 首页  合买热单
	 * 
	 * request   buy_hot_Single.jsp
	 * */
	public List buyHotSingle(String[] params)throws LotteryException {
		String results = helpMessage(params, OperaterCode.BUY_HOT_SINGLE); //合买集合
		return new MessageTool().splits(results);
	}
	
	/*
	 * 首页  中奖信息
	 * 
	 * request   buy_hot_Single.jsp
	 * */
	public List buyWinningMsg(String[] params)throws LotteryException {
		String results = helpMessage(params, OperaterCode.BUY_WINNING_MSG); //中奖信息
		return new MessageTool().splits(results);
	}
	
	public List yhCommit(String[] params,HttpServletRequest request, HttpServletResponse response)throws LotteryException, UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8"); // 防止中文乱码
        response.setContentType("text/html;charset=UTF-8");
        String time = TimeUtil.getDatetoString("yyyyMMddHHmmssSSSSSS", new Date());
		String filePath ="/upload/"+ time + ".txt";
		File file = new File(filePath);
		String chipinum[] = params; 
		try {
			  OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"GBK");
			  BufferedWriter osw=new BufferedWriter(write);
			  int countPrice=0 , noteThe=0 ,money=0;
			  String chuangguan  = "";
			  String[] newKa = params[0].split("\\,");
			  String[] ArrNumber = params[1].split("\\//");
			  String[] Arrsp = params[2].split("\\//");
			  String[] ArrXh = params[3].split("\\//");
			  for(int i=0;i<newKa.length;i++){
				  StringBuffer bettingNumber = new StringBuffer();
				  String[] xh = ArrXh[i].split("\\,");
				  String[] number = ArrNumber[i].split("\\,");
				  String[] sp = Arrsp[i].split("\\,");
				  for(int j=0;j<xh.length;j++){
					  if(number[j].indexOf("-") != -1){
						  number[j] = number[j].replace("-", ":");
					  }
					  bettingNumber.append(xh[j]).append("->").append(number[j]).append(";");
				  }
				  noteThe=Integer.parseInt(newKa[i]);
				  countPrice = noteThe*2;
				  money+=countPrice;
				  chuangguan = number.length+"_1";
				  bettingNumber.deleteCharAt(bettingNumber.lastIndexOf(";"));
				  osw.write(bettingNumber+"\t"+noteThe+"\t"+countPrice+"\t"+chuangguan+"\n");
			  }
			osw.close();
			write.close();
			String[] chipin={null,null,params[5],"unkonw",params[4],"优化投注","优化投注","1","all","1","0",String.valueOf(money),"1",String.valueOf(money),String.valueOf(money),"1","0",filePath,"1","spValue","0-0"};
			List list = new WinsFlat().betting(request, response, chipin);
			return list;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  
		return null;
	}
	/*
	 * 首页  中奖信息累计中奖
	 * 
	 * request   buy_hot_Single.jsp
	 * */
	public String[] buyWinningLJZ(String[] params)throws LotteryException {
		String results = helpMessage(params, OperaterCode.BUY_WINNING_LJZ); //中奖信息
		return new MessageTool().split(results);
	}
	
	/*
	 * 联赛资料   赛事/赛果
	 * 
	 * request league_target.jsp
	 * */
	public String league_target(String date, String startDate, String endDate, String lid){
		String market = new League().execute(date,startDate,endDate,lid);
		return market;
	}
	
	public String Leaguetable_target(String lid, String levelid, String groupid,String sid){
		String market = new Leaguetable().execute(lid,levelid,groupid,sid);
		return market;
	}
	
	/*
	 * 赛程/赛果
	 * */
	public String Matchlist_target(String date, String startDate, String endDate, String lid){
		String market = new Matchlist().execute(date,startDate,endDate,lid);
		return market;
	}
	
	/*
	 * 期次对应场次接口
	 * */
	public String Issue_Match_target(String type, String lotNum){
		String market = new IssueMatch().execute(type,lotNum);
		return market;
	}
	
	/*
	 * 赔率
	 * 
	public String Odds_target(String date){
		JSONObject obj = new MatchAction().getInstantOdds(OperaterCode.DOM_URL+"target=odds&date=2011-8-16");
		return obj.toString();
	}*/
	/*
	 * 赛事分析接口
	 * */
	public  String Analysis_target(String type,String lotNum,String target,String no){
		
		
		String xmlMatch = OperaterCode.DOM_URL+"target="+target+"&type="+type+"&lotNum="+lotNum;
		System.out.println(xmlMatch);
		String market ="",match_d=",";
		StringBuffer str_b= new StringBuffer("{items:[");
		DocumentBuilderFactory documentBF = DocumentBuilderFactory.newInstance();
		documentBF.setNamespaceAware(true);
		try {
			DocumentBuilder documentB = documentBF.newDocumentBuilder();
			InputStream inputStream = getSoapInputStream(xmlMatch);
			Document doc=(Document) documentB.parse(inputStream);
			inputStream.close();
			DOMReader reader = new  DOMReader();
			org.dom4j.Document domDoc=reader.read(doc);
			List match_list=domDoc.selectNodes("/root/match");

			for(Iterator match_it = match_list.iterator();match_it.hasNext();){
				Element el= (Element) match_it.next();
				
				if(no.equals(el.attribute("no").getValue())){
					
					str_b.append("{match_id:\""+el.attribute("id").getValue()+"\","+
							"no:\""+el.attribute("no").getValue()+"\","+"lid:\""+el.attribute("lid").getValue()+"\","+
							"ln:\""+el.attribute("ln").getValue()+"\","+"levelId:\""+el.attribute("levelId").getValue()+"\","+
							"levelName:\""+el.attribute("levelName").getValue()+"\","+"roundNum:\""+el.attribute("roundNum").getValue()+"\","+
							"hid:\""+el.attribute("hid").getValue()+"\","+"hn:\""+el.attribute("hn").getValue()+"\","+
							"aid:\""+el.attribute("aid").getValue()+"\","+"an:\""+el.attribute("an").getValue()+"\","+
							"dt:\""+el.attribute("dt").getValue()+"\","+"st:\""+el.attribute("st").getValue()+"\","+
							"hs:\""+el.attribute("hs").getValue()+"\","+"as:\""+el.attribute("as").getValue()+"\","+
							"ot:\""+el.attribute("ot").getValue()+"\","+"hostOdds:\""+el.attribute("hostOdds").getValue()+"\","+
							"vsOdds:\""+el.attribute("vsOdds").getValue()+"\","+"visitOdds:\""+el.attribute("visitOdds").getValue()+"\","+
							"hand:\""+el.attribute("hand").getValue()+"\","+"sp:\""+el.attribute("sp").getValue()+"\","+
							"updateTime:\""+el.attribute("updateTime").getValue()+"\","+"hhs:\""+el.attribute("hhs").getValue()+"\","+
							"ahs:\""+el.attribute("ahs").getValue()+"\","+
							"ht:\""+el.attribute("ht").getValue()+"\"");
					str_b.append("}]}");
					
					String oddsUrl = OperaterCode.DOM_URL+"target=odds&mid="+el.attribute("id").getValue();
					String leagueUrl = OperaterCode.DOM_URL+"target=leaguetable&lid="+el.attribute("lid").getValue()+"&levelid=1&groupid=99&sid=2012";
					String aysUrl = OperaterCode.DOM_URL+"target=analysis&mid="+el.attribute("id").getValue();
					
					String odds = documentDoc(oddsUrl);
					String league = documentDoc(leagueUrl);
					String analysis = documentDoc(aysUrl);
					String hid=el.attribute("hid").getValue()+","+el.attribute("aid").getValue()+","+el.attribute("ln").getValue();
					
					market += odds+"%";  //即时赔率
					market += league+"%"; //联赛积分
					market += analysis+"%"+str_b+"%"; //对战
					market += hid;
		
				}
				
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return market;
	}

	/*
	 * 请求我中啦数据 返回xml字符串
	 * */
public static String documentDoc(String url){
	DocumentBuilderFactory documentBF = DocumentBuilderFactory.newInstance();
	documentBF.setNamespaceAware(true);
	DocumentBuilder documentB;
	try {
		documentB = documentBF.newDocumentBuilder();
		InputStream inputStream = getSoapInputStream(url);
		Document doc=(Document) documentB.parse(inputStream);
		inputStream.close();
		DOMReader reader = new  DOMReader();
		org.dom4j.Document domDoc=reader.read(doc);
		return ZHConverter.to(ZHConverter.SIMPLIFIED, domDoc.asXML().replaceAll("\n",""));
	} catch (ParserConfigurationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SAXException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return "";
}
public static InputStream getSoapInputStream(String url){
		InputStream inputStream = null;
		try {
			URL urlObj = new URL(url);
			URLConnection conn = urlObj.openConnection();
			conn.setRequestProperty("Host", OperaterCode.SERVICES_HOST);
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.connect();
			inputStream=conn.getInputStream();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inputStream;
	} 

  public int formatTime(int basicDate,int n){
	 String ist = String.valueOf(basicDate).substring(0,4) + "-" + String.valueOf(basicDate).substring(4,6) + "-" + String.valueOf(basicDate).substring(6,8);
	 SimpleDateFormat   df   =   new   SimpleDateFormat("yyyy-MM-dd");  
     Date   tmpDate   =   null;  
     try   {  
         tmpDate   =   df.parse(ist);  
     }  
     catch(Exception   e){  
         //   日期型字符串格式错误  
     }  
     long   nDay=(tmpDate.getTime()/(24*60*60*1000)+1+n)*(24*60*60*1000);  
     tmpDate.setTime(nDay);  
     String str=df.format(tmpDate);
     str=str.replaceAll("-", "");
     int longStr=Integer.valueOf(str);
     return longStr;
	
}
  //得到最近的前10个期号
  public List getTenIssue(){
		String operaterCode = "C0206";
		String[]params=new String[1];
		params[0]="304";
		String results = helpMessage(params, operaterCode);
		List list=new MessageTool().splits(results);
		List tempList=new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			
			String issue=((String[])list.get(i))[0];
			tempList.add(issue);
	}
		return tempList;
		
	}
	
	public static void main(String[] args) throws Exception{
		//List list=new AuxiliaryData().guessChipin();
		//System.out.println("list---"+list);
		int basicDate=20140701;
		List list=new AuxiliaryData().getTenIssue();
		for (int i = 0; i < list.size(); i++) {
		
				System.out.println("----"+i+"===="+((String[])list.get(i))[0]);
			
		}
		
    }
}
