package com.sv.service.api;

import com.github.pagehelper.PageHelper;
import com.sv.dto.api.VenueLessonDTO;
import com.sv.entity.Member;
import com.sv.entity.MemberLessonTicket;
import com.sv.entity.VenueLesson;
import com.sv.entity.VenueLessonTicket;
import com.sv.mapper.VenueLessonMapper;
import com.sv.service.api.util.DateUtilCard;
import com.sv.service.api.util.WeekDayUtil;
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.exception.ExceptionCodeTemplate;
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.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Service - 场馆课程
 *
 * @author lihong
 * @since 2018-08-06
 */
@Service("VenueLessonServiceApi")
@Transactional
public class VenueLessonService extends BaseServiceImpl {

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

	@Resource
	private VenueLessonMapper venueLessonMapper;
	@Resource
	private MemberService memberService;
	@Resource
    private VenueLessonTicketService venueLessonTicketService;

	/**
	 * 创建场馆课程
	 *
	 * @param venueLesson 场馆课程
	 */
	@Transactional
    public void save(VenueLesson venueLesson) {
		if (venueLesson.getId() != null && venueLesson.getId() > 0) {
			// 更新
			venueLessonMapper.update(venueLesson);
		} else {
			// 新建
			venueLessonMapper.insert(venueLesson);
		}
	}

	/**
	 * 更新场馆课程
 	 *
	 * @param venueLesson 场馆课程
	 */
	@Transactional
    public void update(VenueLesson venueLesson) {
		venueLessonMapper.update(venueLesson);
	}

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

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

	/**
	 * api
	 * 查询场馆课程
	 *
	 * @param id 编号
	 * @return 场馆课程
	 */
	public VenueLesson findById(Integer id) {
		return venueLessonMapper.findById(id);
	}

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

