package com.buy507.mall.service.impl;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.buy507.mall.dao.DmsQueryDao;
import com.buy507.mall.dto.ChartDescriptionResult;
import com.buy507.mall.dto.HomeResult;
import com.buy507.mall.dto.MemberShoppingInfoResult;
import com.buy507.mall.dto.MemberTeamInfoResult;
import com.buy507.mall.dto.OrderChartResult;
import com.buy507.mall.dto.WithdrawChartResult;
import com.buy507.mall.mapper.DmsMemberWithdrawApplyMapper;
import com.buy507.mall.mapper.OmsOrderMapper;
import com.buy507.mall.mapper.UmsMemberMapper;
import com.buy507.mall.model.DmsMemberWithdrawApply;
import com.buy507.mall.model.MemberLevel;
import com.buy507.mall.model.OmsOrder;
import com.buy507.mall.model.OmsOrderExample;
import com.buy507.mall.model.StoreStatus;
import com.buy507.mall.model.UmsMember;
import com.buy507.mall.model.UmsMemberExample;
import com.buy507.mall.service.DmsQueryService;
import com.github.pagehelper.PageHelper;

@Service
public class DmsQueryServiceImpl implements DmsQueryService {
	
	@Autowired
	private DmsQueryDao queryDao;
	
	@Autowired
	private UmsMemberMapper memberMapper;
	
	@Autowired
	private OmsOrderMapper orderMapper;
	
	@Autowired
	private DmsMemberWithdrawApplyMapper memberWithdrawApplyMapper;
	
