package com.jeeplus.pubmodules.meetingRoom.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.pubmodules.meetingRoom.domain.MeetingRoom;
import com.jeeplus.pubmodules.meetingRoom.mapper.MeetingRoomMapper;
import com.jeeplus.pubmodules.meetingRoom.service.dto.MeetingRoomDTO;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Service
public class MeetingRoomService {

    @Autowired
    private MeetingRoomMapper meetingRoomMapper;


    /**
     * 会议室列表查询
     * @param meetingRoom
     * @param page
     * @return
     */
    public IPage<MeetingRoom> findPageList(MeetingRoom meetingRoom, Page<MeetingRoom> page) throws Exception {
        QueryWrapper<MeetingRoom> meetingRoomQueryWrapper = QueryWrapperGenerator.buildQueryCondition(meetingRoom, MeetingRoom.class);
        if (ObjectUtil.isNotEmpty(meetingRoomQueryWrapper) && StringUtils.isNotBlank(meetingRoom.getCreateById())){
            meetingRoomQueryWrapper.eq("a.create_by_id",meetingRoom.getCreateById());
        }
        meetingRoomQueryWrapper.eq("a.del_flag",0);
        //会议开始时间
        if (meetingRoom.getMeetingDates() != null && meetingRoom.getMeetingDates().length >0){
            meetingRoomQueryWrapper.between("a.start_date",meetingRoom.getMeetingDates()[0],meetingRoom.getMeetingDates()[1]);
        }
        //标题
        if (StringUtils.isNotBlank(meetingRoom.getTitle())){
            meetingRoomQueryWrapper.like("a.title",meetingRoom.getTitle());
        }
        //发起人部门
        if (StringUtils.isNotBlank(meetingRoom.getOfficeId())){
            meetingRoomQueryWrapper.eq("so.id",meetingRoom.getOfficeId());
        }
        //会议室编号
        if (StringUtils.isNotBlank(meetingRoom.getMeetNumber())){
            meetingRoomQueryWrapper.eq("a.meet_number",meetingRoom.getMeetNumber());
        }
        IPage<MeetingRoom> iPage=meetingRoomMapper.findPageList(page,meetingRoomQueryWrapper);
        iPage.getRecords().stream().forEach(item->{
            if (ObjectUtils.isNotEmpty(item.getStartDate()) && ObjectUtils.isNotEmpty(item.getStartTime())){
                item.setStartDateTime(item.getStartDate()+" "+item.getStartTime());
            }else {
                item.setStartDateTime("");
            }
            if (ObjectUtils.isNotEmpty(item.getStartDate()) && ObjectUtils.isNotEmpty(item.getEndTime())){
                item.setEndDateTime(item.getStartDate()+" "+item.getEndTime());
            }else {
                item.setEndDateTime("");
            }

        });

        return iPage;
    }

