package com.sv.service.api;

import com.enums.MoneyLogEnum;
import com.enums.PayTypeEnum;
import com.enums.VipTypeEnum;
import com.github.pagehelper.PageHelper;
import com.sv.dto.api.MemberCardDTO;
import com.sv.dto.api.MemberCardVenuesDTO;
import com.sv.entity.Member;
import com.sv.entity.MemberCard;
import com.sv.entity.MemberCardOrder;
import com.sv.exception.api.ExceptionCodeTemplate;
import com.sv.mapper.MemberCardMapper;
import com.sv.service.api.util.DateUtilCard;
import com.ydd.framework.core.common.Pagination;
import com.ydd.framework.core.common.utils.ValidationUtils;
import com.ydd.framework.core.exception.ServiceException;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Service - 用户会员卡
 *
 * @author lihong
 * @since 2018-08-03
 */
@Service("MemberCardServiceApi")
@Transactional
public class MemberCardService extends BaseServiceImpl {

	private final Logger logger = LoggerFactory.getLogger(MemberCardService.class);

	@Resource
	private MemberCardMapper memberCardMapper;
	@Resource
	private VenueService venueService;
	@Resource
	private MemberService memberService;
	@Resource
	private MemberMoneyLogService memberMoneyLogService;

	/**
	 * 创建用户会员卡
	 *
	 * @param memberCard 用户会员卡
	 */
	@Transactional
    public void save(com.sv.entity.MemberCard memberCard) {
		if (memberCard.getId() != null && memberCard.getId() > 0) {
			// 更新
			memberCardMapper.update(memberCard);
		} else {
			// 新建
			memberCardMapper.insert(memberCard);
		}
	}

	/**
	 * 更新用户会员卡
 	 *
	 * @param memberCard 用户会员卡
	 */
	@Transactional
    public void update(MemberCard memberCard) {
		memberCardMapper.update(memberCard);
	}

	/**
	 * 删除用户会员卡
	 *
	 * @param id 编号
   	 * @return 删除数量
	 */
	@Transactional
    public Integer delete(Integer id) {
		if (id == null || id <= 0) {
			return 0;
		}
		return memberCardMapper.delete(id);
	}

	/**
	 * 删除用户会员卡
	 *
	 * @param ids 编号数组
	 * @return 删除数量
	 */
	@Transactional
    public Integer deleteByIds(Integer[] ids) {
		if (ids == null || ids.length == 0) {
			return 0;
		}
		return memberCardMapper.deleteByIds(ids);
	}

	/**
	 * api
	 * 查询用户会员卡
	 *
	 * @param id 编号
	 * @return 用户会员卡
	 */
	public MemberCard findById(Integer id) {
		MemberCard memberCard = memberCardMapper.findById(id);
		if (memberCard == null){
			throw new ServiceException(ExceptionCodeTemplate.MEMBER_CARD_ERROR);
		}
		long nowTime= System.currentTimeMillis();
		if (memberCard.getEndTime().getTime() < nowTime){
			throw new ServiceException(ExceptionCodeTemplate.MEMBER_CARD_FAIL);
		}
		if (memberCard.getStartTime().getTime() > nowTime){
			throw new ServiceException(ExceptionCodeTemplate.MEMBER_CARD_LIFE);
		}
		return memberCard;
	}

	/**
	 * 查询会员卡
	 */
	public MemberCard findByIds(Integer id) {
		return memberCardMapper.findById(id);
	}
	/**
	 * qpi 免费会员卡状态
	 */
	public MemberCard findByIdCard(Integer id){
		return memberCardMapper.findById(id);
	}

	/**
	 * api 查出会员卡是已激活的卡
	 */
	@Transactional
	public void findByStatus(Integer venueId,Integer venueType,Integer memberId,MemberCard memberCard){
		MemberCard card = memberCardMapper.findByStatus(venueId,venueType,memberId);
		// 修改卡的状态为未激活
		if (card != null){
			card.setStatus(0);
			memberCardMapper.update(card);
		}

		// 修改选中卡的状态为已激活
		memberCard.setStatus(1);
		memberCardMapper.update(memberCard);
	}

	/**
	 * 查询用户会员卡
	 *
	 * @param pagination 分页信息
	 * @return 分页结果
	 */
	public Pagination findPage(Pagination pagination, Integer memberId) {
		PageHelper.startPage(pagination.getPage(), pagination.getPageSize());
		PageHelper.orderBy("id desc");
		pagination.setQueryResult(memberCardMapper.findAlls(memberId));
		return pagination;
	}

