package com.sv.service.common;

import com.enums.VipTypeEnum;
import com.sv.entity.MemberCard;
import com.sv.entity.GiftMemberCard;
import com.sv.entity.MemberCardOrder;
import com.sv.service.api.MemberCardService;
import com.sv.service.api.util.DateUtilCard;
import com.sv.service.oms.GiftMemberCardService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class MemberCardCommonService {

    @Resource
    private MemberCardService memberCardService;

    @Resource
    private GiftMemberCardService giftMemberCardService;

    /**
     * 生成生成用户会员卡
     */
    @Transactional
    public void createCard(Integer memberId,String cardType,Integer venueType,Integer platformId,Integer venueId,Date star,Date end){
        if (memberId == null || cardType == null || venueType == null || platformId == null || venueId == null){
            return;
        }
        MemberCard card = new MemberCard();
        card.setMemberId(memberId);
        card.setCardType(cardType);
        card.setVeneuType(venueType);
        card.setVenueId(venueId);
        card.setPlatformId(platformId);

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

    }

    /**
     * 保存赠送记录
     */
    @Transactional
    public void saveGift(Integer memberId,String cardType,Integer venueType,Integer platformId,Integer venueId){

        GiftMemberCard card = new GiftMemberCard();
        card.setMemberId(memberId);
        card.setCardType(cardType);
        card.setVenueType(venueType);
        card.setVenueId(venueId);
        card.setPlatformId(platformId);

        giftMemberCardService.save(card);

    }
}
