package com.sky.ioc.service.meeting.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.ioc.config.RestTemplateConfig;
import com.sky.ioc.entity.Label;
import com.sky.ioc.entity.domain.meeting.MeetingRecord;
import com.sky.ioc.entity.domain.meeting.MeetingRoom;
import com.sky.ioc.entity.domain.space.BuildingFloor;
import com.sky.ioc.entity.domain.space.Company;
import com.sky.ioc.entity.domain.space.Department;
import com.sky.ioc.entity.params.IocParam;
import com.sky.ioc.entity.params.IocTimeRange;
import com.sky.ioc.mapper.meeting.MeetingRecordMapper;
import com.sky.ioc.mapper.meeting.MeetingRoomMapper;
import com.sky.ioc.mapper.space.BuildingFloorMapper;
import com.sky.ioc.service.meeting.MeetingRoomService;
import com.sky.ioc.tool.DateUtil;
import com.sky.ioc.tool.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MeetingRoomServiceImpl implements MeetingRoomService {

    @Resource
    RestTemplateConfig restTemplateConfig;

    @Autowired
    MeetingRoomMapper meetingRoomMapper;

    @Autowired
    MeetingRecordMapper meetingRecordMapper;

    @Autowired
    BuildingFloorMapper buildingFloorMapper;

    final static  String MEETTING_ROOM_URL="/api/meeting/MEETING/room/list?pageNum=1&pageSize=100";

    @Override
    public ReturnMsg getMeetingRoomList() {
        // 创建RestTemplate
        RestTemplate restTemplate = restTemplateConfig.build();
        // 发送GET请求
        String url = restTemplateConfig.addBaseUrl(MEETTING_ROOM_URL);
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(url, Map.class);
        // 获取响应对象里的 body 对象
        Map<String, Object> body = responseEntity.getBody();
        // 获取状态码
        Integer code = (Integer)body.get("code");
        // 获取响应信息
        String message = (String)body.get("msg");
        if(code==200){
             ArrayList list = (ArrayList) body.get("rows");
           if(list!=null&&list.size()>0){
                meetingRoomMapper.delete(null);
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    MeetingRoom room = new MeetingRoom();
                    String name = (String) json.get("mrName");
                    Pattern pattern = Pattern.compile("[0-9]*");
                    Matcher isNum = pattern.matcher(name.charAt(0)+"");
                    Integer floorId = 1;
                    if (isNum.matches()&&name.length()>2) {
                        floorId = Integer.valueOf(name.substring(0,2));
                    }
                    room.setId((Integer) json.get("id"));
                    room.setCapacity(8);
                    room.setName((String) json.get("mrName"));
                    room.setAuditTime((String) json.get("auditTime"));
                    room.setOpenTime((String) json.get("openTime"));
                    room.setCloseTime((String) json.get("closeTime"));
                    room.setRemark((String) json.get("remark"));
                    room.setFloorId(floorId);
                    room.setOrderNo((Integer)json.get("orderNo")+"");
                    room.setMrNo((String) json.get("mrNo"));
                    meetingRoomMapper.insert(room);
                }
            }
            return ReturnMsg.ok();
        }else{
            log.info("获取会议室数据："+message);
            return ReturnMsg.fail(message);
        }

    }

    @Override
    public ReturnMsg getMeetingRoomStatus(String date) {
        QueryWrapper queryWrapper = new QueryWrapper<>().orderByAsc("sort_code");
        List<BuildingFloor> floors = buildingFloorMapper.selectList(queryWrapper);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(BuildingFloor floor:floors){
            Map<String,Object> floormap = new HashMap<>();
            floormap.put("floor",floor.getCode());
            List<MeetingRoom> lists = meetingRoomMapper.getListRoomByFloorId(floor.getSortCode());
            List<Map<String,Object>> rooms = new ArrayList<>();
            for (MeetingRoom room:lists) {
                Map<String,Object> map = new HashMap<>();
                Integer roomId = room.getId();
                map.put("name",room.getName());
                map.put("capacity",room.getCapacity()+"");
                if(date!=null){
                    List<MeetingRecord> records = meetingRecordMapper.getListByTimeAndRoomId(date+" 00:00:00",
                            date+" 23:59:00",roomId);
                    if (records!=null&&records.size()>0){
                        String startTime = records.get(0).getStartTime().substring(11);
                        String endTime = records.get(0).getEndTime().substring(11);
                        map.put("time",startTime+"-"+endTime);
                        Integer start=startTime.compareTo(sdf2.format(new Date()));
                        Integer end = endTime.compareTo(sdf2.format(new Date()));
                        if(start>0){
                            map.put("status","已预定");
                        }else if(end>0){
                            map.put("status","闲置中");
                        }else {
                            map.put("status","会议中");
                        }

                    }else{
                        map.put("status","闲置中");
                    }
                }
                rooms.add(map);
            }
            if(lists.size()>0){
                floormap.put("meetingRooms",rooms);
                mapList.add(floormap);
            }

        }
        return ReturnMsg.ok(mapList);
    }

    @Override
    public ReturnMsg getMeetingInfo(IocParam iocParam) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        String[] param ={"会议室"};
        int limit = 24;
        if(iocParam.getFloorId()!=null){
            limit = 8;
            Integer floorId = iocParam.getFloorId();
            param = new String[]{floorId + "01", floorId + "02", floorId + "03"};
        }
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> lists = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = lists.toArray(new String[0]);
        List<Label> labels1 = new ArrayList<>();
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            for (int j = 0; j < param.length; j++) {
                int hours = random.nextInt(1,limit);
                jsonObject.put(param[j],hours);
            }
            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            labels1.add(label);
        }
        // List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        return ReturnMsg.ok(labels1);
    }
}
