package bus.service.impl;

import bus.mapper.BUserPreMapper;
import bus.model.SnowflakeUtil;
import bus.model.dto.*;
import bus.model.po.BUserPrePo;
import bus.model.vo.BCoursePreVo;
import bus.model.po.BCoursePrePo;
import bus.mapper.BCoursePreMapper;

import bus.service.BCoursePreService;
import bus.service.BUserPreService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orcas.common.sso.model.ExtInfo;
import com.orcas.iso.config.common.user.CurrentUserHolder;
import org.springframework.data.web.config.QuerydslWebConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Program: bus
 * @Description: 描述
 * @Author: zy
 * @Date: 2025-03-17 21:07:12
 **/
@Service
public class BCoursePreServiceImpl extends ServiceImpl<BCoursePreMapper, BCoursePrePo> implements BCoursePreService {

    @Autowired
    private BCoursePreMapper bCoursePreMapper;
    @Autowired
    private BUserPreMapper bUserPreMapper;
    @Resource
    private SnowflakeUtil snowflakeUtil;

    @Override
    public BCoursePreTypeDto getDetailPre(String type) {
        QueryWrapper<BCoursePrePo> queryWrapper = new QueryWrapper<>();
        List<BCoursePrePo> list = this.bCoursePreMapper.selectList(queryWrapper);
        Map<String,List<BCoursePrePo>> map = list.stream().collect(Collectors.groupingBy(BCoursePrePo::getType, Collectors.toList()));
        BCoursePreTypeDto typeDto = new BCoursePreTypeDto();
        for (Map.Entry<String, List<BCoursePrePo>> entry : map.entrySet()) {
            List<BCoursePrePo> value = entry.getValue();
            List<BCoursePreDto> bCoursePreDtos = BeanUtil.copyToList(value, BCoursePreDto.class);
            typeDto.setType(entry.getKey());
            typeDto.setBCoursePreDto(bCoursePreDtos);
        }
        // 计算当日、本周六和周日日期
        Date now = new Date();
        String today = DateUtil.format(now, "yyyy-MM-dd");
        String saturday = DateUtil.format(DateUtil.endOfWeek(now), "yyyy-MM-dd");
        String sunday = DateUtil.format(DateUtil.offsetDay(DateUtil.endOfWeek(now), 1), "yyyy-MM-dd");

        BUserPreStatDto statDto = new BUserPreStatDto();
        statDto.setStartDate(DateUtil.parse(today, "yyyy-MM-dd"));
        statDto.setEndDate(DateUtil.parse(sunday, "yyyy-MM-dd"));
        statDto.setType(type);
        // 查询各时间段预约数量
        List<BUserPreCountVo> bUserPreCountVos = bUserPreMapper.countByDateAndType(statDto);
        Map<String,BUserPreCountVo> s = bUserPreCountVos.stream().collect(Collectors.toMap(BUserPreCountVo::getPreId, a->a));

        // 设置各类型预约数量
        typeDto.getBCoursePreDto().forEach(pre -> {
            BUserPreCountVo bUserPreCountVo = s.get(pre.getId());
            if(bUserPreCountVo == null){
                pre.setCounts(0);
            }else{
                pre.setCounts(bUserPreCountVo.getCount());
            }

        });

        return typeDto;
    }

    /**
     * 用户保存预约保存
     *
     * @param dto
     * @return
     */
    @Override
    public void savePre(BUserPreDto dto) {
        String today = null;
        Date now = new Date();
        if(dto.getType().equals("0")){
            today = DateUtil.format(now, "yyyy-MM-dd");
        }else if(dto.getType().equals("1")){
            today = DateUtil.format(DateUtil.endOfWeek(now), "yyyy-MM-dd");
        }else{
            today = DateUtil.format(DateUtil.offsetDay(DateUtil.endOfWeek(now), 1), "yyyy-MM-dd");
        }
        ExtInfo extInfo = CurrentUserHolder.get();
        QueryWrapper<BUserPrePo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("pre_id",dto.getPreId());
        queryWrapper.eq("user_id",extInfo.getUserId());
        queryWrapper.eq("pre_date",today);
        queryWrapper.eq("is_delete",0);
        if(bUserPreMapper.selectList(queryWrapper).size()>0){
            throw new RuntimeException("该时间段已预约");
        }
        BCoursePrePo bCoursePrePo = bCoursePreMapper.selectById(dto.getPreId());
        BUserPrePo po = new BUserPrePo();
        po.setCourseId(bCoursePrePo.getCourseId());
        po.setPreId(dto.getPreId());
        po.setPreDate(DateUtil.parse(today, "yyyy-MM-dd"));
        po.setType(dto.getType());
        po.setUserId(extInfo.getUserId());
        po.setId(snowflakeUtil.snowflakeId());
        po.setCreateTime(new Date());
        po.setUpdateTime(new Date());
        po.setCreatorId(extInfo.getUserId());
        po.setUpdaterId(extInfo.getUserId());
        po.setCreatorName(extInfo.getUserName());
        po.setUpdaterName(extInfo.getUserName());
        bUserPreMapper.insert(po);
    }

    @Override
    public void cancelPre(String preId, String Type) {
        String today = null;
        Date now = new Date();
        if(Type.equals("0")){
            today = DateUtil.format(now, "yyyy-MM-dd");
        }else if(Type.equals("1")){
            today = DateUtil.format(DateUtil.endOfWeek(now), "yyyy-MM-dd");
        }else{
            today = DateUtil.format(DateUtil.offsetDay(DateUtil.endOfWeek(now), 1), "yyyy-MM-dd");
        }
        UpdateWrapper<BUserPrePo> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("pre_id",preId);
        updateWrapper.eq("pre_date",today);
        updateWrapper.set("is_delete",1);
        bUserPreMapper.update(null,updateWrapper);

    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public BCoursePrePo getDetailById(String id){
        return this.bCoursePreMapper.selectById(id);
    }

	/**
     * 保存
     * @param dto
     * @return
     */
    @Override
	public void save(BCoursePreDto dto){
        BCoursePrePo po = new BCoursePrePo();
        BeanUtils.copyProperties(dto,po);
		this.bCoursePreMapper.insert(po);
    }

    /**
    * 列表
    * @param dto
    * @return
    */
    @Override
    public List<BCoursePreVo> list(BCoursePrePageDto dto){
        return this.bCoursePreMapper.list(dto);
    }

	/**
     * 修改
     * @param dto
     * @return
     */
    @Override
    public void update(BCoursePreDto dto){
        BCoursePrePo po = new BCoursePrePo();
        BeanUtils.copyProperties(dto,po);
		bCoursePreMapper.updateById(po);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public void delete(String id){
		bCoursePreMapper.deleteById(id);
    }

    @Override
    public void deleteByCourseId(String courseId) {
        QueryWrapper<BCoursePrePo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        bCoursePreMapper.delete(queryWrapper);
    }
}
