package com.iamberry.wechat.service.reback;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.drp.IncomeRecord;
import com.iamberry.wechat.core.entity.drp.ObjRecord;
import com.iamberry.wechat.core.entity.drp.ObjRecord2;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.reback.RolesListDto;
import com.iamberry.wechat.core.entity.reback.StoreStatiscInfo;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.reback.RebackStaticService;
import com.iamberry.wechat.service.drp.PlaceLogsServiceImpl;
import com.iamberry.wechat.service.mapper.PlaceInfoMapper;
import com.iamberry.wechat.service.mapper.RebackInfoMapper;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.StaticInfo;

/**
 * @description 用于返现表的统计
 * @author ouyang
 * @date 2016-05-26
 */
@Service("rebackStaticServiceImpl")
public class RebackStaticServiceImpl implements RebackStaticService {

	
	@Autowired
	private RebackInfoMapper  rebackInfoMapper;
	@Autowired
	private RatFWLogger logger;
	@Autowired
	private PlaceInfoMapper placeInfoMapper;
	@Autowired
	private SystemService  systemService;
	
	/**
	 * 获取未入账的统计信息（母婴店，门店）
	 */
	public Map getUnIncomeOrderList(String openid, PageBean page) {
		HashMap returnMap=new HashMap();
		HashMap conditionMap=new HashMap();
		conditionMap.put("recordBegin",page.getRecordBegin());
		conditionMap.put("pageSize", page.getPageSize());
		//openids1 openid retio openids2
		//PlaceInfo placeInfo=placeInfoMapper.getOnePlaceInfo2(openid);
		conditionMap.put("openid", openid);
		
		List<ObjRecord> records=rebackInfoMapper.getUnInComeRecord(conditionMap);
		if(records==null || records.size()==0){
			returnMap.put("list", null);
			returnMap.put("unIncomeMoney",0);
			return returnMap;
		}
		
		Date date1=new Date();
		int days=systemService.selectOneShopRuleById(102).getRuleNum().intValue();
		for(ObjRecord  rs:records){
			
			if(rs.getStrDate()==null || rs.getStrDate().equals("未发货")){
				rs.setStrDate("未发货");
			}else{
				Date date2=DateTimeUtil.parse(rs.getStrDate(), "yyyy-MM-dd HH:mm:ss");
				date2=DateTimeUtil.addDay(date2, days);
				rs.setStrDate(DateTimeUtil.getDistanceTime2(date1,date2));
			}
		}
		int mon=0;
		try{
			mon=rebackInfoMapper.getUnIncomeMoney(openid);
		}catch(Exception ex){
			mon=0;
		}
		returnMap.put("list", records);
		returnMap.put("unIncomeMoney",mon);
		return returnMap;
	}

