package com.sv.service.api;

import com.enums.*;
import com.github.pagehelper.PageHelper;
import com.sv.dto.api.LessonTicketOrderDTO;
import com.sv.dto.api.MemberLessonTicketDTO;
import com.sv.dto.api.MemberLessonTicketDetailDTO;
import com.sv.dto.api.wechat.OrderPaySignResponse;
import com.sv.entity.*;
import com.sv.exception.api.ExceptionCodeTemplate;
import com.sv.mapper.MemberLessonTicketMapper;
import com.sv.service.api.util.DateUtilCard;
import com.sv.service.common.RedisLock;
import com.ydd.framework.core.common.Pagination;
import com.ydd.framework.core.common.utils.ValidationUtils;
import com.ydd.framework.core.entity.enums.DeletedEnum;
import com.ydd.framework.core.entity.enums.StatusEnum;
import com.ydd.framework.core.exception.ServiceException;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.sv.entity.Constants.LESSON_TICKET_LOCK_KEY;

/**
 * Service - 用户预约的场馆课程票号
 *
 * @author lihong
 * @since 2018-08-06
 */
@Service("MemberLessonTicketServiceApi")
@Transactional
public class MemberLessonTicketService extends BaseServiceImpl {

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

    @Resource
    private MemberLessonTicketMapper memberLessonTicketMapper;
    @Resource
    private MemberService memberService;
    @Resource
    private MemberAuthService memberAuthService;
    @Resource
    private VenueLessonService venueLessonService;
    @Resource
    private VenueLessonTicketService venueLessonTicketService;
    @Resource
    private MemberCardOrderService memberCardOrderService;
    @Resource
    private OrderService orderService;
    @Resource
    private MemberCardService memberCardService;
    @Resource
    private MemberMoneyLogService memberMoneyLogService;
    @Resource
    private MemberRefundService memberRefundService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 创建用户预约的场馆课程票号
     *
     * @param memberLessonTicket 用户预约的场馆课程票号
     */
    @Transactional
    public void save(MemberLessonTicket memberLessonTicket) {
        if (memberLessonTicket.getId() != null && memberLessonTicket.getId() > 0) {
            // 更新
            memberLessonTicketMapper.update(memberLessonTicket);
        } else {
            // 新建
            memberLessonTicketMapper.insert(memberLessonTicket);
        }
    }

    /**
     * 更新用户预约的场馆课程票号
     *
     * @param memberLessonTicket 用户预约的场馆课程票号
     */
    @Transactional
    public void update(MemberLessonTicket memberLessonTicket) {
        memberLessonTicketMapper.update(memberLessonTicket);
    }

    /**
     * 删除用户预约的场馆课程票号
     *
     * @param id 编号
     * @return 删除数量
     */
    @Transactional
    public Integer delete(Integer id) {
        if (id == null || id <= 0) {
            return 0;
        }
        return memberLessonTicketMapper.delete(id);
    }