    /**
     * 会议室新增或修改
     * @param meetingRoomDTO
     * @return
     */
    public String saveForm(MeetingRoomDTO meetingRoomDTO) throws ParseException {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        //创建会议室对象并进行复制
        MeetingRoom meetingRoom = new MeetingRoom();
        BeanUtil.copyProperties(meetingRoomDTO,meetingRoom);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat Format = new SimpleDateFormat("HH:mm");
        if (StringUtils.isNotBlank(meetingRoomDTO.getStartDate())){
            meetingRoom.setStartDate(meetingRoomDTO.getStartDate()); // 会议开始日期
        }
        if (ObjectUtils.isNotEmpty(meetingRoomDTO.getStartTime())){
            meetingRoom.setStartTime(meetingRoomDTO.getStartTime());// 会议开始时间
        }
        if (ObjectUtils.isNotEmpty(meetingRoomDTO.getDuration())){
            Integer timeLong=0;
            //会议时长计算
            if (meetingRoomDTO.getDuration()==30){
                timeLong=30*60;
            }
            if (meetingRoomDTO.getDuration() != 30 && meetingRoomDTO.getDuration() != 24 ){
                timeLong=meetingRoomDTO.getDuration()*60*60;
            }
            /**
             * 会议结束时间
             */
            //将开始时间转为LocalTime
            LocalTime localTime = meetingRoom.getStartTime().toLocalTime();
            //调用plus方法获取timglong之后的时间
            LocalTime plus = localTime.plus(timeLong, ChronoUnit.SECONDS);
            //设置时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            String formattedDate = plus.format(formatter);
            //生成新的time类型的时间
            Time time = Time.valueOf(formattedDate);
            meetingRoom.setEndTime(time);
            //当会议时长为24时意味着全天,那么将结束日期设置为当天最后时间节点即可
            if (meetingRoomDTO.getDuration()==24){
                Time endOfDay = Time.valueOf(LocalTime.of(23, 59, 59));
                meetingRoom.setEndTime(endOfDay);
            }

        }

        meetingRoom.setTitle(meetingRoomDTO.getTitle()); //标题

         //会议时长
        meetingRoom.setDuration(meetingRoomDTO.getDuration());
        meetingRoom.setRemarks(meetingRoomDTO.getRemarks()); //会议说明
        meetingRoom.setUpdateById(userDTO.getId());
        meetingRoom.setUpdateTime(new Date());
        meetingRoom.setDelFlag(0);

        /**
         * 移动端保存所需
         */
        if (StringUtils.isNotBlank(meetingRoomDTO.getCreateById())) {
            meetingRoom.setCreateById(meetingRoomDTO.getCreateById());
            meetingRoom.setUpdateById(meetingRoomDTO.getCreateById());
            //根据用户id查询用户所属的租户id
            UserDTO dto = SpringUtil.getBean(IUserApi.class).getById(meetingRoomDTO.getCreateById());
            meetingRoom.setTenantId(dto.getTenantDTO().getId());
        }


        if (StringUtils.isNotBlank(meetingRoomDTO.getId())){
            meetingRoomMapper.updateById(meetingRoom);
        }else {
            meetingRoom.setCreateById(userDTO.getId());
            meetingRoom.setCreateTime(new Date());
            meetingRoomMapper.insert(meetingRoom);
        }
        return meetingRoom.getId();

    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public MeetingRoomDTO findById(String id) {
        MeetingRoomDTO roomDTO= meetingRoomMapper.findById(id);
        return roomDTO;
    }

    /**
     * 根据id修改状态
     * @param id
     * @param status
     */
    public void updateStatusById(String id, String status) {
        meetingRoomMapper.updateStatusById(id,status);
    }

    /**
     * 根据会议开始时间查询最近结束的会议时间
     * @param startDate
     * @return
     */
    public Map<String, String> checkTime(String startDate,String meetNumber) throws ParseException {
        //格式化输入的开始时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(startDate);
        //获取审核中的会议时间
        List<MeetingRoom> meetingRooms=meetingRoomMapper.checkTime(date,meetNumber);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

        LocalDate curDate = LocalDate.now();//当前日期
        //限制会议选择的时间 并转为time类型
        LocalTime time1 = LocalTime.of(8, 30, 0); // 9:00:00

        Map<String, String> mergedMap = new HashMap<>();

        if (ObjectUtil.isNotEmpty(meetingRooms)){
            for (MeetingRoom meetingRoom : meetingRooms) {
                //将获取到的开始时间和结束时间转为LocalDateTime格式,用以比较
                LocalTime startTimeLocal  = meetingRoom.getStartTime().toLocalTime();
                LocalTime endTimeLocal   = meetingRoom.getEndTime().toLocalTime();

                LocalDateTime startDateTime = LocalDateTime.of(curDate, startTimeLocal);
                LocalDateTime endDateTime = LocalDateTime.of(curDate, endTimeLocal);

                LocalDateTime current = startDateTime;
                //确保开始时间在结束时间之前
                while (!current.isAfter(endDateTime) || current.isEqual(endDateTime)) {
                    String start = current.format(formatter);
                    mergedMap.put(start,start);
                    //计算半小时之后的时间
                    LocalDateTime truncatedTime = current.truncatedTo(ChronoUnit.HOURS).plusMinutes(current.getMinute() / 30 * 30);
                    String truncatedTimeStr = truncatedTime.format(formatter);
                    //存到map中
                    mergedMap.put(truncatedTimeStr,truncatedTimeStr);

                    current = current.plusMinutes(30); // 移到下一个半小时的时间点
                }
            }
        }

        //获取会议预约日期
        DateTimeFormatter formatte = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate1 = LocalDate.parse(startDate, formatte);
        //比较两个日期是否为当天,
        if (curDate.equals(startDate1)){
            //获取当前时间
            LocalTime now = LocalTime.now();
            LocalDateTime nowDate = LocalDateTime.of(curDate, now);//当前时间
            ArrayList<LocalTime> dateList = new ArrayList<>();
            LocalDateTime morning=LocalDateTime.of(curDate, time1); //上午九点
            LocalTime nowTime = nowDate.toLocalTime();//当前时间,精确到分钟
            //将上午九点开始,截止到当前时间,中间的每半个小时存放到集合中
            if (nowDate.isAfter(morning) || nowDate.isEqual(morning)){
                LocalTime currentTime = time1;
                dateList.add(currentTime);
                while (currentTime.isBefore(nowTime) || (currentTime.equals(nowTime) && currentTime.getMinute() <= nowTime.getMinute())) {
                    // 每隔半小时增加currentTime
                    currentTime = currentTime.plus(30, ChronoUnit.MINUTES);
                    if (currentTime.isBefore(nowTime)){
                        dateList.add(currentTime);
                    }

                }
            }
            //将获取到的时间存到map中
            for (LocalTime localTime : dateList) {
                mergedMap.put(localTime.format(formatter),localTime.format(formatter));
            }
        }
        return mergedMap;
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    public String deleteById(String id) {
        meetingRoomMapper.deleteById(id);
        return "删除成功";
    }
}
