package com.xueyi.system.meeting.controller.api;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xueyi.common.cache.utils.SourceUtil;
import com.xueyi.common.core.constant.basic.SecurityConstants;
import com.xueyi.common.core.constant.basic.SqlConstants;
import com.xueyi.common.core.utils.core.ObjectUtil;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.security.annotation.InnerAuth;
import com.xueyi.common.sms.configure.SmsProperties;
import com.xueyi.common.web.constant.ResponseCode;
import com.xueyi.common.web.utils.DateUtils;
import com.xueyi.nlt.api.netty.domain.vo.DmWebSocketMessageVo;
import com.xueyi.nlt.api.netty.feign.RemoteWebsocketService;
import com.xueyi.nlt.api.nlt.feign.RemoteIntentService;
import com.xueyi.system.api.digitalmans.domain.dto.DmManDeviceDto;
import com.xueyi.system.api.digitalmans.domain.po.DmDigitalmanExtPo;
import com.xueyi.system.api.digitalmans.domain.po.DmDigitalmanPo;
import com.xueyi.system.api.digitalmans.feign.RemoteManDeviceService;
import com.xueyi.system.api.meeting.domain.dto.DmMeetingOrdersDto;
import com.xueyi.system.api.meeting.domain.dto.DmMeetingRoomsDto;
import com.xueyi.system.api.meeting.domain.po.DmMeetingOrdersPo;
import com.xueyi.system.api.meeting.domain.po.DmMeetingRoomsPo;
import com.xueyi.system.api.model.Source;
import com.xueyi.system.api.sms.domain.vo.SmsReqEntity;
import com.xueyi.system.api.sms.feign.RemoteSmsService;
import com.xueyi.system.api.staff.domain.po.DmStaffPo;
import com.xueyi.system.digitalmans.mapper.DmDigitalmanExtMapper;
import com.xueyi.system.digitalmans.mapper.DmDigitalmanMapper;
import com.xueyi.system.meeting.domain.model.DmMeetingOrdersConverter;
import com.xueyi.system.meeting.domain.model.DmMeetingRoomsConverter;
import com.xueyi.system.meeting.mapper.DmMeetingOrdersMapper;
import com.xueyi.system.meeting.mapper.DmMeetingRoomsMapper;
import com.xueyi.system.meeting.service.impl.DmMeetingOrdersServiceImpl;
import com.xueyi.system.meeting.service.impl.DmMeetingRoomsServiceImpl;
import com.xueyi.system.resource.controller.api.BaseApiController;
import com.xueyi.system.staff.mapper.DmStaffMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会议室预约管理 API
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/meeting/inner-api")
public class DmMeetingInnerApiController extends BaseApiController {

    private static final Logger log = LoggerFactory.getLogger(DmMeetingInnerApiController.class);
    @Autowired
    private DmMeetingRoomsMapper dmMeetingRoomsMapper;

    @Autowired
    private DmMeetingOrdersMapper dmMeetingOrdersMapper;

    @Autowired
    private DmStaffMapper dmStaffMapper;

    @Autowired
    private DmMeetingRoomsServiceImpl dmMeetingRoomsService;

    @Autowired
    private DmMeetingOrdersConverter dmMeetingOrdersConverter;

    @Autowired
    private SmsProperties smsProperties;
    @Autowired
    private DmMeetingOrdersServiceImpl dmMeetingOrdersService;

    @Autowired
    private RemoteSmsService remoteSmsService;

    @Autowired
    private DmDigitalmanMapper digitalmanMapper;

    @Autowired
    private DmDigitalmanExtMapper digitalmanExtMapper;


    @Autowired
    private DmMeetingRoomsConverter dmMeetingRoomsConverter;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RemoteWebsocketService remoteWebsocketService;

    @Autowired
    private RemoteIntentService remoteIntentService;
    @Autowired
    private RemoteManDeviceService manDeviceService;