    /**
     * 删除用户预约的场馆课程票号
     *
     * @param ids 编号数组
     * @return 删除数量
     */
    @Transactional
    public Integer deleteByIds(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return 0;
        }
        return memberLessonTicketMapper.deleteByIds(ids);
    }

    /**
     * 查询用户预约的场馆课程票号
     *
     * @param id 编号
     * @return 用户预约的场馆课程票号
     */
    public MemberLessonTicket findById(Integer id) {
        return memberLessonTicketMapper.findById(id);
    }

    /**
     * 查询用户预约的场馆课程票号
     *
     * @param pagination 分页信息
     * @return 分页结果
     */
    public Pagination findPage(Pagination pagination) {
        PageHelper.startPage(pagination.getPage(), pagination.getPageSize());
        PageHelper.orderBy("id desc");
        pagination.setQueryResult(memberLessonTicketMapper.findAll());
        return pagination;
    }

    /**
     * 更新状态
     *
     * @param ids    编号
     * @param status 状态
     * @return 更新数量
     */
    @Transactional
    public Integer updateStatus(Integer[] ids, Byte status) {
        if (ids == null) {
            return 0;
        }
        if (status == null) {
            status = StatusEnum.DISABLE.value;
        }

        return memberLessonTicketMapper.updateStatus(ids, status);
    }

    /**
     * 预约课程，微信下单LessonTicketOrderDTO
     */
    @Transactional
    public synchronized OrderPaySignResponse.WechatPayParam createOrder(Integer memberId, LessonTicketOrderDTO lessonTicketOrderDTO, Integer platformId, String ip) {

        // 判断用户信息
        if (memberId == null) {
            throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
        }
        Member member = memberService.findById(memberId);
        memberService.verify(member);


        // 判断用户是否使用微信登录
        MemberAuth memberAuth = memberAuthService.findByMemberId(memberId);
        if (memberAuth == null) {
            throw new ServiceException(ExceptionCodeTemplate.BUY_ERROR);
        }

        // 参数校验
        ValidationUtils.assertNotNull(lessonTicketOrderDTO.getLessonId(), "请选择课程");
        ValidationUtils.assertNotNull(lessonTicketOrderDTO.getNum(), "请选择预约人数");

        // 1判断选择的课程是否可预约
        VenueLesson venueLesson = venueLessonService.findById(lessonTicketOrderDTO.getLessonId());
        if (new Integer(1).equals(venueLesson.getType())) {

            // 课程是公益课 判断用户是否可以购买公益课
            memberService.verifyMemberBanType(member);
        }

        venueLessonService.decide(venueLesson, lessonTicketOrderDTO.getNum());
        Integer countByZero = memberLessonTicketMapper.findByZero(memberId, lessonTicketOrderDTO.getLessonId());
        if (countByZero != 0) {
            throw new ServiceException("不可重复预约相同课程");
        }
        // 判断是否预约过，价格为0的课程
        if (venueLesson.getPrice().compareTo(new BigDecimal(0)) == 0) {
            // 校验，微信支付，最多只能预约4人
            if (lessonTicketOrderDTO.getNum().intValue() > 1) {
                throw new ServiceException("最多预约1人");
            }
        } else {
            if (lessonTicketOrderDTO.getNum().intValue() > 4) {
                throw new ServiceException("最多预约4人");
            }
        }

        OrderPaySignResponse.WechatPayParam wechatPayParam = new OrderPaySignResponse.WechatPayParam();
        synchronized (lessonTicketOrderDTO.getLessonId()) {

            // 2.判断票是否足够
            Integer count = venueLessonTicketService.findCount(lessonTicketOrderDTO.getLessonId());
            if (count.intValue() < lessonTicketOrderDTO.getNum().intValue()) {
                throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.LESSON_TICKET_ERROR);
            }
            /**
             * 课程库存锁
             */
            RedisLock redisLock = new RedisLock(redisTemplate, LESSON_TICKET_LOCK_KEY + venueLesson.getId());
            try {
                //加锁
                boolean flag = redisLock.lock();
                if (!flag) {
                    //获取库存锁失败 ，有其他用户获得了锁 不允许继续购买
                    throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.LESSON_TICKET_LOCK_ERROR);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                // 2.1查询场馆课程票号，根据预约人数，查询，并修改状态为已购买,并且判断返回的update条数，判断预约是否成功
                List<VenueLessonTicket> tickets = venueLessonTicketService.updateLessonTicketOrder(count, venueLesson, lessonTicketOrderDTO.getNum());

                // 3.创建用户预约的场馆课程票号
                //预约课程支付订单号
                String orderSn = orderService.createSn();
                createMemberLessonTicket(memberId, tickets, lessonTicketOrderDTO.getLessonId(), orderSn, MemberLessonTicketTypeEnum.PAY.value, platformId, null);

                // 4.创建订单记录
                // 订单总价格，保留2位小数
                BigDecimal totalPrice = venueLesson.getPrice().multiply(new BigDecimal(lessonTicketOrderDTO.getNum()));
                Order order = orderService.createOrder(memberId, orderSn, totalPrice, platformId, PayTypeEnum.WEI_XIN.value, OrderTypeEnum.COURSE_ORDER.value, OrderPayEnum.ORDER_NO_PAY.value);

                // 5.修改课程销售数量
                venueLessonService.updateSaleNumById(lessonTicketOrderDTO.getLessonId(), lessonTicketOrderDTO.getNum(), venueLesson);

                // 判断课程是否是0元
                if (totalPrice.compareTo(new BigDecimal(0)) == 0) {
                    paySuccess(order);
                    wechatPayParam.setOrderSn(order.getOrderSn());
                } else {
                    // 6.调微信支付
                    if (lessonTicketOrderDTO.getType() != null &&
                            lessonTicketOrderDTO.getType().equals(1)) {
                        isEnougthMoney(order.getPrice(), member);
                        memberService.updateMoney(memberId, order.getPrice().negate());
                        paySuccess(order);
                    } else {
                        wechatPayParam = memberCardOrderService.createUnifiedOrder(order.getOrderSn(), memberId, ip);
                    }
                }
                redisLock.unlock();
            } catch (ServiceException e) {
                redisLock.unlock();
                throw e;
            } catch (Exception e) {
                redisLock.unlock();
                throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.SERVER_ERROR);
            }
        }

        return wechatPayParam;
    }

    public void isEnougthMoney(BigDecimal money, Member member) {
        if (member.getMoney().compareTo(money) < 0) {
            throw new ServiceException("余额不足，支付失败");
        }
    }

    /**
     * 预约课程，会员卡支付
     */
    @Transactional
    public synchronized String createOrderByMemberCard(Integer memberId, LessonTicketOrderDTO lessonTicketOrderDTO, Integer platformId) {

        // 判断用户信息
        if (memberId == null) {
            throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
        }
        Member member = memberService.findById(memberId);
        memberService.verify(member);

        // 参数校验
        ValidationUtils.assertNotNull(lessonTicketOrderDTO.getLessonId(), "请选择课程");
        ValidationUtils.assertNotNull(lessonTicketOrderDTO.getNum(), "请选择预约人数");
        ValidationUtils.assertNotNull(lessonTicketOrderDTO.getMemberCardId(), "请选择会员卡");
        // 0.判断会员卡是否可用
        MemberCard memberCard = memberCardService.findById(lessonTicketOrderDTO.getMemberCardId());
        // 0.1判断用户当天是否使用过免费卡预约同课程，免费卡一天只能用一次
        findByMemberId(memberId, lessonTicketOrderDTO.getLessonId(), lessonTicketOrderDTO.getMemberCardId());

        // 会员卡，只能买一个人，并且一天内，对应的课程只能使用一次
        if (lessonTicketOrderDTO.getNum().intValue() > 1) {
            throw new ServiceException("使用会员卡仅能预约一人");
        }
        // 判断当日，是否使用会员卡购买过该课程
        Integer countBuy = memberLessonTicketMapper.findBuyByCard(memberId, lessonTicketOrderDTO.getLessonId());
        if (countBuy > 0) {
            throw new ServiceException("不可重复预约相同课程");
        }

        // 1判断选择的课程是否可预约
        VenueLesson venueLesson = venueLessonService.findById(lessonTicketOrderDTO.getLessonId());
        venueLessonService.decide(venueLesson, lessonTicketOrderDTO.getNum());

        if (memberCard.getVenueId().intValue() != venueLesson.getVenueId().intValue()) {
            throw new ServiceException(ExceptionCodeTemplate.MEMBER_CARD_ERROR);
        }
        //修改选中的会员卡的状态为激活状态
        // 修改会员卡的状态为激活状态
		/*if (memberCard.getStatus().intValue() != 1) {
			// 查出之前的会员卡的状态是已激活的
			memberCardService.findByStatus(memberCard.getVenueId(),memberCard.getVeneuType(),memberId,memberCard);
		}*/
        String orderSn = "";
        synchronized (lessonTicketOrderDTO.getLessonId()) {
            // 2.判断票是否足够
            Integer count = venueLessonTicketService.findCount(lessonTicketOrderDTO.getLessonId());
            if (count.intValue() < lessonTicketOrderDTO.getNum().intValue()) {
                throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.LESSON_TICKET_ERROR);
            }

            // 2.1查询场馆课程票号，根据预约人数，查询，并修改状态为已购买,并且判断返回的update条数，判断预约是否成功
            List<VenueLessonTicket> tickets = venueLessonTicketService.updateLessonTicketOrder(count, venueLesson, lessonTicketOrderDTO.getNum());

            // 3.创建用户预约的场馆课程票号
            orderSn = orderService.createSn(); //预约课程支付订单号
            createMemberLessonTicket(memberId, tickets, lessonTicketOrderDTO.getLessonId(), orderSn, MemberLessonTicketTypeEnum.MEMBER_CARD.value, platformId, lessonTicketOrderDTO.getMemberCardId());

            // 4.创建订单记录
            // 订单总价格
            BigDecimal totalPrice = venueLesson.getPrice().multiply(new BigDecimal(lessonTicketOrderDTO.getNum()));
            Order order = orderService.createOrder(memberId, orderSn, totalPrice, platformId, PayTypeEnum.MEMBER_CARD.value, OrderTypeEnum.COURSE_ORDER.value, OrderPayEnum.PENDING_DELIVERY.value);

            // 5. 记录‘用户账单（余额，微信，会员卡）记录’
            memberMoneyLogService.create(order.getMemberId(), order.getPlatformId(), MoneyLogEnum.BUY_LESSON.value, order.getPrice().multiply(new BigDecimal(-1)), PayTypeEnum.MEMBER_CARD.value,
                    memberCard.getCardType(), null, null, lessonTicketOrderDTO.getLessonId());

            // 6.修改课程销售数量
            venueLessonService.updateSaleNumById(lessonTicketOrderDTO.getLessonId(), lessonTicketOrderDTO.getNum(), venueLesson);
        }


        return orderSn;
    }


    /**
     * 创建用户预约的场馆课程票号记录
     */
    @Transactional
    public void createMemberLessonTicket(Integer memberId, List<VenueLessonTicket> tickets, Integer lessonId, String orderSn,
                                         Integer payType, Integer platformId, Integer memberCardId) {
        for (VenueLessonTicket ticket : tickets) {
            MemberLessonTicket memberLessonTicket = new MemberLessonTicket();
            memberLessonTicket.setVeneuType(ticket.getVenueType());
            memberLessonTicket.setVenueId(ticket.getVenueId());
            memberLessonTicket.setTicketId(ticket.getId());
            memberLessonTicket.setLessonId(ticket.getId());
            memberLessonTicket.setTicket(ticket.getTicket());
            memberLessonTicket.setLessonId(ticket.getLessonId());
            memberLessonTicket.setMemberId(memberId);
            memberLessonTicket.setOrderSn(orderSn);
            memberLessonTicket.setPayType(payType);
            if (memberCardId != null) {
                memberLessonTicket.setMemberCardId(memberCardId);
                memberLessonTicket.setPayStatus(OrderPayEnum.PENDING_DELIVERY.value);
            }
            memberLessonTicket.setPlatformId(platformId);
            memberLessonTicketMapper.insert(memberLessonTicket);
        }
    }

    /**
     * 修改‘用户预约的场馆课程票号’支付状态：1已支付
     */
    @Transactional
    public void paySuccess(Order order) {
        // 根据订单号，查找‘用户预约的场馆课程票号’记录
        List<MemberLessonTicket> memberLessonTickets = memberLessonTicketMapper.findByOrderSn(order.getOrderSn());
        if (memberLessonTickets.size() == 0) {
            return;
        }
        // 修改‘用户预约的场馆课程票号’支付状态：1已支付
        memberLessonTicketMapper.updateTicketStatus(memberLessonTickets);

        // 2. 记录‘用户账单（余额，微信，会员卡）记录’
        Integer venueId = memberLessonTickets.get(0).getVenueId();
        Integer venueType = memberLessonTickets.get(0).getVeneuType();
        Integer lessonId = memberLessonTickets.get(0).getLessonId();
        memberMoneyLogService.create(order.getMemberId(), order.getPlatformId(), MoneyLogEnum.BUY_LESSON.value, order.getPrice().multiply(new BigDecimal(-1)),
                PayTypeEnum.WEI_XIN.value, null, null, null, lessonId);
    }

    /**
     * api 用户预约记录
     */
    public Pagination findMemberLessonTicketReserve(Integer memberId, Pagination pagination, Integer status) {
        // 判断用户信息
        if (memberId == null) {
            throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
        }
        Member member = memberService.findById(memberId);
        memberService.verify(member);
        if (status.intValue() != 1 && status.intValue() != 0) {
            return null;
        }

        PageHelper.startPage(pagination.getPage(), pagination.getPageSize());
        pagination.setQueryResult(memberLessonTicketMapper.findMemberLessonTicketReserve(memberId, status));
        return pagination;
    }

    /**
     * api 预约详情页
     */
    public MemberLessonTicketDetailDTO memberLessonTicketDetail(Integer memberId, String orderSn) {
        if (memberId == null) {
            throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
        }

        // 判断用户信息
        Member member = memberService.findById(memberId);
        memberService.verify(member);

        MemberLessonTicketDetailDTO memberLessonTicketDTO = memberLessonTicketMapper.memberLessonTicketDetail(memberId, orderSn);
        if (memberLessonTicketDTO != null) {
            if (memberLessonTicketDTO.getMemberCardId() != null) {
                memberLessonTicketDTO.setMemberCard(memberCardService.findByIds(memberLessonTicketDTO.getMemberCardId()));
            }
        }
        return memberLessonTicketDTO;
    }

    /**
     * api 取消预约
     */
    public void lessonTicketsCancel(Integer memberId, String orderSn, Integer platformId) {

        // 判断用户信息
        if (memberId == null) {
            throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
        }
        Member member = memberService.findById(memberId);
        memberService.verify(member);

        // 1.根据orderSn查出lesson_id,member_card_id
        MemberLessonTicketDetailDTO memberLessonTicket = memberLessonTicketMapper.memberLessonTicketDetail(memberId, orderSn);
        Integer lessonId = memberLessonTicket.getLessonId();
        Integer memberCardId = memberLessonTicket.getMemberCardId();

        // 2.根据课程ID查询课程的上课时间
        VenueLesson venueLesson = venueLessonService.findById(lessonId);
        if (venueLesson == null || DeletedEnum.YES.value.equals(venueLesson.getDeleted())) {
            throw new ServiceException(ExceptionCodeTemplate.LESSON_CANCEL_NO);
        }
        if (venueLesson.getStatus().intValue() == 0) {
            throw new ServiceException(ExceptionCodeTemplate.LESSON_CANCEL_NO);
        }
        if (memberLessonTicket.getPayStatus().intValue() != 1) {
            throw new ServiceException(ExceptionCodeTemplate.LESSON_ERROR_CANCEL);
        }
        // 一天只能取消一次，所有订单只能一次
        List<MemberLessonTicket> tickets = memberLessonTicketMapper.findCancelNumber(memberId);
        if (tickets.size() > 0) {
            throw new ServiceException(ExceptionCodeTemplate.LESSON_CANCEL_DAY);
        }
        // 3.判断当前时间距离上课时间是否是48小时以外，不是取消失败
        Date date = venueLesson.getDate();
        LocalTime starTime = venueLesson.getStartTime();
        Date lessonDate = DateUtilCard.date(date, starTime); //上课时间
        double between = (lessonDate.getTime() - System.currentTimeMillis()) / 1000; //除以1000是为了转换成秒
        double min = between / 3600;
        DecimalFormat df = new DecimalFormat("#.#");
        Double hour = Double.parseDouble(df.format(min));
        Double subHour = 48D;
        if (hour <= subHour) {
            throw new ServiceException(ExceptionCodeTemplate.LESSON_CANCEL);
        }

        // 4.1 会员卡支付，直接取消成功，‘用户预约的场馆课程票号’-1已取消
        List<MemberLessonTicket> memberLessonTickets = memberLessonTicketMapper.findByOrderSn(orderSn);
        checkMemberLessonTicket(memberLessonTickets);
        //  4.1.1 修改‘用户预约的场馆课程票号’，使用状态为 2 已取消
        memberLessonTicketMapper.updateMemberLessonTicketStatus(memberLessonTickets, 2);

        // 5.释放票据0未购买，课程销售减少
        venueLessonTicketService.updateTicketStatus(memberLessonTickets);
        // 修改课程销售量
        Integer lessonCount = -1 * memberLessonTicket.getLessonCount();
        venueLessonService.updateSaleNumById(memberLessonTicket.getLessonId(), lessonCount);

        // 6 微信支付，退款，
        // 记录到‘用户退款记录表’
        if (memberCardId == null && memberLessonTicket.getPayType().intValue() == 1) {
            MemberRefund memberRefund = memberRefundService.addMemberRefund(memberId, memberLessonTicket, orderSn, platformId);
            Order order = orderService.findOrderSn(orderSn, memberId);
            if (order == null) {
                throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.ORDER_ERROR);
            }
            if (order.getPrice().compareTo(new BigDecimal(0)) == 1) {
                // 调微信退款接口
                memberRefundService.refund(memberRefund);
            }
        }

    }

    /**
     * 校验用户预约的课程是否可以取消
     */
    public void checkMemberLessonTicket(List<MemberLessonTicket> tickets) {
        if (tickets.size() == 0) {
            throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.ORDER_ERROR);
        }
        for (MemberLessonTicket ticket : tickets) {
            if (DeletedEnum.YES.value.equals(ticket.getDeleted())) {
                throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.ORDER_ERROR);
            }
        }
    }

    /**
     * api 查询用户当天是否使用过免费卡
     */
    @Transactional(rollbackFor = Exception.class)
    public void findByMemberId(Integer memberId, Integer lessonId, Integer memberCardId) {
        MemberCard member = memberCardService.findByIdCard(memberCardId);
        if (!(member.getCardType().equals(VipTypeEnum.getByValue(5).getName()))) {
            return;
        }
        List<MemberLessonTicket> memberLessonTickets = memberLessonTicketMapper.findByMemberId(memberId);
        for (MemberLessonTicket card : memberLessonTickets) {
            // 根据会员卡ID查询用户会员卡
            MemberCard memberCard = memberCardService.findByIdCard(card.getMemberCardId());
            if (memberCard != null) {
                if (memberCard.getCardType().equals(VipTypeEnum.getByValue(5).getName())) {
                    throw new ServiceException(ExceptionCodeTemplate.MEMBER_CARD_USER);
                }
            }
        }
    }

    /**
     * 签到
     *
     * @param lessonId 课程ID （原先为老师ID）
     * @param memberId
     * @return
     */
    public String sign(Integer lessonId, Integer memberId) {
        // 判断用户是否登录
        if (memberId == null) {
            throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
        }
        Member member = memberService.findById(memberId);
        memberService.verify(member);

        // 1.根据课程Id，查找对应的课程
        VenueLesson lesson = venueLessonService.findById(lessonId);
        if (lesson == null) {
            throw new ServiceException(ExceptionCodeTemplate.LESSON_SIGN_ERROR);
        }

        // 2.判断用户是否预约该课程
        List<MemberLessonTicket> memberLessonTickets = memberLessonTicketMapper.findByMemberIdAndLessonId(memberId, lessonId);
        if (memberLessonTickets.size() == 0) {
            throw new ServiceException(ExceptionCodeTemplate.LESSON_SIGN_ERROR);
        }

        // 3.修改‘用户预约的场馆课程票号’使用状态: 1已使用
        memberLessonTicketMapper.updateMemberLessonTicketStatus(memberLessonTickets, 1);
        return memberLessonTickets.get(0).getOrderSn();
    }

    /**
     * 查询所有未支付订单
     */
    public List<MemberLessonTicket> findOrders() {
        return memberLessonTicketMapper.findOrders();
    }

    /**
     * api 查询所有未支付订单，课程ID
     */
    public List<MemberLessonTicket> findOrdersLessonId() {
        return memberLessonTicketMapper.findOrdersLessonId();
    }

    /**
     * 未支付课程数量
     */
    public Integer lessonNum(Integer lessonId) {
        return memberLessonTicketMapper.lessonNum(lessonId);
    }

    /**
     * 修改状态
     */
    public void updateMemberLessonTicketStatus(List<MemberLessonTicket> memberLessonTickets) {
        memberLessonTicketMapper.updateMemberLessonTicketStatus(memberLessonTickets, 2);
    }

    /**
     * 查询所有预约课程的用户，签到状态
     */
    public List<MemberLessonTicketDTO> findAllExpired() {
        return memberLessonTicketMapper.findAllExpired();
    }

    /**
     * 修改用于已过期，但未签到的课程状态为3
     */
    public void updateMemberStatus(MemberLessonTicketDTO ticket) {
        //已经过期未签到 判断该课程 是否是公益课
        VenueLesson lesson = venueLessonService.findById(ticket.getLessonId());
        if (lesson != null && new Integer(1).equals(lesson.getType())) {
            //该课程是公益课 判断用户三个月内 是否还有其他未签到的公益课
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());
            now.add(Calendar.MONTH, -3);
            Date threeMonthsAgo = now.getTime();
            List<MemberLessonTicketDetailDTO> tickets = memberLessonTicketMapper.findTicketByStatusAndTime(ticket.getMemberId(), 3, DateFormatUtils.format(threeMonthsAgo, "yyyy-MM-dd HH:mm:ss"), DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            if (tickets.size() > 0) {
                //有未签到的课程  查看该课程是否有公益课程
                for (MemberLessonTicketDetailDTO t : tickets) {
                    if (new Integer(1).equals(t.getVenueLesson().getType())) {
                        //是公益课 加上本次未签到 三个月内超过两次 拉入黑名单
                        memberService.updateMemberBanStatus(ticket.getMemberId(), 1);
                    }
                }
            }

        }
        memberLessonTicketMapper.updateMemberStatus(ticket.getId());
    }
}