	/**
	 * 获取未入账的统计信息（非母婴店，门店）
	 */
	public Map getUnIncomeOrderList2(String openid, PageBean page) {
		HashMap returnMap=new HashMap();
		HashMap conditionMap=new HashMap();
		conditionMap.put("recordBegin",page.getRecordBegin());
		conditionMap.put("pageSize", page.getPageSize());
		//openids1 openid retio openids2
		//PlaceInfo placeInfo=placeInfoMapper.getOnePlaceInfo2(openid);
		conditionMap.put("openid", openid);
		
		PlaceInfo placeInfo=placeInfoMapper.getOnePlaceInfo2(openid);
		conditionMap.put("pid", placeInfo.getId());
		List<ObjRecord2> records=rebackInfoMapper.getDrpUnInComeRecord(conditionMap);
		if(records==null || records.size()==0){
			returnMap.put("list", null);
			returnMap.put("unIncomeMoney",0);
			return returnMap;
		}

		int mon=0;
		try{
			mon=rebackInfoMapper.getUnIncomeMoney(openid);
		}catch(Exception ex){
			mon=0;
		}
		returnMap.put("list", records);
		returnMap.put("unIncomeMoney",mon);
		return returnMap;
	}
	/**
	 * 获取未入账的统计信息（非母婴店，门店）对于省代的贡献的
	 */
	public Map getUnIncomeOrderList2Top(String openid,String openidInit, PageBean page) {
		HashMap returnMap=new HashMap();
		HashMap conditionMap=new HashMap();
		conditionMap.put("recordBegin",page.getRecordBegin());
		conditionMap.put("pageSize", page.getPageSize());
		//openids1 openid retio openids2
		//PlaceInfo placeInfo=placeInfoMapper.getOnePlaceInfo2(openid);
		conditionMap.put("openid", openid);
		
		PlaceInfo placeInfo=placeInfoMapper.getOnePlaceInfo2(openidInit);
		conditionMap.put("pid", placeInfo.getId());
		List<ObjRecord2> records=rebackInfoMapper.getDrpUnInComeRecord2(conditionMap);
		if(records==null || records.size()==0){
			returnMap.put("list", null);
			returnMap.put("unIncomeMoney",0);
			return returnMap;
		}

		int mon=0;
		try{
			mon=rebackInfoMapper.getUnIncomeMoney2(conditionMap);
		}catch(Exception ex){
			mon=0;
		}
		returnMap.put("list", records);
		returnMap.put("unIncomeMoney",mon);
		return returnMap;
	}
	/**
	 * 根据周，月，年统计信息
	 */
	public List<ObjRecord> getIncomeStatistics(String openid, String type) {
		HashMap conditionMap=new HashMap();
		 List<ObjRecord> records=new ArrayList<ObjRecord>();
		 List<ObjRecord> records2;
		 conditionMap.put("toOpenid",openid);
		 logger.info(PlaceLogsServiceImpl.class,"==========conditionMap=============="+conditionMap.toString());
		 if(type.equals(StaticInfo.SevenDay)){
			records2=rebackInfoMapper.getRecentIncome7Day(conditionMap);
			 Map<String,Object> testMap=new HashMap<String,Object>();
			 
			 if(records2==null || records2.size()==0){
				 testMap.put("1",null);
			 }else if(records2.size()==1){
				 ObjRecord  re=records2.get(0);
				 if( re==null || null==re.getName()){
				 }else{
					 testMap.put(re.getName(),re);
				 }
			 }else{
				 for(ObjRecord  re:records2){
					 testMap.put(re.getName(),re);
				 }
			 }
			 for(int i=0;i<7;i++){
				 Calendar cl= DateTimeUtil.getRecentDay(-i);
				 String name=DateFormatUtils.format(cl, "yyyyMMdd");
				 if(testMap.get(name)==null){
					 ObjRecord re2=new ObjRecord();
					 re2.setAmount(0);
					 re2.setName(name);
					 re2.setStrDate(DateFormatUtils.format(cl, "MM.dd"));
					 records.add(re2);
				 }else{
					 records.add((ObjRecord)testMap.get(name));
				 }
			 }

		 }else if(type.equals(StaticInfo.SixMon)){
		    records2=rebackInfoMapper.getRecentIncome6Month(conditionMap);
			 Map<String,Object> testMap=new HashMap<String,Object>();
			 if(records2==null || records2.size()==0){
				 testMap.put("1",null);
			 }else if(records2.size()==1){
				 ObjRecord  re=records2.get(0);
				 if( re==null || null==re.getName()){
				 }else{
					 testMap.put(re.getName(),re);
				 }
			 }else{
				 for(ObjRecord  re:records2){
					 testMap.put(re.getName(),re);
				 }
			 }
			 for(int i=0;i<6;i++){
				 Calendar cl= DateTimeUtil.getLastMon(-i);
				 String name=DateFormatUtils.format(cl, "yyyyMM");
				 if(testMap.get(name)==null){
					 ObjRecord re2=new ObjRecord();
					 re2.setAmount(0);
					 re2.setName(name);
					 re2.setStrDate(DateFormatUtils.format(cl, "yyyy.MM"));
					 records.add(re2);
				 }else{
					 ObjRecord ob=(ObjRecord)testMap.get(name);
					 records.add(ob);
				 }
			 }

		 }else if(type.equals(StaticInfo.Year)){
			 /*String year=DateFormatUtils.format(new Date(), "yyyy");
			  conditionMap.put("beginDate", year+"01-01");
			  conditionMap.put("endDate",  year+"01-01");
		      records=placeLogsMapper.getRecentIncomeYear(conditionMap);*/
			  records2=rebackInfoMapper.getRecentIncome6Month(conditionMap);
			 Map<String,Object> testMap=new HashMap<String,Object>();
			 if(records2==null || records2.size()==0){
				 testMap.put("1",null);
			 }else if(records2.size()==1){
				 ObjRecord  re=records2.get(0);
				 if( re==null || null==re.getName()){
				 }else{
					 testMap.put(re.getName(),re);
				 }
			 } else{
				 for(ObjRecord  re:records2){
					 testMap.put(re.getName(),re);
				 }
			 }
			 for(int i=0;i<12;i++){
				 Calendar cl= DateTimeUtil.getLastMon(-i);
				 String name=DateFormatUtils.format(cl, "yyyyMM");
				 if(testMap.get(name)==null){
					 ObjRecord re2=new ObjRecord();
					 re2.setAmount(0);
					 re2.setName(name);
					 re2.setStrDate(DateFormatUtils.format(cl, "yyyy.MM"));
					 records.add(re2);
				 }else{
					 records.add((ObjRecord)testMap.get(name));
				 }
			 }

		 }
       return records;
	}