    @InnerAuth
    @GetMapping("/rooms/{deptId}")
    public R<List<DmMeetingRoomsDto>> listInner(@RequestParam(value = "deptId") Long deptId, HttpServletRequest request) {

        DmMeetingRoomsPo dm = new DmMeetingRoomsPo();
        dm.setDeptId(deptId);
        List<DmMeetingRoomsPo> pos = dmMeetingRoomsMapper.selectRoomList(dm);
        List<DmMeetingRoomsDto> dtoList = new ArrayList<>();
        pos.forEach(item -> {
            DmMeetingRoomsDto di = dmMeetingRoomsConverter.mapperDto(item);
            dtoList.add(di);
        });
        return R.ok(dtoList);
    }

    @InnerAuth
    @PostMapping(value = "/save")
    public JSONObject saveInner(@RequestBody DmMeetingOrdersDto order, HttpServletRequest request) {
        log.info("saveInner order:{}", order);
        String orderData = order.getOrderData();
        JSONArray jsonArray = JSONArray.parseArray(orderData);
        if (jsonArray.isEmpty()) {
            return output(ResponseCode.ILLEGAL_PARAMETER, "orderData").toJSON();
        }
        List<DmMeetingOrdersPo> list = new ArrayList<>();
        StringBuilder mms = new StringBuilder();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("HH:mm");

        DmMeetingRoomsPo meetingRoom = dmMeetingRoomsService.selectById(order.getSpaceId().toString());
        if (null == meetingRoom){
            return output(ResponseCode.ILLEGAL_PARAMETER, "spaceId").toJSON();
        }
        for (Object js : jsonArray) {
            JSONObject temp = (JSONObject) js;
            String date = temp.getString("date");
            JSONArray timeList = temp.getJSONArray("timeList");
            for (Object timeStr : timeList) {
                String times = (String) timeStr;
                String[] timeAry = times.split("-");

                Date orderDate = DateUtils.parseStrToDate(date + " " + timeAry[0], "yyyy-MM-dd HH:mm");
                Date endDate = DateUtils.parseStrToDate(date + " " + timeAry[1], "yyyy-MM-dd HH:mm");
                Long duration1 = orderDate.getTime();
                Long duration2 = endDate.getTime();
                Integer duration = Math.toIntExact(duration2 - duration1);
                duration = duration/(1000*60);

                if (orderDate.before(new Date())) {
                    return output(ResponseCode.MEETING_ORDER_TIME_ERROR, null).toJSON();
                }
                List<DmMeetingOrdersPo> lists = dmMeetingOrdersMapper.queryByOrder(order.getSpaceId(), date, timeAry[0], timeAry[1]);
                if (!lists.isEmpty()) {
                    return output(ResponseCode.MEETING_ORDER_CONFLICT, null).toJSON();
                }
                DmMeetingOrdersPo mm = dmMeetingOrdersConverter.mapperPo(order);
                mm.setMeetingDuration(duration);
                mm.setOrderDate(orderDate);
                mm.setStartTime(orderDate);
                mm.setEndTime(endDate);
                list.add(mm);
                mms.append(dateFormat1.format(mm.getOrderDate()) + " " + dateFormat2.format(mm.getStartTime()) + "，");
            }
        }

        dmMeetingOrdersMapper.insertBatch(list);

        String mms2 = mms.substring(0, mms.length() - 1) + "于" + meetingRoom.getName();
        DmStaffPo dmStaffPo = dmStaffMapper.selectById(order.getOrderBy());

        SmsReqEntity send = new SmsReqEntity();
        try {
            if (null != dmStaffPo && StringUtils.isNotEmpty(dmStaffPo.getPhone())) {
                send.setPhone(dmStaffPo.getPhone());
                send.setTemplate(smsProperties.getMeetingOrderTemplate());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("dateStr", mms2);
                jsonObject.put("name", dmStaffPo.getUserName());
                //TODO. 发送短信 后期需要获取数字人昵称

                DmDigitalmanPo dmDigitalmanPo = digitalmanMapper.selectByCode(digitalmanExtMapper.selectOne(Wrappers.<DmDigitalmanExtPo>query().lambda().eq(DmDigitalmanExtPo::getDeviceId, order.getDevId()).last(SqlConstants.LIMIT_ONE)).getManCode());
                if (null!= dmDigitalmanPo &&  StringUtils.isNotEmpty(dmDigitalmanPo.getName())) {
                    jsonObject.put("robotName", dmDigitalmanPo.getName());
                } else {
                    jsonObject.put("robotName", smsProperties.getRobotName());
                }

                send.setDataMap(jsonObject.toJSONString());
                remoteSmsService.sendSms(send);

            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
        // 埋点 预定会议室
        redisTemplate.opsForValue().increment("dashboard:meeting", 1);
        // 创建会议提醒
        // 创建json
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("meetingRoom", meetingRoom.getName());
        jsonObject.put("orderName", dmStaffPo.getUserName());
        jsonObject.put("orderId", dmStaffPo.getId());
        jsonObject.put("timestamp", list.get(0).getStartTime().getTime());
//        redisTemplate.opsForValue().set("group:nlp" + ":" + dmStaffPo.getId() + ":" + "meeting",jsonObject.toString());
        // 将创建临时信息添加进缓存：用户会议提醒

        DmWebSocketMessageVo vo = new DmWebSocketMessageVo();
        vo.setDevId(order.getDevId());
        vo.setSkillCode("1");
        vo.setFormat(jsonObject);
        R<DmManDeviceDto> manDeviceDtoR = manDeviceService.manDeviceInfoInner(order.getDevId());
        Source source = SourceUtil.getSourceCache(manDeviceDtoR.getData().getStrategyId());
        remoteIntentService.sendMessage(vo,  manDeviceDtoR.getData().getTId(), source.getMaster(), SecurityConstants.INNER);
        // 清除设备会议室模版session信息
        redisTemplate.delete("group:websocket" + ":" + order.getDevId());
        redisTemplate.delete("group:device" + ":" + order.getDevId() + ":" +"session");
        return outputSuccess().toJSON();
    }


    @InnerAuth
    @GetMapping(value = "/enableOrder/{roomId}/{dateStr}/{startTime}")
    public JSONObject queryExist(@PathVariable(name = "roomId") Long roomId, @PathVariable(name = "dateStr") String dateStr, @PathVariable(name = "startTime") String startTime) {
        log.info("dateStr:{}", dateStr);
        log.info("startTime:{}", startTime);
        DmMeetingRoomsPo room = dmMeetingRoomsMapper.findById(roomId);
        if (null == room) {
            return output(ResponseCode.DATA_NOT_EXISTS, "会议室").toJSON();
        }
        if (DateUtils.formatDate(new Date(), "yyyy-MM-dd").compareTo(dateStr) > 0) {
            return output(ResponseCode.MEETING_ORDER_TIME_ERROR).toJSON();
        }
        if (StringUtils.isEmpty(startTime)) {
            return output(ResponseCode.MEETING_ORDER_TIME_ERROR).toJSON();
        }
        String sTime = startTime,eTime = "";
        Date end = DateUtils.addMinutes(DateUtils.parseStrToDate(dateStr + " " + startTime, "yyyy-MM-dd HH:mm"), 30);
        eTime = DateUtils.formatDate(end, "HH:mm");

        List<DmMeetingOrdersPo> lists = dmMeetingOrdersMapper.queryByOrder(roomId, dateStr, sTime, eTime);
        if (lists.size() > 0) {
            return output(ResponseCode.MEETING_ORDER_TIME_ERROR).toJSON();
        }
        return outputSuccess().toJSON();
    }

    @InnerAuth
    @GetMapping(value = "/enableOrder/{roomId}/{dateStr}/{startTime}/{duration}")
    public JSONObject queryExistOrder(@PathVariable(name = "roomId") Long roomId, @PathVariable(name = "dateStr") String dateStr, @PathVariable(name = "startTime") String startTime,  @PathVariable(name = "duration") Integer duration) {
        log.info("dateStr:{}", dateStr);
        log.info("startTime:{}", startTime);
        DmMeetingRoomsPo room = dmMeetingRoomsMapper.findById(roomId);
        if (null == room) {
            return output(ResponseCode.DATA_NOT_EXISTS, "会议室").toJSON();
        }
        if (DateUtils.formatDate(new Date(), "yyyy-MM-dd").compareTo(dateStr) > 0) {
            return output(ResponseCode.MEETING_ORDER_TIME_ERROR).toJSON();
        }
        if (StringUtils.isEmpty(startTime)) {
            return output(ResponseCode.MEETING_ORDER_TIME_ERROR).toJSON();
        }
        String sTime = startTime,eTime = "";
        Date end = DateUtils.addMinutes(DateUtils.parseStrToDate(dateStr + " " + startTime, "yyyy-MM-dd HH:mm"), 30);
        end = DateUtils.addMinutes(end, duration);
        eTime = DateUtils.formatDate(end, "HH:mm");

        List<DmMeetingOrdersPo> lists = dmMeetingOrdersMapper.queryByOrder(roomId, dateStr, sTime, eTime);
        if (lists.size() > 0) {
            return output(ResponseCode.MEETING_ORDER_TIME_ERROR).toJSON();
        }
        return outputSuccess().toJSON();
    }

    @InnerAuth
    @PostMapping(value = "/quit")
    public JSONObject quitInner(@RequestParam("id") Long id) {

        DmMeetingOrdersPo mro = dmMeetingOrdersMapper.selectById(id);
        if (null == mro) {
            return output(ResponseCode.MEETING_RECORD_NOT_FOUND, null).toJSON();
        }

        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("HH:mm");
        DmMeetingRoomsPo meetingRoom = dmMeetingRoomsMapper.findById(mro.getSpaceId());
        String mms = dateFormat1.format(mro.getOrderDate()) + " " + dateFormat2.format(mro.getStartTime()) + "于" + meetingRoom.getName();

        //TODO. 发送短信
        DmStaffPo dmStaffPo = dmStaffMapper.selectById(mro.getOrderBy());

        SmsReqEntity send = new SmsReqEntity();
        try {
            if (null != dmStaffPo && StringUtils.isNotEmpty(dmStaffPo.getPhone())) {
                send.setPhone(dmStaffPo.getPhone());
                send.setTemplate(smsProperties.getMeetingQuitTemplate());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("dateStr", mms);
                jsonObject.put("name", dmStaffPo.getUserName());
                //TODO. 发送短信 后期需要获取数字人昵称
                jsonObject.put("robotName", smsProperties.getRobotName());
                send.setDataMap(jsonObject.toJSONString());
                remoteSmsService.sendSms(send);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        QueryWrapper<DmMeetingOrdersPo> wrapper = new QueryWrapper<>();
        wrapper.eq("id", mro.getId());
        dmMeetingOrdersMapper.delete(wrapper);

        return outputSuccess().toJSON();

    }

    @InnerAuth
    @PostMapping(value = "/person-lists")
    public JSONObject personListInner(@RequestParam("orderBy") Long orderBy) {
        List<DmMeetingOrdersPo> mrs = dmMeetingOrdersMapper.findListByPerson(orderBy);
        List<DmMeetingOrdersDto> list = new ArrayList<>();
        for (DmMeetingOrdersPo m : mrs) {
            DmMeetingRoomsPo mr = dmMeetingRoomsMapper.findById(m.getSpaceId());
            DmMeetingOrdersDto dd = dmMeetingOrdersConverter.mapperDto(m);
            dd.setRoomName(mr.getName());
            dmMeetingOrdersService.fixColumns(dd);
            list.add(dd);
        }
        return outputSuccess(list).toJSON();
    }

    @InnerAuth
    @PostMapping(value = "/date-lists")
    public JSONObject listByDate(@RequestParam("dateStr") String dateStr) {
        List<DmMeetingOrdersPo> list = dmMeetingOrdersMapper.findListByDateStr(dateStr);
        List<DmMeetingOrdersDto> res = new ArrayList<>();
        list.forEach(item -> {
            DmMeetingRoomsPo mr = dmMeetingRoomsMapper.findById(item.getSpaceId());
            if (null != mr) {
                DmMeetingOrdersDto dto = dmMeetingOrdersConverter.mapperDto(item);
                dto.setRoomName(mr.getName());
                dmMeetingOrdersService.fixColumns(dto);
                res.add(dto);
            }
        });
        return outputSuccess(res).toJSON();
    }


    @InnerAuth
    @PostMapping(value = "/lists")
    public JSONObject listInner(@RequestParam("dateStr") String dateStr, @RequestParam("spaceId") Long spaceId) {
        List<DmMeetingOrdersPo> list = dmMeetingOrdersMapper.findListByDate(dateStr, spaceId);
        List<DmMeetingOrdersDto> res = new ArrayList<>();
        list.forEach(item -> {
            DmMeetingOrdersDto dto = dmMeetingOrdersConverter.mapperDto(item);
            dmMeetingOrdersService.fixColumns(dto);
            res.add(dto);
        });
        return outputSuccess(res).toJSON();
    }

    @InnerAuth
    @PostMapping(value = "/lists-all")
    public JSONObject listAllInner(@RequestParam("dateStr") String dateStr, @RequestParam("spaceId") Long spaceId) {
        String date = dateStr.substring(0, 10);
        String time = dateStr.substring(11);
        System.err.println("date:"+date+"; time:"+time+";spaceId:"+spaceId);
        List<DmMeetingOrdersPo> list = dmMeetingOrdersMapper.findAllListByDate(date,time, spaceId);
        List<DmMeetingOrdersDto> res = new ArrayList<>();
        list.forEach(item -> {
            DmMeetingOrdersDto dto = dmMeetingOrdersConverter.mapperDto(item);
            dmMeetingOrdersService.fixColumns(dto);
            res.add(dto);
        });
        return outputSuccess(res).toJSON();
    }

    @InnerAuth
    @GetMapping(value = "/lists")
    public JSONObject listAllInner() {
        List<DmMeetingOrdersPo> list = dmMeetingOrdersMapper.findAllList();
        List<DmMeetingOrdersPo> res = new ArrayList<>();
        list.forEach(item -> {
            DmMeetingOrdersDto dto = dmMeetingOrdersConverter.mapperDto(item);
            DmMeetingRoomsPo mr = dmMeetingRoomsMapper.findById(dto.getSpaceId());
            dto.setRoomName(mr.getName());
            dmMeetingOrdersService.fixColumns(dto);
            res.add(dto);
        });
        return outputSuccess(res).toJSON();
    }

    /*
     *  获取会议室最近的可用时间段
     * @Author yangkai
     * @Description //TODO
     * @Date 2023/9/1
     * @Param [roomId, objects, currentTime]
     * @return java.util.List
     **/
    List freeTimePart (Long roomId, List<DmMeetingOrdersPo> objects, String currentTime) {
        List<JSONObject> freeTimeList = new ArrayList<>();

        if (null == objects || objects.size() ==0) {
            JSONObject json = new JSONObject();
            json.put("startTime", currentTime);
            json.put("endTime", 0);
            json.put("roomId", roomId);
            freeTimeList.add(json);
            return freeTimeList;
        }
        if (objects.size() ==1) {
            DmMeetingOrdersPo current = objects.get(0);
            if (DateUtils.formatDate(current.getStartTime(), "HH:mm").compareTo(currentTime) > 0 ) {
                JSONObject json = new JSONObject();
                json.put("startTime", currentTime);
                json.put("endTime", DateUtils.formatDate(current.getStartTime(), "HH:mm"));
                json.put("roomId", roomId);
                freeTimeList.add(json);
            } else {
                if (DateUtils.formatDate(current.getEndTime(), "HH:mm").compareTo(currentTime) > 0 ) {
                    JSONObject json = new JSONObject();
                    json.put("startTime", DateUtils.formatDate(current.getEndTime(), "HH:mm"));
                    json.put("endTime", 0);
                    json.put("roomId", roomId);
                    freeTimeList.add(json);
                } else {
                    JSONObject json = new JSONObject();
                    json.put("startTime", currentTime);
                    json.put("endTime", 0);
                    json.put("roomId", roomId);
                    freeTimeList.add(json);
                }

            }
            return  freeTimeList;
        }
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        objects = objects.stream().sorted(Comparator.comparing(po -> DateUtils.formatDate(po.getStartTime(), "HH:mm"))).collect(Collectors.toList());
        for (int i = 0; i < objects.size() - 1; i++) {
            DmMeetingOrdersPo current = objects.get(i);
            DmMeetingOrdersPo next = objects.get(i + 1);

            Date freeStartTime = current.getEndTime();
            Date freeEndTime = next.getStartTime();

            String freeStartTimeStr = DateUtils.formatDate(current.getEndTime(), "HH:mm");
            String freeEndTimeStr = DateUtils.formatDate(next.getStartTime(), "HH:mm");

            if (DateUtils.formatDate(current.getStartTime(), "HH:mm").compareTo(currentTime) < 0) {
                if (i==objects.size() - 2) {
                    JSONObject json = new JSONObject();
                    if (DateUtils.formatDate(next.getEndTime(), "HH:mm").compareTo(currentTime)>0) {
                        json.put("startTime", DateUtils.formatDate(next.getEndTime(), "HH:mm"));
                    } else {
                        json.put("startTime", currentTime);
                    }
                    json.put("endTime", 0);
                    json.put("roomId", current.getSpaceId());
                    freeTimeList.add(json);
                }
                continue;
            }

            if (i==0 && DateUtils.formatDate(current.getStartTime(), "HH:mm").compareTo(currentTime) > 0 ) {
                JSONObject json = new JSONObject();
                json.put("startTime", currentTime);
                json.put("endTime", DateUtils.formatDate(current.getStartTime(), "HH:mm"));
                json.put("roomId", roomId);
                freeTimeList.add(json);
            }

            if (freeStartTime.before(freeEndTime)) {
                JSONObject json = new JSONObject();
                json.put("startTime", freeStartTimeStr);
                json.put("endTime", freeEndTimeStr);
                json.put("roomId", roomId);
                freeTimeList.add(json);
            }

            if (i==objects.size() - 2) {
                JSONObject json = new JSONObject();
                if (DateUtils.formatDate(next.getEndTime(), "HH:mm").compareTo(currentTime)>0) {
                    json.put("startTime", DateUtils.formatDate(next.getEndTime(), "HH:mm"));
                } else {
                    json.put("startTime", currentTime);
                }
                json.put("endTime", 0);
                json.put("roomId", current.getSpaceId());
                freeTimeList.add(json);
            }
        }
        log.info("===============freeTimePart==============111");
        log.info("roomId:{},currentStr:{}, freeTimeList:{}",roomId,currentTime, freeTimeList);
        log.info("===============freeTimePart==============222");
        return freeTimeList;
    }


    JSONObject getList(String currentStr, Map<Long, List<DmMeetingOrdersPo>> groupedByRoom, Map<Long, String> rooms, Map<Long, Integer> sorts, List<Long> ids){
        Map<Long, List<JSONObject>> freeTime = new HashMap<>();
        log.info("currentStr:{}", currentStr);
        for(int i=0;i<ids.size();i++){
            Long key = ids.get(i);
            //groupedByRoom.get(key)可能为空
            freeTime.put(key, freeTimePart(key, groupedByRoom.get(key), currentStr));
        }
        List<JSONObject> arr = new ArrayList<>();
        for (int i=0;i<freeTime.keySet().size();i++){
            Long key = (Long) freeTime.keySet().toArray()[i];
            List<JSONObject> value = freeTime.get(key);
            arr.addAll(value);
        }
        Map<Long, String> finalRooms = rooms;
        Map<Long, Integer> finalSorts = sorts;
        arr = arr.stream().map(j->{j.put("roomName", finalRooms.get(j.getLong("roomId")));j.put("sort", finalSorts.get(j.getLong("roomId")));return j;}).sorted(Comparator.comparing(po -> po.getString("startTime"))).collect(Collectors.toList());
        List<JSONObject> arr2 = new ArrayList<>();
        for (int i=0;i<arr.size();i++){
            JSONObject j = arr.get(i);
            if (arr2.size() == 0 || arr2.get(0).getString("startTime").equals(j.getString("startTime"))) {
                arr2.add(j);
            } else {
                break;
            }
        }

        return arr2.size()>0 ? arr2.stream().sorted(Comparator.comparing(po -> po.getInteger("sort"))).collect(Collectors.toList()).get(0) :  null;
    }

    @InnerAuth
    @GetMapping("/recent/{deptId}/{dateStr}")
    @ResponseBody
    public List<JSONObject> recent(@PathVariable(value = "deptId") Long deptId,@PathVariable(value = "dateStr") String dateStr,@RequestParam(value = "roomId", required = false) Long roomId,@RequestParam(value = "startTime", required = false) String startTime, HttpServletRequest request) {

        List<DmMeetingOrdersPo> list = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        Map<Long, String> rooms = new HashMap<>();
        if (null == roomId) {
            DmMeetingRoomsPo dm = new DmMeetingRoomsPo();
            dm.setDeptId(deptId);
            List<DmMeetingRoomsPo> pos = dmMeetingRoomsMapper.selectRoomList(dm);
            ids = pos.stream().map(DmMeetingRoomsPo::getId).collect(Collectors.toList());
            rooms = pos.stream().collect(Collectors.toMap(DmMeetingRoomsPo::getId, DmMeetingRoomsPo::getName));
            list = dmMeetingOrdersMapper.findListByDateStr(dateStr);
        } else {
            DmMeetingRoomsPo po = dmMeetingRoomsMapper.findById(roomId);
            list = dmMeetingOrdersMapper.findListByDate(dateStr, po.getId());
            ids.add(roomId);
            rooms.put(po.getId(), po.getName());
        }


        //过滤掉今天的已经过去的预约记录，并按开始时间进行排序
        list = list.stream().filter(t->DateUtils.formatDate(t.getOrderDate(), "yyyy-MM-dd").compareTo(DateUtils.formatDate(new Date(), "yyyy-MM-dd"))>0 || (DateUtils.formatDate(t.getOrderDate(), "yyyy-MM-dd").compareTo(DateUtils.formatDate(new Date(), "yyyy-MM-dd"))==0 && DateUtils.formatDate(t.getStartTime(), "HH:mm").compareTo(DateUtils.formatDate(new Date(), "HH:mm"))>0)).sorted(Comparator.comparing(po -> DateUtils.formatDate(po.getStartTime(), "HH:mm"))).collect(Collectors.toList());


        //获得当前时间开始最近的整点，或者半点
        String currentStr = "08:00";
        if (StringUtils.isNotEmpty(startTime)) {
            currentStr = startTime;
        }

        if (dateStr.compareTo(DateUtils.formatDate(new Date(), "yyyy-MM-dd")) == 0) {
            LocalTime currentTime = LocalTime.now();
            if (currentTime.getMinute() >= 30) {
                currentTime = currentTime.plusHours(1).withMinute(0).withSecond(0);
            } else {
                currentTime = currentTime.withMinute(30).withSecond(0);
            }

            currentStr = currentTime.format(DateTimeFormatter.ofPattern("HH:mm"));
        }

        Map<Long, List<DmMeetingOrdersPo>> groupedByRoom = list.stream()
                .collect(Collectors.groupingBy(DmMeetingOrdersPo::getSpaceId));

        Map<Long, List<JSONObject>> freeTime = new HashMap<>();

        for(int i=0;i<ids.size();i++){
            Long key = ids.get(i);
            //groupedByRoom.get(key)可能为空
            freeTime.put(key, freeTimePart(key, groupedByRoom.get(key), currentStr));
        }
        List<JSONObject> arr = new ArrayList<>();
        for (int i=0;i<freeTime.keySet().size();i++){
            Long key = (Long) freeTime.keySet().toArray()[i];
            List<JSONObject> value = freeTime.get(key);
            arr.addAll(freeTime.get(key));
        }
        Map<Long, String> finalRooms = rooms;
        arr = arr.stream().map(j->{j.put("roomName", finalRooms.get(j.getLong("roomId")));return j;}).sorted(Comparator.comparing(po -> po.getString("startTime"))).collect(Collectors.toList());
        return arr;
    }

    @Autowired
    private DmMeetingOrdersServiceImpl ordersService;

    @InnerAuth
    @GetMapping("/recent/{deptId}")
    @ResponseBody
    public List<JSONObject> recent(@PathVariable(value = "deptId") Long deptId) {

        List<DmMeetingOrdersPo> list = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        Map<Long, String> rooms = new HashMap<>();
        Map<Long, Integer> sorts = new HashMap<>();
        //当天
        String dateStr = DateUtils.formatDate(new Date(), "yyyy-MM-dd");

        DmMeetingRoomsPo dm = new DmMeetingRoomsPo();
        dm.setDeptId(deptId);
        List<DmMeetingRoomsPo> pos = dmMeetingRoomsMapper.selectRoomList(dm);

        ids = pos.stream().map(DmMeetingRoomsPo::getId).collect(Collectors.toList());
        rooms = pos.stream().collect(Collectors.toMap(DmMeetingRoomsPo::getId, DmMeetingRoomsPo::getName));
        sorts = pos.stream().collect(Collectors.toMap(DmMeetingRoomsPo::getId, DmMeetingRoomsPo::getSort));
        log.info("ids:" + ids);

        //获得当前时间开始最近的整点，或者半点
        String currentStr = "08:00";
        if (dateStr.compareTo(DateUtils.formatDate(new Date(), "yyyy-MM-dd")) == 0) {
            LocalTime currentTime = LocalTime.now();
            if (currentTime.getMinute() >= 30) {
                currentTime = currentTime.plusHours(1).withMinute(0).withSecond(0);
            } else {
                currentTime = currentTime.withMinute(30).withSecond(0);
            }
            currentStr = currentTime.format(DateTimeFormatter.ofPattern("HH:mm"));
        }

        Map<Long, List<DmMeetingOrdersPo>> groupedByRoom = ordersService.selectOrderedList(deptId,dateStr);
        String nextDateStr = DateUtils.dateStrAdd(dateStr, 1);
        Map<Long, List<DmMeetingOrdersPo>> nextGroupedByRoom = ordersService.selectOrderedList(deptId,nextDateStr);
        JSONObject js1 = getList(currentStr, groupedByRoom,  rooms, sorts, ids);
        JSONObject js2 = new JSONObject();
        JSONObject js3 = new JSONObject();
        if (DateUtils.isAmPm().equals("am")) {
            currentStr = "14:00";
            js2 = getList(currentStr, groupedByRoom,  rooms, sorts, ids);
            currentStr = "09:00";
            js3 = getList(currentStr, nextGroupedByRoom,  rooms, sorts, ids);

        } else {
            currentStr = "09:00";
            js2 = getList(currentStr, nextGroupedByRoom,  rooms, sorts, ids);
            currentStr = "14:00";
            js3 = getList(currentStr, nextGroupedByRoom,  rooms, sorts, ids);
        }
        List<JSONObject> arr = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(js1)) {
            js1.put("orderDate", dateStr);
            arr.add(js1);
        }
        if (ObjectUtil.isNotEmpty(js2)) {
            if (DateUtils.isAmPm().equals("am")) {
                js2.put("orderDate", dateStr);
            } else {
                js2.put("orderDate", nextDateStr);
            }
            arr.add(js2);
        }
        if (ObjectUtil.isNotEmpty(js3)) {
            js3.put("orderDate", nextDateStr);
            arr.add(js3);
        }

        return arr;
    }

}
