package com.sv.api.task;


import com.sv.dto.api.MemberLessonTicketDTO;
import com.sv.entity.MemberLessonTicket;
import com.sv.service.api.MemberLessonTicketService;
import com.sv.service.api.VenueLessonService;
import com.sv.service.api.VenueLessonTicketService;
import com.sv.service.api.util.DateUtilCard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

/**
 * Controller - 检查预约课程，是否超时
 *
 * @author lihong
 * @since 2018-08-11
 */
@Component
public class MemberLessonTickerOrderTask {

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

    @Resource
    private MemberLessonTicketService memberLessonTicketService;
    @Resource
    private VenueLessonTicketService venueLessonTicketService;
    @Resource
    private VenueLessonService venueLessonService;

    /**
     *  每30秒执行一次订单查看
     */
    @Scheduled(fixedDelay = 30000)
    @Transactional(rollbackFor = Exception.class)
    public void execute(){
        // 查询所有未支付订单
        List<MemberLessonTicket> memberLessonTickets = memberLessonTicketService.findOrders();
        if (memberLessonTickets.size() > 0){
            logger.info("开始取消课程");
            List<MemberLessonTicket> lessonIds = memberLessonTicketService.findOrdersLessonId();
            if (lessonIds.size() > 0 ){
                for (MemberLessonTicket lessonId : lessonIds){
                    Integer num = memberLessonTicketService.lessonNum(lessonId.getLessonId());
                    venueLessonService.updateSaleNum(num,lessonId.getLessonId());
                }
            }
            memberLessonTicketService.updateMemberLessonTicketStatus(memberLessonTickets);
            venueLessonTicketService.updateTicketStatus(memberLessonTickets);
        }
        updateExpired();
    }

    /**
     * 修改课程结束，还未签到的状态
     */
    public void updateExpired(){
        // 判断签到是否过期
        List<MemberLessonTicketDTO> ticketDTOS = memberLessonTicketService.findAllExpired();
        for (MemberLessonTicketDTO ticketDTO : ticketDTOS) {
            //判断日期是否在今天之前，过期，直接改状态
            long nowDate = DateUtilCard.getTime(new Date()).getTime();
            long lessonDate = ticketDTO.getDate().getTime();
            LocalTime now = DateUtilCard.nowTime();
            LocalTime lessTIme = ticketDTO.getEndTime();
            boolean compare = now.isAfter(lessTIme);
            if (nowDate > lessonDate) {
                memberLessonTicketService.updateMemberStatus(ticketDTO);
            } else if (compare && nowDate == lessonDate) {
                //日期等于今天，判断上课时间是否结束，是，改状态
                memberLessonTicketService.updateMemberStatus(ticketDTO);
            }
        }
    }
}