	/**
	 * 获取未入账的总数
	 */
	public int getUnIncomeMoney(String openid) {
		return rebackInfoMapper.getUnIncomeMoney(openid);
	}

	/**
	 * 获取分销商的下线用户列表信息
	 */
	public Map getNextDrpStatisc(String openid,PageBean page) {
		PlaceInfo placeInfo=new PlaceInfo();
		placeInfo.setOpenid(openid);
		List<String> openids=placeInfoMapper.getUnderling(placeInfo);
		
		HashMap<String ,Object> conditionMap=new HashMap<String,Object>();
		if(page!=null){
			page.initRecordBegin();
			conditionMap.put("recordBegin", page.getRecordBegin());
			conditionMap.put("pageSize", page.getPageSize());
		}else{
			conditionMap.put("recordBegin", 0);
			conditionMap.put("pageSize", 10);
		}
		
		Map<String,Object> resultMap=new HashMap<String,Object>();
		String str=getConditionString(openids);
		if(str.equals("") || str.equals("()")){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}
		placeInfo=placeInfoMapper.getOnePlaceInfo2(openid);
		List<RolesListDto> rolesList=rebackInfoMapper.getRolesList(placeInfo.getId());
		
		conditionMap.put("roleId", rolesList.get(0).getRoleId()); 
		conditionMap.put("openids", str); 
		List<StoreStatiscInfo> lists=rebackInfoMapper.getUnderlingStatisc(conditionMap);
		if(lists==null || lists.size()==0){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}
		
		

		resultMap.put("size",openids.size());
		resultMap.put("rolesList", rolesList);
		resultMap.put("list", lists);
		
		return resultMap;
	}
	
	/**
	 * 获取分销商的下线用户角色列表
	 */
	public Map getNextDrpStatisc(String openid) {
		Map<String,Object> resultMap=new HashMap<String,Object>();
		PlaceInfo placeInfo=placeInfoMapper.getOnePlaceInfo2(openid);
		List<RolesListDto> rolesList=rebackInfoMapper.getRolesList(placeInfo.getId());
		resultMap.put("rolesList", rolesList);
		return resultMap;
	}
	
	/**
	 * 获取分销商的下线用户列表信息(分页)
	 */
	public Map getNextDrpStatisc(String openid,PageBean page,int roleId) {
		PlaceInfo placeInfo=new PlaceInfo();
		placeInfo.setOpenid(openid);
		List<String> openids=placeInfoMapper.getUnderling(placeInfo);
	
		HashMap<String ,Object> conditionMap=new HashMap<String,Object>();
		if(page!=null){
			page.initRecordBegin();
			conditionMap.put("recordBegin", page.getRecordBegin());
			conditionMap.put("pageSize", page.getPageSize());
		}else{
			conditionMap.put("recordBegin", 0);
			conditionMap.put("pageSize", 10);
		}
		
		Map<String,Object> resultMap=new HashMap<String,Object>();
		String str=getConditionString(openids);
		if(str.equals("") || str.equals("()")){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}

		conditionMap.put("roleId", roleId); 
		conditionMap.put("openids", str); 
		List<StoreStatiscInfo> lists=rebackInfoMapper.getUnderlingStatisc(conditionMap);
		if(lists==null || lists.size()==0){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}

		resultMap.put("size",openids.size());
		resultMap.put("list", lists);
		return resultMap;
	}
	
	/**
	 * 获取门店的下一级统计信息
	 *//*
	public Map getStoreNextStatisc(String openid,PageBean page) {
		Map<String,Object> resultMap=new HashMap<String,Object>();
		PlaceInfo placeInfo=new PlaceInfo();
		placeInfo.setOpenid(openid);
		//获取导购的openids
		List<String> openids=placeInfoMapper.getUnderling(placeInfo);
		if(openids==null || openids.size()==0){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}
		
		HashMap<String ,Object> conditionMap0=new HashMap<String,Object>();
		conditionMap0.put("openids", getConditionString(openids));
		//获取最终用户的ids
		List<String> ids=rebackInfoMapper.getUnderlingUserIds2(conditionMap0);
		HashMap<String ,Object> conditionMap=new HashMap<String,Object>();
		if(page!=null){
			page.initRecordBegin();
			conditionMap.put("recordBegin", page.getRecordBegin());
			conditionMap.put("pageSize", page.getPageSize());
		}else{
			conditionMap.put("recordBegin", 0);
			conditionMap.put("pageSize", 10);
		}
		
		String str=getConditionString(ids);
		if(str.equals("") || str.equals("()")){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}
		
		conditionMap.put("openid",openid);
		conditionMap.put("openids", str);
		List<StoreStatiscInfo> lists=rebackInfoMapper.getUnderlingStatisc2(conditionMap);
		if(lists==null || lists.size()==0){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}
		resultMap.put("size",ids.size());
		resultMap.put("list", lists);
		
		return resultMap;
		
	}*/
	
