package com.iamberry.wechat.service.statistics;

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 java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.cache.LocalCache;
import com.iamberry.wechat.core.entity.PaperBean;
import com.iamberry.wechat.core.entity.order.ProbationOrderDto;
import com.iamberry.wechat.core.entity.statictics.GoldMemberStatisticsDto;
import com.iamberry.wechat.core.entity.statictics.SalesmanDto;
import com.iamberry.wechat.core.entity.statictics.SalesmanInfo;
import com.iamberry.wechat.core.entity.statictics.StatisticManagerDto;
import com.iamberry.wechat.core.entity.statictics.StatisticOrderByMonthDto;
import com.iamberry.wechat.core.entity.statictics.StatisticsAdministratorDTO;
import com.iamberry.wechat.core.entity.statictics.StatisticsOrderDTO;
import com.iamberry.wechat.core.entity.statictics.StatisticsOrderDetailsDTO;
import com.iamberry.wechat.core.entity.statictics.StoresStatisticsDto;
import com.iamberry.wechat.core.entity.statictics.VipOfflineDto;
import com.iamberry.wechat.face.statistics.StatisticsRelationService;
import com.iamberry.wechat.service.mapper.StatisticsRelationMapper;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.ResponseJson;
/**
 * 销售统计serivce实现
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年12月21日
 */
@Service
public class StatisticsRelationServiceImpl implements StatisticsRelationService {
	
	@Autowired
	private StatisticsRelationMapper statisticsRelationMapper;
	
	public LocalCache<String, SalesmanInfo> statisticsCache = new LocalCache<>(20);
	
	public List<String> monthArray = new ArrayList<String>();

	@Override
	public SalesmanInfo getRelationByOpenID(String openID) {
		String cacheKey = "statiscs_" + openID;
		// TODO Auto-generated method stub
		SalesmanInfo salesmanRelation = statisticsCache.get(cacheKey);
		if (salesmanRelation == null) {
			salesmanRelation = statisticsRelationMapper.getRelationByOpenID(openID);
			if (salesmanRelation == null) {
				return null;
			}
			statisticsCache.put(cacheKey, salesmanRelation);
		}
		return salesmanRelation;
	}

	@Override
	public ResponseJson getStatisticsOrderByOpenID(int raiationID, int pageNO, int pageSize) {
		ResponseJson json = new ResponseJson();
		PaperBean bean = new PaperBean();
		bean.setPaperData(pageNO, pageSize);
		// 当前时间
		Date nowDate = new Date();
		// 本月的结束时间  类似 ：2016-02-29 23:59:59
		Date endDate = DateTimeUtil.getLastDayOfYear(nowDate);
		// 本月的开始时间  类似 ：2016-02-01 00:00:00
		Date startDate = DateTimeUtil.getFirstDayOfYear(nowDate);
		List<StatisticsOrderDTO> dtos = statisticsRelationMapper.getStatisticsOrderByOpenID(startDate, endDate, raiationID, bean.getMinNum(), bean.getMaxNum());
		if (dtos == null || dtos.isEmpty()) {
			json.setResultCode(200);
			json.setResultMsg("SUCCESS");
			json.setReturnCode(201);
			return json;
		}
		// 根据dealers填充商户的名称
		int monthTotal = statisticsRelationMapper.getTotalByMonth(startDate, endDate, raiationID);
		
		// 返回正确的数据
		json.setResultCode(200);
		json.setResultMsg("SUCCESS");
		json.setReturnCode(200);
		json.addResponseKeyValue("data", dtos);
		json.addResponseKeyValue("total", monthTotal);
		
		return json;
	}