	/**
	 * 查询首页信息
	 * @return
	 */
	@Override
	public HomeResult getHomeInfo() {
		
		HomeResult homeResult = new HomeResult();
		
		List<OmsOrder> todayOrder = queryDao.selectTodayOrder();
		int todayOrderCount = 0; //今日订单总数
		BigDecimal todaySellAmount = new BigDecimal(0); //今日销售总额
		
		//查询今日订单
		for(OmsOrder order : todayOrder) {
			//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
			if(order.getStatus().equals(1) || order.getStatus().equals(2) || order.getStatus().equals(3)) {
				todayOrderCount += 1;
				todaySellAmount = todaySellAmount.add(order.getTotalAmount());
			}
		}
		
		NumberFormat nbf = NumberFormat.getInstance(); 
        nbf.setMinimumFractionDigits(2);
		
		homeResult.setTodayOrderCount(todayOrderCount);
		homeResult.setTodaySellAmount(todaySellAmount);
		homeResult.setYesterdaySellAmount(queryDao.selectYesterdaySellAmount()); //昨日销售总额
		homeResult.setCurrentMonthSellAmount(queryDao.selectCurrentMonthSellAmount()); //本月销售总额
		homeResult.setAllSellAmount(queryDao.selectAllSellAmount()); //销售总金额
		homeResult.setBalancePayemntAmount(queryDao.selectBalancePayemntAmount()); //积分支付总金额
		
		UmsMemberExample memberExample = new UmsMemberExample();
		List<UmsMember> members = memberMapper.selectByExample(memberExample);
		
		OmsOrderExample orderExample = new OmsOrderExample();
		List<OmsOrder> orders = orderMapper.selectByExample(orderExample);
		
		List<DmsMemberWithdrawApply> memberWithdrawApplies = memberWithdrawApplyMapper.selectAll();
		
		int memberCount = 0;
		int consumerCount = 0;
		int partnerCount = 0;
		int diamondCount = 0;
		int oneDiamondCount = 0;
		int twoDiamondCount = 0;
		int threeDiamondCount = 0;
		int fourDiamondCount = 0;
		int allMemberCount = 0;
		int openStoreCount = 0;
		int waitPaymentOrderCount = 0;
		int doneOrderCount = 0;
		int waitDeliveryOrderCount = 0;
		int waitPickUpOrderCount = 0;
		int deliveredOrderCount = 0;
		int waitConfirmPaymentOrderCount = 0;
		int waitConfirmReceiveOrderCount = 0;
		int waitHandleWithdrawApplyCount = 0;
		int handledWithdrawApplyCount = 0;
		
		for(UmsMember member : members) {
			allMemberCount += 1;
			if(MemberLevel.Member.equals(member.getMemberLevel())) {
				memberCount += 1;
			}
			if(MemberLevel.Consumer.equals(member.getMemberLevel())) {
				consumerCount += 1;
			}
			if(MemberLevel.Partner.equals(member.getMemberLevel())) {
				partnerCount += 1;
			}
			if(MemberLevel.Diamond.equals(member.getMemberLevel())) {
				diamondCount += 1;
			}
			if(MemberLevel.OneDiamond.equals(member.getMemberLevel())) {
				oneDiamondCount += 1;
			}
			if(MemberLevel.TwoDiamond.equals(member.getMemberLevel())) {
				twoDiamondCount += 1;
			}
			if(MemberLevel.ThreeDiamond.equals(member.getMemberLevel())) {
				threeDiamondCount += 1;
			}
			if(MemberLevel.FourDiamond.equals(member.getMemberLevel())) {
				fourDiamondCount += 1;
			}
			if(StoreStatus.Yes.equals(member.getStoreStatus())) {
				openStoreCount += 1;
			}
		}
		
		//支付方式：0->未支付；1->支付宝；2->微信；3->线下支付
		//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
		for(OmsOrder order : orders) {
			if(order.getStatus().equals(0) && order.getPayType().equals(0)) {
				waitPaymentOrderCount += 1; //待付款订单
			}
			if(order.getStatus().equals(3)) {
				doneOrderCount += 1; //已完成订单
			}
			//提货方式：0->自提；1->物流
			if(order.getStatus().equals(1)) {
				waitDeliveryOrderCount += 1; //待发货订单
			}
			if(order.getStatus().equals(2) && order.getDeliveryType().equals(0)) {
				waitPickUpOrderCount += 1; //待提货订单
			}
			if(order.getStatus().equals(2) && order.getDeliveryType().equals(1)) {
				deliveredOrderCount += 1; //已发货订单
				waitConfirmReceiveOrderCount += 1; //待确认收货订单
			}
			if(order.getStatus().equals(0) && order.getPayType().equals(3)) {
				waitConfirmPaymentOrderCount += 1; //待确认付款订单
			}
			
		}
		
		BigDecimal withdrawAmount = new BigDecimal(0);
		List<Long> temp = new ArrayList<>();
		////付款状态：0->未打款；1->已打款；2->打款失败
		for(DmsMemberWithdrawApply apply : memberWithdrawApplies) {
			if(apply.getPaymentStatus().equals(0)) {
				waitHandleWithdrawApplyCount += 1; //待处理提现申请
			}
			if(apply.getPaymentStatus().equals(1)) {
				handledWithdrawApplyCount += 1; //已处理提现申请
				withdrawAmount = withdrawAmount.add(apply.getValue());
				temp.add(apply.getMemberId());
			}
		}
		
		Set set = new HashSet(temp);
		temp = new ArrayList<>(set);
		
		homeResult.setMemberCount(memberCount); //普通会员
		homeResult.setConsumerCount(consumerCount); //消费商
		homeResult.setPartnerCount(partnerCount); //经销商
		homeResult.setDiamondCount(diamondCount); //合作商
		homeResult.setOneDiamondCount(oneDiamondCount); //初级合作商
		homeResult.setTwoDiamondCount(twoDiamondCount); //中级合作商
		homeResult.setThreeDiamondCount(threeDiamondCount); //高级合作商
		homeResult.setFourDiamondCount(fourDiamondCount); //特级合作商
		homeResult.setOpenStoreCount(openStoreCount); //开店
		homeResult.setAllMemberCount(allMemberCount); //会员总数
		homeResult.setWaitPaymentOrderCount(waitPaymentOrderCount); //待付款订单
		homeResult.setDoneOrderCount(doneOrderCount); //已完成订单
		homeResult.setWaitDeliveryOrderCount(waitDeliveryOrderCount); //待发货订单
		homeResult.setWaitPickUpOrderCount(waitPickUpOrderCount); //待提货订单
		homeResult.setDeliveredOrderCount(deliveredOrderCount); //已发货订单
		homeResult.setWaitConfirmPaymentOrderCount(waitConfirmPaymentOrderCount); //待确认付款订单
		homeResult.setWaitConfirmReceiveOrderCount(waitConfirmReceiveOrderCount); //待确认收货订单
		homeResult.setWaitHandleWithdrawApplyCount(waitHandleWithdrawApplyCount); //待处理提现申请
		homeResult.setHandledWithdrawApplyCount(handledWithdrawApplyCount); //已处理提现申请
		homeResult.setWithdrawAmount(withdrawAmount); //提现总金额
		homeResult.setWithdrawMemberCount(temp.size()); //提现总人数
		
		return homeResult;
	}
	
