package cn.com.countrygarden.bi.main.service.dup.impl;

import cn.com.countrygarden.bi.main.dao.dup.WeekIncomeMapper;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.dup.WeekIncome;
import cn.com.countrygarden.bi.main.service.dup.WeekIncomeService;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageRowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 周收入统计表
 * @author pansw
 *
 */
@Service
@Transactional
public class WeekIncomeServiceImpl implements WeekIncomeService {
	
	@Autowired
	private WeekIncomeMapper weekIncomeMapper;

	/**
	 * 查询所有项目名称
	 * @return
	 */
	@Override
	public List<Map<String,Object>> findAllProject() {
		List<WeekIncome> p = weekIncomeMapper.findAllProject();
		List<WeekIncome> o = weekIncomeMapper.findAllOrgan();
		List<Map<String,Object>> list = new ArrayList<>();
		if(o == null || p==null) {
			return null;
		}
		for (WeekIncome weekIncome : o) {
			Map<String,Object> children = new HashMap<>();
			children.put("code", "");
			children.put("id", weekIncome.getOrganCode());
			children.put("label", weekIncome.getOrganName());
			list.add(children);
		}
		
		for (Map<String, Object> map : list) {
			List<Map<String,Object>> plist = new ArrayList<>();
			for (WeekIncome  weekIncome: p) {
				if(null == map.get("id")) {
					break;
				}
				if(weekIncome.getOrganCode().equals(map.get("id"))) {
					Map<String,Object> org = new HashMap<>();
					org.put("children", new ArrayList<>());
					org.put("code", "");
					org.put("id", weekIncome.getCommID());
					org.put("label", weekIncome.getCommName());
					plist.add(org);
				}
			}
			map.put("children", plist);
		}
		//删除没有子节点的区域
		Iterator<Map<String, Object>> it = list.iterator();
		while(it.hasNext()){
		    Map<String, Object> x = it.next();
		    if(((List) x.get("children")).size()<=0){
		        it.remove();
		        System.out.println(x.get("id")+"+++++++++++"+x.get("label"));
		    }
		}
		return list;
	}

	@Value("${holoweb.url.findWeekIncome}")
	private String holowebUrlFind;
	
	/**
	 *  查询周收入统计
	 */
	@Override
	public PageData findWeekIncomeStatistical(Integer[] commmIds,String startDate1,String endDate1,WeekIncome income) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         //起始日期
		startDate1=startDate1+"%2000:00:00.0";
		//结束日期
		endDate1=endDate1+"%2023:59:59.0";

		String commmIdstring="";
		for (int i = 0; i <commmIds.length ; i++) {
			if(i==0){
				commmIdstring = commmIds[i]+"";
			}else{
				commmIdstring = commmIdstring+","+commmIds[i];
			}
		}
		try {
			String url=holowebUrlFind+"&commid="+commmIdstring+
					"&pageNum="+income.getPageIndex()+"&pageSize="+income.getPageSize()+"&startDate="+startDate1+"&endDate="+endDate1;
			URL oracle = new URL(url);
			HttpURLConnection connect = (HttpURLConnection) oracle.openConnection();
			BufferedReader br = new BufferedReader(new InputStreamReader(connect.getInputStream(),"utf-8"));
			StringBuilder response = new StringBuilder();
			String line;
			while((line=br.readLine())!=null){
				response.append(line);
			}

			JSONObject jsonObject=new JSONObject(response.toString());
			Object data = jsonObject.get("data");
			JSONObject jsonOb=new JSONObject(data.toString());
			Long totalNum=jsonOb.getLong("totalNum");
			JSONArray jsonArray= JSON.parseArray(jsonOb.get("rows").toString());
            List<WeekIncome> weekIncomeList=new ArrayList<>();
			if(jsonArray.size()!=0) {
				for(int i=0;i<jsonArray.size();i++) {
					com.alibaba.fastjson.JSONObject jsonO=jsonArray.getJSONObject(i);
					WeekIncome weekInc=new WeekIncome();
					weekInc.setOrganName(jsonO.getString("organ_name"));
					weekInc.setCommName(jsonO.getString("comm_name"));
					weekInc.setNCSystemNumber(jsonO.getString("nc_system_number"));
					weekInc.setReceipts(jsonO.getDouble("ss_by_tax_amount"));
					weekInc.setWeekAmount(jsonO.getDouble("ss_by_ntax_amount"));
					weekIncomeList.add(weekInc);
				}
				PageRowBounds pageRowBounds = new PageRowBounds(income.getPageIndex(),income.getPageSize());
				pageRowBounds.setTotal(totalNum);
				PageData PageData=new PageData(weekIncomeList,pageRowBounds);
				return PageData;

			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		/*try {
			//查询区域
	//		List<WeekIncome> organLi = weekIncomeMapper.findOrgan(commmIds);
			
			//起始日期
			Date startDate=sdf.parse(startDate1+" 00:00:00");
			//结束日期
			Date endDate =sdf.parse(endDate1+" 23:59:59");
			Map<String,Object> map=new HashMap<String,Object>();
			List<String> autoBatcyList=new ArrayList<>();
			for (int i = 0; i < commmIds.length; i++) {
				autoBatcyList.add(commmIds[i]+"");
			}
			List<WeekIncome>list=new ArrayList<WeekIncome>();
		      //由于数据库对于插入字段的限制，在这里对批量插入的数据进行分批处理
            int batchCount =120;//每批查询的个数
            int batchLastIndex = batchCount - 1;// 每批最后一个的下标
            for (int index = 0; index < autoBatcyList.size() - 1;) {
                if (batchLastIndex > autoBatcyList.size() - 1) {
                    batchLastIndex = autoBatcyList.size() - 1;
                    map.put("lists", autoBatcyList.subList(index, batchLastIndex + 1));
        			map.put("startDate", startDate);
        			map.put("endDate", endDate);
        			
        			List<WeekIncome>listnew=weekIncomeMapper.findWeekIncome(map);
        			if(listnew.size()>0){
        				list.addAll(listnew);
        			}			
                    break;// 数据插入完毕,退出循环
                } else {
                	map.put("lists", autoBatcyList.subList(index, batchLastIndex + 1));
         			map.put("startDate", startDate);
         			map.put("endDate", endDate);
         			weekIncomeMapper.findWeekIncome(map);
         			List<WeekIncome>listnew=weekIncomeMapper.findWeekIncome(map);
         			if(listnew.size()>0){
        				list.addAll(listnew);
        			}	
                    index = batchLastIndex + 1;// 设置下一批下标
                    batchLastIndex = index + (batchCount - 1);
                }
            }			
			PageRowBounds pageRowBounds = new PageRowBounds(income.getPageIndex(),income.getPageSize());
			//List<WeekIncome>list = weekIncomeMapper.findWeekIncome(map,pageRowBounds);
			//List<WeekIncome>list = weekIncomeMapper.findWeekIncome(map);
			Integer str = (income.getPageIndex()-1) * income.getPageSize();
			Integer end = (income.getPageIndex()-1) * income.getPageSize()+income.getPageSize();
			List<WeekIncome> newList = new ArrayList<>();
			for (int i = 0;i<list.size();i++) {
				if((i>= str && i<=end) || (income.getPageIndex() == 0 && income.getPageSize() == 0)) {
				    newList.add(list.get(i));
				}
			}
			pageRowBounds.setTotal(new Long(list.size()));
			PageData PageData=new PageData(newList,pageRowBounds);
			return PageData;
			
		} catch (ParseException e) {
			e.printStackTrace();
		}*/
		return null;
	}
	
	
	
}