	/**
	 * 获取分销商下线--微代理用户的统计
	 */
	public Map getUnderlingStatisc(String openid,PageBean page ,Integer searchNo,String type){
		HashMap conditionmap=new HashMap();
		
		PlaceInfo placeInfo=placeInfoMapper.getOnePlaceInfo2(openid);
		conditionmap.put("userDealer", placeInfo.getId());
		
		List<String> ids=rebackInfoMapper.getUnderlingUserIds(conditionmap);
		HashMap<String ,Object> conditionMap=new HashMap<String,Object>();
		if(page!=null){
			page.initRecordBegin();
			conditionMap.put("recordBegin", 0); //page.getRecordBegin()
			conditionMap.put("pageSize", page.getPageSize());
		}else{
			conditionMap.put("recordBegin", 0);
			conditionMap.put("pageSize", 10);
		}
		
		Map<String,Object> resultMap=new HashMap<String,Object>();
		String str=getConditionString(ids);
		if(str.equals("") || str.equals("()")){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}
		
		conditionMap.put("openid",openid);
		conditionMap.put("openids", str);
		if(searchNo!=null && type.equals("endNo")){
			conditionMap.put("endNo", searchNo);
		}
		if(searchNo!=null && type.equals("beginNo")){
			conditionMap.put("beginNo", searchNo);
		}
		//conditionMap.put("level", 1);
		List<StoreStatiscInfo> lists=rebackInfoMapper.getUnderlingStatisc2(conditionMap);
		if(lists==null || lists.size()==0){
			resultMap.put("size",0);
			resultMap.put("list", null);
			return resultMap;
		}
		resultMap.put("size",ids.size());
		resultMap.put("endNo", lists.get(lists.size()-1).getUserId());
		resultMap.put("beginNo", lists.get(0).getUserId());
		resultMap.put("list", lists);
		
		return resultMap;
	}
	
	
	//===========================后台订单收入统计=============================
	/**
	 * 用于后台统计某一分销商的收入记录的
	 * param PageBean 包含分页信息及其查询条件placeInfo
	 */
	public Map getSearchIncomeDetail(PageBean page){
		Map<String,Object> hm=new HashMap<String,Object>();
		HashMap conditionMap=new HashMap();
	
		PageBean pageIndex=new PageBean();
		HashMap placeInfomap=(HashMap)page.getCondition();
		/*if(placeInfo.getType()>0){
			conditionMap.put("status", placeInfo.getType());
		}*/
		
		if(placeInfomap.get("name")==null && placeInfomap.get("initCode")==null){
			hm.put("data", new ArrayList<IncomeRecord>());
			hm.put("page",pageIndex);
			return hm;
		}
		PlaceInfo placeInfo=new PlaceInfo();
		placeInfo.setInitCode((String)placeInfomap.get("initCode"));
		
		placeInfo=placeInfoMapper.getOnePlaceInfoByInitcode(placeInfo);
		if(placeInfo==null){
			hm.put("data", new ArrayList<IncomeRecord>());
			hm.put("page",pageIndex);
			return hm;
		}		
		conditionMap.put("toOpenid", placeInfo.getOpenid());
		conditionMap.put("status", (String)placeInfomap.get("type"));
		page.initRecordBegin();
		
		conditionMap.put("recordBegin",page.getRecordBegin());
		conditionMap.put("pageSize", page.getPageSize());
		
		pageIndex.setPageSize(page.getPageSize());
		pageIndex.setPageNumber(page.getPageNumber());
		
		List<IncomeRecord> records=rebackInfoMapper.getSearchInComeRecord(conditionMap);
		
		pageIndex.setCount(rebackInfoMapper.getSearchInComeRecordCount(conditionMap));
		 hm.put("data", records);
		 hm.put("page", pageIndex);
		
		return hm;
	}
	
	
	
	
	//获取查询用户条件的openid字符串
	public String getConditionString(List<String> list){
		int size=list.size();
		StringBuffer sbf=new StringBuffer();
		for(int i=0;i<size;i++){
			 String openid2=list.get(i);
			 if(i!=size-1){
				 sbf.append("'"+openid2+"',");
			 }else{
				 sbf.append("'"+openid2+"'");
			 }
		 }
		
		return "("+sbf.toString()+")";
	}

}