	/**
	 * 生成生成用户会员卡
	 */
	@Transactional
	public void createCard(MemberCardOrder memberCardOrder,BigDecimal price){

		MemberCard card = new MemberCard();
		card.setMemberId(memberCardOrder.getMemberId());
		card.setCardType(memberCardOrder.getCardType());
		card.setVeneuType(memberCardOrder.getVeneuType());
		card.setVenueId(memberCardOrder.getVenueId());
		card.setPlatformId(memberCardOrder.getPlatformId());

		// 1. 判断用户是否有其他的会员卡，并且不是免费卡，有效时间顺延
		Date starTime = DateUtilCard.getTime(new Date());
		Date endTime;
		MemberCard memberCard = memberCardMapper.findCard(memberCardOrder.getMemberId(),memberCardOrder.getVeneuType(),memberCardOrder.getVenueId());
		if (memberCard != null ) {
			if (!memberCard.getCardType().equals(VipTypeEnum.getByValue(5).getName())){
				starTime = DateUtilCard.getDay(memberCard.getEndTime());
			}
		}
		if (memberCardOrder.getCardType().equals(VipTypeEnum.YEARCARD.name)){
			endTime = DateUtilCard.getYear(starTime);
		}else{
			endTime = DateUtilCard.getMouth(starTime,memberCardOrder.getCardType());
		}
		card.setStartTime(starTime);
		card.setEndTime(endTime);
		long nowDate = new Date().getTime();
		if(starTime.getTime() <= nowDate && endTime.getTime() >= nowDate && memberCard == null){
			card.setStatus(1);//已激活
		}
		memberCardMapper.insert(card);

		// 2. 记录‘用户账单（余额，微信，会员卡）记录’
		memberMoneyLogService.create(memberCardOrder.getMemberId(),memberCardOrder.getPlatformId(),MoneyLogEnum.VIPCARD.value,
				price.multiply(new BigDecimal(-1)),PayTypeEnum.WEI_XIN.value,memberCardOrder.getCardType(),memberCardOrder.getVenueId(),memberCardOrder.getVeneuType(),null);
	}

	/**
	 * 我的会员卡
	 */
	public List<MemberCardVenuesDTO> findMyVenueCard(Integer memberId){
		Member member = memberService.findById(memberId);
		memberService.verify(member);
		return venueService.findAVenues(member);
	}

	/**
	 * api
	 * 查询用户对应店的会员卡
	 */
	public List<MemberCardDTO> findMemberCardByVenues(Integer memberId,Integer venueId,Integer venueType){
        List<MemberCard> list = memberCardMapper.findMemberCardByVenues( memberId, venueId, venueType);
        List<MemberCardDTO> memberCardDTOS = new ArrayList<>();
        for (MemberCard card : list){
            MemberCardDTO cardDTO = new MemberCardDTO();
            cardDTO.setId(card.getId());
            cardDTO.setCardType(card.getCardType());
            cardDTO.setVenueId(card.getVenueId());
            cardDTO.setVeneuType(card.getVeneuType());
            cardDTO.setStartTime(card.getStartTime());
            cardDTO.setEndTime(card.getEndTime());
            cardDTO.setStatus(card.getStatus());
            if (card.getEndTime().getTime() < System.currentTimeMillis()) {
                cardDTO.setCardFlg(2);
            }
            if (card.getStartTime().getTime() > System.currentTimeMillis()) {
                cardDTO.setCardFlg(1);
            }
            memberCardDTOS.add(cardDTO);
        }
		return memberCardDTOS;
	}

	/**
	 * api 返回用户中心用户拥有会员卡的数量
	 */
	public Integer findMemberCardCount(Integer memberId){
		if (memberId == null){
			throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
		}
		Member member = memberService.findByMember(memberId);
		memberService.verify(member);

		return memberCardMapper.findMemberCardCount(memberId);
	}

    /**
     * api 查询用户有没有对应篮球馆的可使用会员卡
     */
    public List<MemberCard> findByMemberId(Integer venueId,Integer memberId){
        return memberCardMapper.findByMemberId(venueId,memberId);
    }

	public MemberCard findCard(Integer memberId,Integer venueType,Integer venueId){
    	return memberCardMapper.findCard(memberId,venueType,venueId);
	}

	public void insert(MemberCard card){
    	memberCardMapper.insert(card);
	}

	/**
	 * 设置默认会员卡
	 */
	public void updateCardStatus(Integer memberId,Integer cardId){
		// 判断用户信息
		if (memberId == null){
			throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
		}
		Member member = memberService.findById(memberId);
		memberService.verify(member);

		// 参数校验
		ValidationUtils.assertNotNull(cardId,"请选择需要设置的默认卡");

		//修改选中的会员卡的状态为激活状态
		// 修改会员卡的状态为激活状态
		MemberCard memberCard = memberCardMapper.findById(cardId);
		/*if (memberCard.getStatus().intValue() == 1){
			throw new ServiceException("该卡已是默认卡");
		}*/

		// 查出之前的会员卡的状态是已激活的
		findByStatus(memberCard.getVenueId(),memberCard.getVeneuType(),memberId,memberCard);
	}

    /**
     * 查询已过期的会员卡
     */
    public List<MemberCard> findAllCard(){
        return memberCardMapper.findAllCard();
    }

    /**
     * 查询用户顺延的会员卡正好是今日
     */
    public List<MemberCard> findAllMemberCard(List<MemberCard> cards){
        return memberCardMapper.findAllMemberCard(cards);
    }

    /**
     * 修改会员卡激活状态
     */
    public void updateStatus(List<MemberCard> cards,Integer status){
        memberCardMapper.updateStatus(status,cards);
    }

	/**
	 * 查询用户拥有对应店的会员卡
	 */
	public MemberCard findMemberCardByVenue(Integer memberId,Integer venueId,Integer venueType){
		return memberCardMapper.findCards(memberId, venueId, venueType);
	}

}

