package com.jeeplus.business.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.business.meetingRoom.domain.MeetingRoom;
import com.jeeplus.business.meetingRoom.mapper.MeetingRoomMapper;
import com.jeeplus.business.meetingRoom.service.dto.MeetingRoomDTO;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.joda.time.Period;
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.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
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());
        }
        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("");
            }

        });

        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()==1 || meetingRoomDTO.getDuration()==2 || meetingRoomDTO.getDuration()==3){
                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);
        }

        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.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) throws ParseException {
        //格式化输入的开始时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(startDate);

        List<MeetingRoom> meetingRooms=meetingRoomMapper.checkTime(date);
        ArrayList<Map<String, String>> strings = new ArrayList<>();

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


        //限制会议选择的时间 并转为time类型
        LocalTime time1 = LocalTime.of(9, 0, 0); // 9:00:00
        String date1 = time1.format(formatter);
        Time am1 = Time.valueOf(date1);
        LocalTime time2 = LocalTime.of(11, 30, 0); // 11:30:00
        String date2 = time2.format(formatter);
        Time am2 = Time.valueOf(date2);
        LocalTime time3 = LocalTime.of(14, 0, 0); // 14:00:00
        String date3 = time3.format(formatter);
        Time pm1 = Time.valueOf(date3);
        LocalTime time4 = LocalTime.of(17, 0, 0); // 17:00:00
        String date4 = time4.format(formatter);
        Time pm2 = Time.valueOf(date4);

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

        if (ObjectUtil.isNotEmpty(meetingRooms)){
            List<Map<String, String>> meetingRoomMaps = new ArrayList<>();
            for (MeetingRoom meetingRoom : meetingRooms) {
                HashMap<String, String> hashMap = new HashMap<>();
                //判断会议结束后的半小时是否在规定范围内
                LocalTime newEndTime = meetingRoom.getEndTime().toLocalTime().plus(30 * 60, ChronoUnit.SECONDS);
                String format = newEndTime.format(formatter);
                Time endTime = Time.valueOf(format);
                if ((endTime.after(am1) && endTime.before(am2)) || (endTime.after(pm1) && endTime.before(pm2))) {
                    //创建集合将获取到的开始时间存到集合中
                    LocalTime localTime = meetingRoom.getStartTime().toLocalTime();
                    hashMap.put("0", meetingRoom.getStartTime().toString());
                    //将开始时间之后的每半小时的时间存到map中
                    for (int i = 0; i < 48; i++) {
                        int minute = localTime.getMinute();
                        if (minute < 30) {
                            localTime = localTime.withMinute(30);
                        } else {
                            localTime = localTime.withMinute(0).plusHours(1);
                        }
                        hashMap.put((i + 1) + "", localTime.format(formatter));
                        //当新时间与会议结束时间一致时,在延续半小时,循环结束
                        Time time = Time.valueOf(localTime.format(formatter));
                        if (time.equals(meetingRoom.getEndTime())) {
                            /*int m = localTime.getMinute();
                            if (m < 30) {
                                localTime = localTime.withMinute(30);
                            } else {
                                localTime = localTime.withMinute(0).plusHours(1);
                            }
                            hashMap.put((i + 2) + "", localTime.format(formatter));*/
                            break;
                        }
                    }

                }else {
                    Map<String, String> emptyMap = new HashMap<>();
                    meetingRoomMaps.add(emptyMap);
                }
                hashMap.put("0", meetingRoom.getStartTime().toString());
                meetingRoomMaps.add(hashMap); // 将当前会议的映射添加到列表中
            }
            //将找到的时间重新存入到新的map中
            if (ObjectUtils.isNotEmpty(meetingRoomMaps)){
                for (Map<String, String> map : meetingRoomMaps) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue();
                        if (mergedMap.containsKey(key)) {
                            int size = mergedMap.size();
                            mergedMap.put((size+1)+"",value);
                        } else {
                            mergedMap.put(key, value);
                        }
                    }
                }
            }

        }
        //获取当前时间
        LocalTime now = LocalTime.now();
        String format1 = now.format(formatter);
        Time nowDate = Time.valueOf(format1);
        ArrayList<LocalTime> dateList = new ArrayList<>();
        //判断当前时间在哪个范围内
        if ((nowDate.after(am1) && nowDate.before(am2))){
            // 获取时间段内的所有时间
            LocalTime currentTime = time1;
            dateList.add(currentTime);
            while (currentTime.isBefore(time2)) {
                currentTime = currentTime.plus(30 * 60, ChronoUnit.SECONDS); // 每隔半小时
                dateList.add(currentTime);
            }
            //将每半个小时的时间进行遍历,与当前时间比较
            for (LocalTime localTime : dateList) {
                Time time = Time.valueOf(localTime);
                //如果当前时间在每半小时间隔之后,则将之前的存到map中
                if (nowDate.after(time)){
                    mergedMap.put(time+"",localTime.format(formatter));
                }
            }
        }
        if ((nowDate.after(pm1) && nowDate.before(pm2))){
            // 获取时间段内的所有时间
            LocalTime currentTime = time3;
            while (currentTime.isBefore(time4)) {
                currentTime = currentTime.plus(30 * 60, ChronoUnit.SECONDS); // 每隔半小时
                dateList.add(currentTime);
            }
            //将每半个小时的时间进行遍历,与当前时间比较
            for (LocalTime localTime : dateList) {
                Time time = Time.valueOf(localTime);
                //如果当前时间在每半小时间隔之后,则将之前的存到map中
                if (nowDate.after(time)){
                    mergedMap.put(time+"",localTime.format(formatter));
                }
            }
        }

        return mergedMap;
    }

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