	/**
	 * 获取订单图表
	 * @return
	 */
	@Override
	public List<OrderChartResult> getOrderChart(String startTime, String endTime) {
		
		Date start = null;
		Date end = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (!StringUtils.isEmpty(startTime)) {
            String startStr = startTime + " 00:00:00";
            try {
                start = sdf.parse(startStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
		
		if(!StringUtils.isEmpty(endTime)) {
			String endStr = endTime + " 23:59:59";
			try {
                end = sdf.parse(endStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
		}
		
		return queryDao.selectOrderChart(start, end);
	}
	
	
	/**
	 * 获取提现图表
	 * @return
	 */
	@Override
	public List<WithdrawChartResult> getWithdrawChart(String startTime, String endTime) {
		Date start = null;
		Date end = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (!StringUtils.isEmpty(startTime)) {
            String startStr = startTime + " 00:00:00";
            try {
                start = sdf.parse(startStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
		
		if(!StringUtils.isEmpty(endTime)) {
			String endStr = endTime + " 23:59:59";
			try {
                end = sdf.parse(endStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
		}
		
		return queryDao.selectWithdrawChart(start, end);
	}
	
	
	/**
	 * 获取图表描述
	 */
	@Override
	public ChartDescriptionResult getChartDescription() {
		ChartDescriptionResult result = new ChartDescriptionResult();
		
		/*
		List<OmsOrder> todayOrder = queryDao.selectTodayOrder();
		int todayOrderCount = 0; //今日订单总数
		BigDecimal todaySellAmount = new BigDecimal(0); //今日销售总额
		
		//查询今日订单
		for(OmsOrder order : todayOrder) {
			//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
			if(order.getStatus().equals(1) || order.getStatus().equals(2) || order.getStatus().equals(3)) {
				todayOrderCount += 1;
				todaySellAmount = todaySellAmount.add(order.getTotalAmount());
			}
		}
		
		result.setTodayOrderCount(todayOrderCount); //今日订单总数
		result.setTodaySellAmount(todaySellAmount); //今日销售总额
		*/
		result.setCurrentWeekOrderCount(queryDao.selectCurrentWeekOrderCount()); //本周订单总数
		result.setCurrentWeekSellAmount(queryDao.selectCurrentWeekSellAmount()); //本周销售总额
		result.setCurrentMonthOrderCount(queryDao.selectCurrentMonthOrderCount()); //本月订单总数
		result.setCurrentMonthSellAmount(queryDao.selectCurrentMonthSellAmount()); //本月销售总额
		result.setCurrentYearOrderCount(queryDao.selectCurrentYearOrderCount()); //本年订单总数
		result.setCurrenYearSellAmount(queryDao.selectCurrentYearSellAmount()); //本年销售总额
		
		result.setCurrentWeekWithdrawCount(queryDao.selectCurrentWeekWithdrawCount()); //本周提现总数
		result.setCurrentWeekWithdrawAmount(queryDao.selectCurrentWeekWithdrawAmount()); //本周提现总额
		result.setCurrentMonthWithdrawCount(queryDao.selectCurrentMonthWithdrawCount()); //本月提现总数
		result.setCurrentMonthWithdrawAmount(queryDao.selectCurrentMonthWithdrawAmount()); //本月提现总额
		result.setCurrentYearWithdrawCount(queryDao.selectCurrentYearWithdrawCount()); //本年提现总数
		result.setCurrenYearWithdrawAmount(queryDao.selectCurrentYearWithdrawAmount()); //本年提现总额
		
		return result;
	}
	

	/**
	 * 查询会员团队信息
	 * @param nickname
	 * @param inviterName
	 * @param inviterId
	 * @param memberLevel
	 * @param storeStatus
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@Override
	public List<MemberTeamInfoResult> memberTeamInfo(String nickname, String inviterName, Long inviterId, Integer memberLevel,
			Integer storeStatus, Integer pageSize, Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		return queryDao.selectMemberTeamInfo(nickname, inviterName, inviterId, memberLevel, storeStatus);
	}

	/**
	 * 查询会员购物信息
	 * @param startTime
	 * @param endTime
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@Override
	public List<MemberShoppingInfoResult> getMemberShoppingInfo(String startTime, String endTime, Integer pageSize,
			Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		return getMemberShoppingInfo(startTime, endTime);
	}

	/**
	 * 导出会员购物信息
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@Override
	public Workbook exportExcel(String startTime, String endTime) {
		
		List<MemberShoppingInfoResult> queryList = getMemberShoppingInfo(startTime, endTime);
		
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("提现列表");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow((int) 0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle headerStyle = wb.createCellStyle();
		headerStyle.setBorderBottom(BorderStyle.THIN);
		headerStyle.setBorderLeft(BorderStyle.THIN);//左边框
		headerStyle.setBorderTop(BorderStyle.THIN);//上边框
		headerStyle.setBorderRight(BorderStyle.THIN);//右边框
		headerStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
		headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
		
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("姓名");
		cell.setCellStyle(headerStyle);
		cell = row.createCell(1);
		cell.setCellValue("电话");
		cell.setCellStyle(headerStyle);
		cell = row.createCell(2);
		cell.setCellValue("商品名称");
		cell.setCellStyle(headerStyle);
		cell = row.createCell(3);
		cell.setCellValue("数量");
		cell.setCellStyle(headerStyle);
		cell = row.createCell(4);
		cell.setCellValue("单价");
		cell.setCellStyle(headerStyle);
		cell = row.createCell(5);
		cell.setCellValue("总价");
		cell.setCellStyle(headerStyle);
		cell = row.createCell(6);
		cell.setCellValue("下单时间");
		cell.setCellStyle(headerStyle);
		
		MemberShoppingInfoResult infoResult = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		HSSFCellStyle style = wb.createCellStyle();
		style.setBorderBottom(BorderStyle.THIN);
		style.setBorderLeft(BorderStyle.THIN);//左边框
		style.setBorderTop(BorderStyle.THIN);//上边框
		style.setBorderRight(BorderStyle.THIN);//右边框
		
//		HSSFCellStyle leftStyle = wb.createCellStyle();
//		leftStyle.setBorderBottom(BorderStyle.THIN);
//		leftStyle.setBorderLeft(BorderStyle.THIN);//左边框
//		leftStyle.setBorderTop(BorderStyle.THIN);//上边框
//		leftStyle.setBorderRight(BorderStyle.THIN);//右边框
//		leftStyle.setAlignment(HorizontalAlignment.RIGHT);
		
		for (int i = 0; i < queryList.size(); i++) {
			row = sheet.createRow((int) i + 1);
			infoResult = queryList.get(i);
			// 第五步，创建单元格，并设置值
			cell = row.createCell(0);
			cell.setCellStyle(style);
			cell.setCellValue(infoResult.getName() == null ? infoResult.getNickname() : infoResult.getName()); //会员姓名
			
			cell = row.createCell(1);
			cell.setCellStyle(style);
			cell.setCellValue(infoResult.getPhone()); //电话
			
			cell = row.createCell(2);
			cell.setCellStyle(style);
			cell.setCellValue(infoResult.getProductName()); //商品名称
			
			cell = row.createCell(3);
			cell.setCellStyle(style);
			cell.setCellValue(infoResult.getQuantity()); //数量
			
			cell = row.createCell(4);
			cell.setCellStyle(style);
			cell.setCellValue(infoResult.getPrice().doubleValue()); //单价
			
			cell = row.createCell(5);
			cell.setCellStyle(style);
			cell.setCellValue(infoResult.getTotalPrice().doubleValue()); //总价
			
			cell = row.createCell(6);
			cell.setCellStyle(style);
			cell.setCellValue(sdf.format(infoResult.getCreateTime())); //下单时间
			
		}
		
		return wb;
	}
	
	
	private List<MemberShoppingInfoResult> getMemberShoppingInfo(String startTime, String endTime) {
		Date start = null;
		Date end = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (!StringUtils.isEmpty(startTime)) {
            String startStr = startTime + " 00:00:00";
            try {
                start = sdf.parse(startStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
		
		if(!StringUtils.isEmpty(endTime)) {
			String endStr = endTime + " 23:59:59";
			try {
                end = sdf.parse(endStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
		}
		return queryDao.selectMemberShoppingInfo(start, end);
	}


}
