package com.ssj.service.sys.fx.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.fx.domain.MerchantMeal;
import com.ssj.bean.sys.fx.domain.MerchantMealOrder;
import com.ssj.dao.sys.fx.dao.FxQueryDao;
import com.ssj.dao.sys.fx.dao.MerchantMealDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.service.sys.fx.service.MerchantMealOrderService;
import com.ssj.service.sys.fx.service.MerchantMealService;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.sys.fx.service.MerchantSignService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;

@Service
public class MerchantMealServiceImpl extends BaseServiceImpl<MerchantMeal, String> implements MerchantMealService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private MerchantMealDao dao;
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private MerchantMealOrderService mrchantMealOrderService;
	
	@Autowired
	private MerchantSignService merchantSignService;
	
	@Autowired
	private LibVipServiceService libVipServiceService;
	
    @Autowired
    private FxQueryDao queryDao;

	@Override
	public PagingAndSortingRepository<MerchantMeal, String> getDao() {
		return dao;
	}

	@Override
	public MerchantMeal getMerchantMealByMaxEndSignTime(String merchantId) {
		return dao.getMerchantMealByMaxEndSignTime(merchantId);
	}
	
	@Override
	public List<MerchantMeal> findMerchantMealByStatusList(String merchantId) {
		return dao.findMerchantMealByStatusList(merchantId);
	}
	
	@Override
	public List<MerchantMeal> findMerchantMealAll(String merchantId) {
		return dao.findMerchantMealAll(merchantId);
	}
	

	@Override
	public Page<Map<String, Object>> findMerchantMealByPage(Map<String, Object> params, Pageable initPage){
		return queryDao.findMerchantMealPage(params, initPage);
	}
	
	@Override
	public Page<Map<String, Object>> findMerchantMealStatusPage(Map<String, Object> params, Pageable initPage) {
		return queryDao.findMerchantMealStatusPage(params, initPage);
	}
	
	@Override
	public Page<Map<String, Object>> findMerchantCapByPage(Map<String, Object> params, Pageable initPage) {
		return queryDao.findMerchantCapByPage(params, initPage);
	}

	@Override
	@Transactional
	public void saveMerchantMeal(String merchantId, Integer signType,Integer libService, Integer buyMonth, Integer giveMonth,Double unitPrice,Double price) {
		List<MerchantMeal> merchantMeals=new ArrayList<MerchantMeal>();
		Merchant merchant=merchantService.getById(merchantId);
		switch (merchant.getPosType()) {
		case 2:
			MerchantMealOrder mealOrder=new MerchantMealOrder();
			mealOrder.setBuyMonth(buyMonth);
			mealOrder.setGiveMonth(giveMonth);
			mealOrder.setMerchantId(merchantId);
			mealOrder.setLibService(libService);
			mealOrder.setPrice(price);
			mealOrder.setUnitPrice(unitPrice);
			mealOrder.setCreateTime(new Date());
			mealOrder.setType(1);
			mealOrder.setSignType(signType);
			switch (mealOrder.getSignType()) {
			case 1:
				mealOrder.setPortNum(200);
				break;
			case 2:
				mealOrder.setPortNum(200);
				break;
			case 3:
				mealOrder.setPortNum(400);
				break;
			case 4:
				mealOrder.setPortNum(200);
				break;
			case 5:
				mealOrder.setPortNum(400);
				break;
			default:
				mealOrder.setPortNum(0);
				break;
			}
			mrchantMealOrderService.save(mealOrder);
			
			//端口商户的处理,
			Date signTime=new Date();
			MerchantMeal merchantMeal=this.getMerchantMealByMaxEndSignTime(merchantId);	
			if(merchantMeal!=null ) {
				if(merchantMeal.getEndSignTime().getTime()>=new Date().getTime()) {
					signTime=merchantMeal.getEndSignTime();
				}
			}else {
				if(merchant.getComputeTime()!=null) {
					signTime=merchant.getComputeTime();
				}else {
					signTime=merchant.getActiveTime();
				}
			}
			Date endSignTime=DateHelper.getMonthDate(signTime,1);
			//添加赠送的记录
			for (int i =1; i <=giveMonth; i++) {
				MerchantMeal meal=new MerchantMeal();
				meal.setMerchantId(merchantId);
				meal.setSignTime(signTime);
				meal.setEndSignTime(DateHelper.getMonthDate(signTime,1));
				meal.setSignType(signType);
				meal.setStatus(1);
				meal.setLibService(libService);
				meal.setCreateTime(new Date());
				meal.setOrderId(mealOrder.getId());
				merchantMeals.add(meal);
				
				signTime=endSignTime;
				endSignTime=DateHelper.getMonthDate(signTime,1);
			}
			
			//添加购买的记录
			for (int i =1; i <=buyMonth; i++) {
				MerchantMeal meal=new MerchantMeal();
				meal.setMerchantId(merchantId);
				meal.setSignTime(signTime);
				meal.setEndSignTime(endSignTime);
				meal.setSignType(signType);
				meal.setStatus(1);
				meal.setLibService(libService);
				meal.setCreateTime(new Date());
				meal.setOrderId(mealOrder.getId());
				merchantMeals.add(meal);
				
				signTime=endSignTime;
				endSignTime=DateHelper.getMonthDate(signTime,1);
			}
			
			this.save(merchantMeals);
			
			updateMerchantByMeal(merchantId);
			
			break;
		default:
			break;
		}
	}

	@Override
	@Transactional
	public void saveMerchantMealSC(String merchantId, Integer signType, Integer libService, String startActiveTime,String endActiveTime,Double unitPrice, Double price) {
		List<MerchantMeal> merchantMeals=new ArrayList<MerchantMeal>();
		Merchant merchant=merchantService.getById(merchantId);
		switch (merchant.getPosType()) {
		case 3:
			Integer month=DateHelper.getDifferMonth(DateHelper.parseDate(startActiveTime, "yyyy-MM-dd"),DateHelper.parseDate(endActiveTime, "yyyy-MM-dd"));
			
			MerchantMealOrder mealOrder=new MerchantMealOrder();
			mealOrder.setBuyMonth(month);
			mealOrder.setGiveMonth(0);
			mealOrder.setSignTime(DateHelper.parseDate(startActiveTime, "yyyy-MM-dd"));
			mealOrder.setEndSignTime(DateHelper.parseDate(endActiveTime, "yyyy-MM-dd"));
			mealOrder.setMerchantId(merchantId);
			mealOrder.setLibService(libService);
			mealOrder.setPrice(price);
			mealOrder.setUnitPrice(unitPrice);
			mealOrder.setCreateTime(new Date());
			mealOrder.setType(2);
			mealOrder.setSignType(signType);
			switch (mealOrder.getSignType()) {
			case 1:
				mealOrder.setPortNum(200);
				break;
			case 2:
				mealOrder.setPortNum(200);
				break;
			case 3:
				mealOrder.setPortNum(400);
				break;
			case 4:
				mealOrder.setPortNum(200);
				break;
			case 5:
				mealOrder.setPortNum(400);
				break;
			default:
				mealOrder.setPortNum(0);
				break;
			}
			mrchantMealOrderService.save(mealOrder);
			
			Date signTime=DateHelper.parseDate(startActiveTime, "yyyy-MM-dd");
			Date endSignTime=DateHelper.getMonthDate(signTime,1);
			//添加购买的记录
			for (int i =1; i <=month; i++) {
				MerchantMeal meal=new MerchantMeal();
				meal.setMerchantId(merchantId);
				meal.setSignTime(signTime);
				if(month==i) {
					meal.setEndSignTime(DateHelper.parseDate(endActiveTime, "yyyy-MM-dd"));
				}else {
					meal.setEndSignTime(endSignTime);
				}
				meal.setSignType(signType);
				meal.setStatus(1);
				meal.setLibService(libService);
				meal.setCreateTime(new Date());
				meal.setOrderId(mealOrder.getId());
				merchantMeals.add(meal);
				
				signTime=endSignTime;
				endSignTime=DateHelper.getMonthDate(signTime,1);
			}
			
			this.save(merchantMeals);

			updateMerchantByMeal(merchantId);
			
			break;
		default:
			break;
		}
	}
	
	
	//激活日期间，如提前激活了就对所有的服务包做减天处理。
	public void updateMerchantByActiveTime(String merchantId,Date activeTime) {
		activeTime=DateHelper.parseDate(DateHelper.format(activeTime, "yyyy-MM-dd"), "yyyy-MM-dd");//转换一下日期，转为0点的状态。
		Merchant merchant=merchantService.getById(merchantId);
		if(merchant.getPosType()!=2) {
			//不是端口商户的，直接不处理。
			return ;
		}
		if(activeTime.getTime()>=merchant.getActiveTime().getTime()) {
			//激活日期大于或等于商户设置的激活日期，直接不处理。
			return ;
		}
		
		
		
		
		
		
	}
	

	//更新商户的有效服务
	//端口商户，查询MerchantMeal表的数据，最新当前时间段的数据，更新到Merchant-》endActiveTime，signType，libService
	//学校商户，查询MerchantMealOrder最新当前时间段的数据，更新Merchant-》startActiveTime,activeTime,endActiveTime,signType,libService。
	//调用openapi接口，更新数据到libjoin表。
	@Override
	public void updateMerchantByMeal(String merchantId) {
		Merchant merchant=merchantService.getById(merchantId);
		switch (merchant.getPosType()) {
		case 2://端口商户
			
			//查询结束时间最大的数据。
			MerchantMeal maxMerchantMeal=dao.getMerchantMealByMaxEndSignTime(merchantId);
			//查询当前日期在服务期段的数据
			MerchantMeal merchantMeal=dao.getMerchantMealByCurTime(merchantId);
			if(merchantMeal==null) {
				//查出大于今天的服务数据
				merchantMeal=dao.getMerchantMealByCurSignTime(merchantId);
			}
			if(merchantMeal==null) {
				//查出没有大于今天的服务数据，就取最大的数据。
				merchantMeal=maxMerchantMeal;
			}
			
			if(maxMerchantMeal!=null && merchantMeal!=null) {
				MerchantMealOrder merchantMealOrder=mrchantMealOrderService.getById(maxMerchantMeal.getOrderId());
				merchant.setEndActiveTime(maxMerchantMeal.getEndSignTime());
				merchant.setSignType(merchantMeal.getSignType());
				merchant.setPortNum(merchantMealOrder!=null ? merchantMealOrder.getPortNum() : 0);
				merchant.setLibService(merchantMeal.getLibService()+merchantSignService.getMerchantSignByCurLibService(merchantId));
				merchantService.save(merchant);
				
				//调用openApi接口
				if(StringUtils.isNotEmpty(merchant.getLibId())) {
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					libVipServiceService.openApiServiceCRM(
							3,
							merchant.getLibId(), 
							merchant.getSignType(),
							merchant.getMealType(),
							merchant.getLibService(),
							merchant.getStartActiveTime()!=null ? format.format(merchant.getStartActiveTime()) : "",
							merchant.getStartActiveTime()!=null ? format.format(merchant.getStartActiveTime()) : "",
							merchant.getEndActiveTime()!=null ? format.format(merchant.getEndActiveTime()) : ""
							);
				}
			}
			break;
		case 3:
			//学校商户
			MerchantMealOrder merchantMealOrder=mrchantMealOrderService.getMerchantMealOrderByCurTime(merchantId);
			if(merchantMealOrder==null) {
				merchantMealOrder=mrchantMealOrderService.getMerchantMealOrderByMaxCreateTime(merchantId);
			}
			
			if(merchantMealOrder!=null) {
				merchant.setStartActiveTime(merchantMealOrder.getSignTime());
				merchant.setActiveTime(merchantMealOrder.getSignTime());
				merchant.setEndActiveTime(merchantMealOrder.getEndSignTime());
				merchant.setSignType(merchantMealOrder.getSignType());
				merchant.setPortNum(merchantMealOrder.getPortNum());
				merchant.setLibService(merchantMealOrder.getLibService()+merchantSignService.getMerchantSignByCurLibService(merchantId));
				merchantService.save(merchant);
				
				//调用openApi接口
				if(StringUtils.isNotEmpty(merchant.getLibId())) {
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					libVipServiceService.openApiServiceCRM(
							3,
							merchant.getLibId(), 
							merchant.getSignType(),
							merchant.getMealType(),
							merchant.getLibService(),
							merchant.getStartActiveTime()!=null ? format.format(merchant.getStartActiveTime()) : "",
							merchant.getStartActiveTime()!=null ? format.format(merchant.getStartActiveTime()) : "",
							merchant.getEndActiveTime()!=null ? format.format(merchant.getEndActiveTime()) : ""
							);
				}
			}
			break;
		default:
			break;
		}
		
	}


}