	@Override
	public StatisticsOrderDetailsDTO getOrderDetails(Integer dealer, String orderId) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.getOrderDetails(dealer, orderId);
	}
	
	@Override
	public List<ProbationOrderDto> selectProbationStatictics(SalesmanDto salesmanDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectProbationStatictics(salesmanDto);
	}

	@Override
	public Map<String,Integer> selectProbationStaticticsCount(SalesmanDto salesmanDto) {
		// TODO Auto-generated method stub
		Map<String,Integer> map = new HashMap<String,Integer>();
		int count = statisticsRelationMapper.selectProbationStaticticsCount(salesmanDto);
		//查询统计的总条目数
		map.put("probationNum", count);
		count = count % salesmanDto.getPage().getPageSize() == 0?count/salesmanDto.getPage().getPageSize():(count/salesmanDto.getPage().getPageSize())+1;
		//分页的页数
		map.put("pageSize", count);
		return map;
	}

	@Override
	public List<StoresStatisticsDto> selectStoresStatistics(StoresStatisticsDto storesStatisticsDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectStoresStatistics(storesStatisticsDto);
	}

	@Override
	public Map<String,Integer> selectStoresStatisticsCount(StoresStatisticsDto storesStatisticsDto) {
		// TODO Auto-generated method stub
		Map<String,Integer> map = new HashMap<String,Integer>();
		int count = statisticsRelationMapper.selectStoresStatisticsCount(storesStatisticsDto);
		//查询统计的总条目数
		map.put("probationNum", count);
		count = count % storesStatisticsDto.getPage().getPageSize() == 0?count/storesStatisticsDto.getPage().getPageSize():(count/storesStatisticsDto.getPage().getPageSize())+1;
		//分页的页数
		map.put("pageSize", count);
		return map;
	}
	@Override
	public List<VipOfflineDto> selectVipOffline(VipOfflineDto vipOfflineDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectVipOffline(vipOfflineDto);
	}

	@Override
	public Map<String,Integer> selectVipOfflineCount(VipOfflineDto vipOfflineDto) {
		// TODO Auto-generated method stub
		Map<String,Integer> map = new HashMap<String,Integer>();
		int count = statisticsRelationMapper.selectVipOfflineCount(vipOfflineDto);
		//查询统计的总条目数
		map.put("probationNum", count);
		count = count % vipOfflineDto.getPage().getPageSize() == 0?count/vipOfflineDto.getPage().getPageSize():(count/vipOfflineDto.getPage().getPageSize())+1;
		//分页的页数
		map.put("pageSize", count);
		return map;
	}
	
	@Override
	public List<StoresStatisticsDto> selectAdministratorStatistics(StoresStatisticsDto storesStatisticsDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectAdministratorStatistics(storesStatisticsDto);
	}

	@Override
	public Map<String,Integer> selectAdministratorStatisticsCount(StoresStatisticsDto storesStatisticsDto) {
		// TODO Auto-generated method stub
		Map<String,Integer> map = new HashMap<String,Integer>();
		int count = statisticsRelationMapper.selectAdministratorStatisticsCount(storesStatisticsDto);
		//查询统计的总条目数
		map.put("probationNum", count);
		count = count % storesStatisticsDto.getPage().getPageSize() == 0?count/storesStatisticsDto.getPage().getPageSize():(count/storesStatisticsDto.getPage().getPageSize())+1;
		//分页的页数
		map.put("pageSize", count);
		return map;
	}
	@Override
	public ProbationOrderDto selectProbationInfo(ProbationOrderDto probationOrderDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectProbationInfo(probationOrderDto);
	}
	
	@Override
	public StatisticManagerDto selectSalesCount(PaperBean page) {
		// TODO Auto-generated method stub
		StatisticManagerDto dto = statisticsRelationMapper.selectSalesCount(page);
		return dto;
	}

	@Override
	public StatisticManagerDto selectOrderList(PaperBean page) {
		// TODO Auto-generated method stub
		StatisticManagerDto dto = new StatisticManagerDto();
		List<StatisticsOrderDTO> list = null;
		Integer i = null;
		if("probationOrder".equals(page.getStr())){
			list = statisticsRelationMapper.selectProbationOrderBySalesManOpenid(page);
			i = statisticsRelationMapper.selectProbationOrderCountNumBySalesManOpenid(page);
		}else if("salesOrder".equals(page.getStr())){
			list = statisticsRelationMapper.selectOrderBySalesManOpenid(page);
			i = statisticsRelationMapper.selectOrderCountNumBySalesManOpenid(page);
		}
		if(list != null && i != null && i > 0){
			dto.setSalesOrderDto(list);
			dto.setSalesOrderCount(i);
			return dto;
		}else{
			return null;
		}
	}
	
	@Override
	public List<StatisticOrderByMonthDto> selectOrderCountNumByMonth(
			PaperBean page) {
		//试用订单月销量统计
		List<StatisticOrderByMonthDto> probationList = statisticsRelationMapper.selectProbationCountNumByMonth(page);
		//销售订单月销量统计
		List<StatisticOrderByMonthDto> orderList = statisticsRelationMapper.selectOrderCountNumByMonth(page);
		
		List<StatisticOrderByMonthDto> resultList = initResultList(page.getOtherInt());
		//填充数据
		for (StatisticOrderByMonthDto resultDto1 : resultList) {
			//填充销售台数到对应的月份
			for (StatisticOrderByMonthDto orderDto : orderList) {
				if(resultDto1.getMonth().equals(orderDto.getMonth())){
					resultDto1.setOrderCountNum(orderDto.getOrderCountNum());
				}
			}
			//填充试用台数到对应的月份
			for (StatisticOrderByMonthDto probationDto : probationList) {
				if(resultDto1.getMonth().equals(probationDto.getMonth())){
					resultDto1.setProbationCountNum(probationDto.getProbationCountNum());
				}
			}
		}
		return resultList;
	}

	/**
	 * 初始化结果集，若是今年则返回1月到当前月的集合，若是往年则返回12个月的,默认数据都为0
	 * @author mzx
	 * @param year	需要查询的年 如：2017
	 * @return
	 */
	private List<StatisticOrderByMonthDto> initResultList(int year){
		List<StatisticOrderByMonthDto> resultList = new ArrayList<StatisticOrderByMonthDto>();
		StatisticOrderByMonthDto resultDto = null;
		int thisYearNum = DateTimeUtil.year();	//今年	如：2017
		int num = 0;
		if(year == thisYearNum){	//今年的
			num = DateTimeUtil.month() + 1;
		}else{		//往年的
			num = 12;
		}
		for (int i = 0; i < num; i++) {
			resultDto = new StatisticOrderByMonthDto();
			resultDto.setMonth((i + 1) + "月");
			resultDto.setProbationCountNum(0);
			resultDto.setOrderCountNum(0);
			resultList.add(resultDto);
		}
		return resultList;
	}

	@Override
	public List<StatisticsAdministratorDTO> selectSalesInfo() {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectSalesInfo();
	}

	@Override
	public List<StatisticsAdministratorDTO> selectOrderMoney() {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectOrderMoney();
	}

	@Override
	public StatisticsAdministratorDTO selectRoleInfo() {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectRoleInfo();
	}

	@Override
	public StatisticsAdministratorDTO selectUserNum() {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectUserNum();
	}

	@Override
	public Integer selectUserSubordinateInfo() {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectUserSubordinateInfo();
	}
	
	@Override
	public SalesmanDto selectAdminInfo(String openId) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectAdminInfo(openId);
	}

	@Override
	public List<StatisticOrderByMonthDto> selectOrderByMonth(
			StatisticOrderByMonthDto statisticOrderByMonthDto) {
		// TODO Auto-generated method stub
		//按月查询销售订单售出水机总数
		List<StatisticOrderByMonthDto> orderList = statisticsRelationMapper.selectOrderByMonth(statisticOrderByMonthDto);
		//按月查询试用订单总数
		List<StatisticOrderByMonthDto> probationList = statisticsRelationMapper.selectProbationByMonth(statisticOrderByMonthDto);
		//初始化月份集合，将应查的月份添加到集合中
		List<StatisticOrderByMonthDto> resultList = initResultList(Integer.parseInt(statisticOrderByMonthDto.getMonth()));
		//填充数据
		for (StatisticOrderByMonthDto resultDto1 : resultList) {
			//填充销售台数到对应的月份
			for (StatisticOrderByMonthDto orderDto : orderList) {
				if(resultDto1.getMonth().equals(orderDto.getMonth())){
					resultDto1.setOrderCountNum(orderDto.getOrderCountNum());
				}
			}
			//填充试用台数到对应的月份
			for (StatisticOrderByMonthDto probationDto : probationList) {
				if(resultDto1.getMonth().equals(probationDto.getMonth())){
					resultDto1.setProbationCountNum(probationDto.getProbationCountNum());
				}
			}
		}
			
		return resultList;
	}
	
	//计算当月所有的日期节点