	/**
	 * api
	 * 健身馆对应的课程
	 */
	public List<VenueLessonDTO> show(Integer venueId, Integer type){
        //参数校验
        ValidationUtils.assertNotNull(venueId);
        ValidationUtils.assertNotNull(type);
		// 1.查出当前日期，并查出上周一和下下周日
		Date geLastWeekMonday = WeekDayUtil.getLastWeekMonday(new Date());
		// 2.查询出下下周日
		Date getWeekDays = WeekDayUtil.getWeekDays(2);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 查出从上周一到下下周日的所有日期
		List<Date> listDate = WeekDayUtil.getDatesBetweenTwoDate(geLastWeekMonday,getWeekDays);
		List<VenueLessonDTO> venueLessonDTOList = new ArrayList<>();
		try {
			for (int i = 0;i<listDate.size();i++){
				Integer flg = 0;
				VenueLessonDTO venueLessonDTO = new VenueLessonDTO();
				//查询有哪些日期是有课可以预约
				LocalTime time = DateUtilCard.nowTime();
				String nowTime = null;
				if (sdf.parse(sdf.format(listDate.get(i))).getTime() >= sdf.parse(sdf.format(new Date())).getTime()){
					//查询可预约的课程
					List<VenueLesson> lessons = venueLessonMapper.findBook(venueId,type, sdf.format(listDate.get(i)));
					Integer sum = venueLessonMapper.findBooks(venueId,type, sdf.format(listDate.get(i)));
					venueLessonDTO.setDateList(listDate.get(i));
					if (lessons.size() > 0){
						for (VenueLesson lesson : lessons){
							if (lesson.getNum() > lesson.getSaleNum()){
								//可预约
								flg = 1;
								break;
							}
						}
					}
					if (flg == 1){
						venueLessonDTO.setFlg(1);
					}else if (sum > 0){
						venueLessonDTO.setFlg(2);
					}
					venueLessonDTOList.add(venueLessonDTO);
				}else{ // 过期日期
					nowTime = time.toString();
					//查询过期时间是否有课程
					List<VenueLesson> lessons = venueLessonMapper.findBook(venueId,type, sdf.format(listDate.get(i)));
					venueLessonDTO.setDateList(listDate.get(i));
					if (lessons.size() > 0){
						//有课
						venueLessonDTO.setFlg(2);
					}
					venueLessonDTOList.add(venueLessonDTO);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}

		return venueLessonDTOList;
	}

    /**
     * api
     * 查询预约课程上课时间对应的课程
     */
    public List<VenueLessonDTO> lessonShow(Integer venueId,Integer type,String date){
        //参数校验
        ValidationUtils.assertNotNull(venueId);
        ValidationUtils.assertNotNull(type);
        ValidationUtils.assertNotNull(date);
       List<VenueLessonDTO> list =  venueLessonMapper.lessonShow(date,venueId,type);
       for (VenueLessonDTO listDto : list){
//		   Integer count = venueLessonTicketService.findNum(listDto.getId());
//		   VenueLesson venueLesson = venueLessonMapper.findById(listDto.getId());
//		   venueLesson.setSaleNum(count);
//		   venueLessonMapper.update(venueLesson);
		   long nowDate = DateUtilCard.getTime(new Date()).getTime();
		   long lessonDate = listDto.getDate().getTime();
           LocalTime now = DateUtilCard.nowTime();
           LocalTime lessTIme = listDto.getStartTime();
           boolean compare = now.isAfter(lessTIme);
		   if (nowDate > lessonDate){
			   listDto.setFlg(1);
		   }else if(compare && nowDate == lessonDate){
			   listDto.setFlg(1);
		   } else if (listDto.getSaleNum().intValue() == listDto.getNum().intValue()){
			   listDto.setFlg(2);
		   }
       }
       return list;
    }

	/**
	 * api
	 * 课程详情
	 */
	public VenueLessonDTO findDetail(Integer lessonId){
		VenueLessonDTO venueLessonDTO = venueLessonMapper.findByLessonId(lessonId);
		if (venueLessonDTO != null) {
			Integer sub = venueLessonDTO.getNum().intValue() - venueLessonDTO.getSaleNum().intValue();
			venueLessonDTO.setFlg(sub);
		}
		return venueLessonDTO;
	}

	/**
	 *api  预约课程确认订单页面
	 * @param memberId 用户ID
	 * @param venueId 场馆ID
	 * @param venueType 场馆类型
	 * @param lessonId 课程ID
	 * @return
	 */
	public VenueLessonDTO findLessonOrder(Integer memberId,Integer venueId,Integer venueType,Integer lessonId){

		// 判断用户是否登录
		if (memberId == null){
			throw new ServiceException(ExceptionCodeTemplate.NEED_LOGIN);
		}
		Member member = memberService.findById(memberId);
		memberService.verify(member);

		// 参数校验
		ValidationUtils.assertNotNull(venueId);
		ValidationUtils.assertNotNull(venueType);
		ValidationUtils.assertNotNull(lessonId);

		// 只能拿会员卡，或者微信支付
		VenueLessonDTO venueLesson = venueLessonMapper.findByLessonAndMemberCard(venueId,venueType,lessonId);
		return venueLesson;
	}

	/**
	 * api 判断课程状态
	 */
	public void decide(VenueLesson venueLesson,Integer num){
		if (venueLesson == null || DeletedEnum.YES.value.equals(venueLesson.getDeleted())) {
			throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.ORDER_ERROR);
		}
		if(venueLesson.getStatus().intValue() == 0){
			throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.LESSON_ERROR);
		}
		if(venueLesson.getSaleNum().intValue() == venueLesson.getNum().intValue()){
			throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.LESSON_FULL);
		}
		Integer subNum = venueLesson.getNum().intValue() - venueLesson.getSaleNum().intValue();
		if (num.intValue() > subNum.intValue()){
			throw new ServiceException("库存不足，无法预约");
		}

		long nowDate = DateUtilCard.getTime(new Date()).getTime();
		long lessonDate = venueLesson.getDate().getTime();

		LocalTime now = DateUtilCard.nowTime();
		LocalTime lessTIme = venueLesson.getStartTime();
		boolean compare = now.isAfter(lessTIme);
		if (nowDate > lessonDate){
			throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.LESSON_END);
		}else if (compare && nowDate == lessonDate) {
			throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.LESSON_END);
		}
	}

	/**
	 * api 修改课程销售数量
	 */
	@Transactional
	public void updateSaleNumById(Integer lessonId, Integer num,VenueLesson lesson){
		decide(lesson,num);
		venueLessonMapper.updateSaleNumById(lessonId,num);
	}

	/**
	 * 修改课程销售量
	 */
	@Transactional
	public void updateSaleNumById(Integer lessonId,Integer num){
		venueLessonMapper.updateSaleNumById(lessonId,num);
	}

	/**
	 * 签到查询对应的课程
	 */
	public VenueLesson findLessonByTime(Integer coachId,Date date,String nowTime){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowDate = sdf.format(date);
		VenueLesson venueLesson = venueLessonMapper.findLessonByTime(coachId,nowDate,nowTime);
		return venueLesson;
	}

	/**
	 * 修改库存
	 */
	@Transactional
	public void updateSaleNum(Integer num,Integer lessonId){
		venueLessonMapper.updateSaleNumBy(num,lessonId);
	}
}