//	private static List<String> getAllTheDateOftheMonth(String time) {
//		List<String> list = new ArrayList<String>();
//		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//		try {
//			Date date = format.parse(time);
//			Calendar cal = Calendar.getInstance();
//			cal.setTime(date);
//			cal.set(Calendar.DATE, 1);
//
//			int month = cal.get(Calendar.MONTH);
//			while(cal.get(Calendar.MONTH) == month){
//				list.add(format.format(cal.getTime()));
//				cal.add(Calendar.DATE, 1);
//			}
//			return list;
//		} catch (Exception e) {
//			System.out.println("时间类型转换报错");
//			return null;
//		}
//	}

	@Override
	public List<StatisticOrderByMonthDto> selectProbationByMonth(
			StatisticOrderByMonthDto statisticOrderByMonthDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectProbationByMonth(statisticOrderByMonthDto);
	}

	@Override
	public List<GoldMemberStatisticsDto> selectAllGoldMemberStatistics(
			GoldMemberStatisticsDto goldMemberDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectAllGoldMemberStatistics(goldMemberDto);
	}
	@Override
	public Integer selectAllGoldMemberStatisticsCountNum(String placeName) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectAllGoldMemberStatisticsCountNum(placeName);
	}
	@Override
	public List<GoldMemberStatisticsDto> selectGoldUnderUserAndBoughtCount(
			GoldMemberStatisticsDto goldMemberDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectGoldUnderUserAndBoughtCount(goldMemberDto);
	}

	@Override
	public Integer selectGoldUnderUserAndBoughtCountNum(
			GoldMemberStatisticsDto goldMemberDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectGoldUnderUserAndBoughtCountNum(goldMemberDto);
	}

	@Override
	public List<StatisticOrderByMonthDto> selectSalesNumbers(
			StatisticOrderByMonthDto statisticOrderByMonthDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectSalesNumbers(statisticOrderByMonthDto);
	}

	@Override
	public Map<String, Integer> selectSalesNumbersCount(StatisticOrderByMonthDto statisticOrderByMonthDto){
			// TODO Auto-generated method stub
			Map<String,Integer> map = new HashMap<String,Integer>();
			int count = statisticsRelationMapper.selectSalesNumbersCount(statisticOrderByMonthDto);
			//查询统计的总条目数
			map.put("probationNum", count);
			count = count % statisticOrderByMonthDto.getPage().getPageSize() == 0?count/statisticOrderByMonthDto.getPage().getPageSize():(count/statisticOrderByMonthDto.getPage().getPageSize())+1;
			//分页的页数
			map.put("pageSize", count);
			return map;
	}

	@Override
	public List<StatisticOrderByMonthDto> selectProbationSumByMonth(
			StatisticOrderByMonthDto statisticOrderByMonthDto) {
		// TODO Auto-generated method stub
		return statisticsRelationMapper.selectProbationSumByMonth(statisticOrderByMonthDto);
	}
	
	public static void main(String[] args) {
		System.out.println(DateTimeUtil.month());
	}
	
}
