package com.ics.admin.service.impl.meeting;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
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.ics.admin.domain.BuildingDetail;
import com.ics.admin.domain.Room;
import com.ics.admin.domain.meeting.*;
import com.ics.admin.mapper.meeting.ReservationMapper;
import com.ics.admin.mapper.meeting.RoomItemByRoomMapper;
import com.ics.admin.mapper.meeting.RoomServeByRoomMapper;
import com.ics.admin.service.IBuildingDetailService;
import com.ics.admin.service.IIcsCustomerStaffService;
import com.ics.admin.service.IRoomService;
import com.ics.admin.service.meeting.*;
import com.ics.common.core.domain.BaseEntity;
import com.ics.common.core.domain.IcsCustomerStaff;
import com.ics.common.utils.DateUtils;
import com.ics.system.domain.DictData;
import com.ics.system.mapper.DictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ics.admin.mapper.meeting.RoomContentMapper;
import com.ics.admin.domain.meeting.RoomContent;

/**
 * 房间主体内容Service业务层处理
 * 
 * @author ics
 * @date 2024-02-22
 */
@Service
public class RoomContentServiceImpl extends ServiceImpl<RoomContentMapper, RoomContent> implements IRoomContentService {
    @Autowired
    private RoomContentMapper roomContentMapper;

    @Autowired
    private IRoomItemByRoomService roomItemByRoomService;

    @Autowired
    private IRoomItemService roomItemService;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private IRoomEquipmentService roomEquipmentService;

    @Autowired
    private IBuildingDetailService buildingDetailService;

    @Autowired
    private IRoomServeService iRoomServeService;

    @Autowired
    private RoomItemByRoomMapper roomItemByRoomMapper;

    @Autowired
    private IRoomServeByRoomService iRoomServeByRoomService;

    @Autowired
    private RoomServeByRoomMapper roomServeByRoomMapper;

    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private IIcsCustomerStaffService staffService;

    @Autowired
    private DictDataMapper dictDataMapper;

    /**
     * 查询房间主体内容
     * 
     * @param id 房间主体内容ID
     * @return 房间主体内容
     */
    @Override
    public RoomContent selectRoomContentById(Long id) {
        return roomContentMapper.selectById(id);
    }

    /**
     * 查询房间主体内容列表
     * 
     * @param roomContent 房间主体内容
     * @return 房间主体内容
     */
    @Override
    public List<RoomContent> selectRoomContentList(RoomContent roomContent) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(roomContent.getMeetingName() !=null,"meeting_name", roomContent.getMeetingName());
        queryWrapper.eq(roomContent.getTypeName() !=null,"type", roomContent.getTypeName());
        queryWrapper.eq(roomContent.getShape() !=null,"shape", roomContent.getShape());
        queryWrapper.eq(roomContent.getCapacityNum() !=null,"capacity_num", roomContent.getCapacityNum());
        queryWrapper.eq(roomContent.getParkId() !=null,"park_id", roomContent.getParkId());
        queryWrapper.eq(roomContent.getTenantId() !=null,"tenant_id", roomContent.getTenantId());
        queryWrapper.eq(roomContent.getRoomId() !=null,"room_id", roomContent.getRoomId());
        queryWrapper.in(roomContent.getRoomIds() !=null,"room_id", roomContent.getRoomIds());
        queryWrapper.orderByAsc("create_time");
        return roomContentMapper.selectList(queryWrapper);
    }

    /**
     * 新增房间主体内容
     * 
     * @param roomContent 房间主体内容
     * @return 结果
     */
    @Override
    public int insertRoomContent(RoomContent roomContent) {
        return roomContentMapper.insert(roomContent);
    }

    /**
     * 修改房间主体内容
     * 
     * @param roomContent 房间主体内容
     * @return 结果
     */
    @Override
    public int updateRoomContent(RoomContent roomContent) {
        return roomContentMapper.updateById(roomContent);
    }

    /**
     * 删除房间主体内容对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteRoomContentByIds(String ids) {
        String[] idsArray = StrUtil.split(ids,",");
        return roomContentMapper.deleteBatchIds(CollUtil.toList(idsArray));
    }

    /**
     * 删除房间主体内容信息
     * 
     * @param id 房间主体内容ID
     * @return 结果
     */
    @Override
    public int deleteRoomContentById(Long id) {
        return roomContentMapper.deleteRoomContentById(id);
    }

    @Override
    public List<RoomContent> selectApiRoomList(RoomContent roomContent) {
        //  根据物品查询数据
        if (CollUtil.isNotEmpty(roomContent.getRoomItemList())){
            //查询出所有的 roomContent 数据，
            List<RoomContent> roomContents = roomContentMapper.selectRoomContentList(roomContent);
            List<RoomItem> roomItemList = roomContent.getRoomItemList();
            List<Long> collect = roomItemList.stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            int size = roomItemList.size();
            ArrayList<RoomContent> roomContents1 = new ArrayList<>();
            //获取数据
            List<RoomItemByRoom> roomItemByRooms = roomItemByRoomService.selectRoomContent(collect, size);
            if (CollUtil.isNotEmpty(roomItemByRooms)){
                for (RoomItemByRoom roomItemByRoom : roomItemByRooms) {
                    RoomContent roomContent1 = roomContentMapper.selectById(roomItemByRoom.getRoomContentId());
                    roomContents1.add(roomContent1);
                }
            }
            List<Long> collect1 = roomContents1.stream().map(RoomContent::getId).collect(Collectors.toList());

            List<RoomContent> studentList = roomContents.stream().map(item -> {
                return collect1.stream().filter(id -> {        //条件判断
                    return item.getId() == id;
                }).map(name -> {
                    return item;                            //返回的结果
                }).collect(Collectors.toList());
            }).flatMap(List::stream).collect(Collectors.toList());//设置返回结果类型

            return selectRoomContentList(studentList);
        }else {
            if (roomContent.getType() != null) {
//                RoomContent.Type type = roomContent.getType();
//                roomContent.setTypeValue(type.ordinal());
            }
            List<RoomContent> roomContents = roomContentMapper.selectRoomContentList(roomContent);
            return selectRoomContentList(roomContents);
        }

    }

    public List<RoomContent> selectRoomContentList(List<RoomContent> roomContents) {
        for (RoomContent content : roomContents) {
            String typeName = dictDataMapper.selectDictLabel("meeting_type", String.valueOf(content.getType()));

//            content.setTypeValue(content.getType().getValue());
            content.setTypeName(typeName);
            ArrayList<RoomItem> items = new ArrayList<>();

            //查询房间号
            Room room = roomService.selectRoomById(content.getRoomId());
            if (room != null) {
                content.setRoomName(room.getName());
                //查询楼层号
                BuildingDetail buildingDetail = buildingDetailService.selectBuildingDetailById(room.getBuildingDetailId());
                if (buildingDetail != null) {
                    content.setBuildingName(buildingDetail.getFloorName());
                }
            }
            RoomItemByRoom roomItemByRoom = new RoomItemByRoom();
            roomItemByRoom.setRoomContentId(content.getId());
            List<RoomItemByRoom> roomItemByRooms = roomItemByRoomService.selectRoomItemByRoomList(roomItemByRoom);
            if (CollUtil.isNotEmpty(roomItemByRooms)){
                for (RoomItemByRoom itemByRoom : roomItemByRooms) {
                    RoomItem roomItem = roomItemService.selectRoomItemById(itemByRoom.getItemId());
                    items.add(roomItem);
                }
                content.setRoomItemList(items);
            }
        }
        return roomContents;
    }

    @Override
    public RoomContent selectInfoById(Long id) {
        RoomContent roomContent = roomContentMapper.selectRoomContentById(id);
        Assert.isTrue(roomContent != null, "未找到该房间信息");
        //获取房间所有服务信息
        RoomServeByRoom roomServeByRoom = new RoomServeByRoom();
        roomServeByRoom.setRomeContentId(id);

        List<RoomServe> roomServe1 = new ArrayList<>();
        List<RoomItem> roomItemList = new ArrayList<>();
        List<RoomServeByRoom> roomServeByRooms = iRoomServeByRoomService.selectRoomServeByRoomList(roomServeByRoom);
        if (CollUtil.isNotEmpty(roomServeByRooms)){
            for (RoomServeByRoom serveByRoom : roomServeByRooms) {
                RoomServe roomServe = iRoomServeService.selectRoomServeById(serveByRoom.getServeId());
                if (roomServe.getServeType()== 1){
                    roomServe1.add(roomServe);
                }
            }
            roomContent.setRoomServeList(roomServe1);
        }
        RoomItemByRoom roomItemByRoom = new RoomItemByRoom();
        roomItemByRoom.setRoomContentId(id);
        List<RoomItemByRoom> roomItemByRooms = roomItemByRoomService.selectRoomItemByRoomList(roomItemByRoom);
        if (CollUtil.isNotEmpty(roomItemByRooms)){
            for (RoomItemByRoom itemByRoom : roomItemByRooms) {
                RoomItem roomItem = roomItemService.selectRoomItemById(itemByRoom.getItemId());
                roomItemList.add(roomItem);
            }
            roomContent.setRoomItemList(roomItemList);
        }

        // 所在楼层，占地面积，办公面积
        Room room = roomService.selectRoomById(roomContent.getRoomId());
        if (room != null) {
            roomContent.setRoomName(room.getName());
            roomContent.setArea(room.getArea());
            roomContent.setRenArea(room.getRentArea());
            //查询楼层号
            BuildingDetail buildingDetail = buildingDetailService.selectBuildingDetailById(room.getBuildingDetailId());
            if (buildingDetail != null) {
                roomContent.setBuildingName(buildingDetail.getFloorName());
            }
        }

        return roomContent;

    }

    @Override
    public Map<String,Object> selectSearchInfoByType(Integer type) {
        HashMap<String, Object> map = new HashMap<>();

        if (type == 3){
            QueryWrapper<RoomItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("name,id");
            List<RoomItem> list =roomItemService.list(queryWrapper);
            map.put("roomItem",list);
            return map;

        }else {
            QueryWrapper<RoomContent> queryWrapper = new QueryWrapper<>();
            if (type == 1){
                queryWrapper.groupBy("type");
            }else if (type == 2){
                queryWrapper.groupBy("capacity_num");
            }else if (type == 4){
                queryWrapper.groupBy("shape");
            }
            List<RoomContent> roomContents = roomContentMapper.selectList(queryWrapper);
            for (RoomContent roomContent : roomContents) {
                String typeName = dictDataMapper.selectDictLabel("meeting_type", String.valueOf(roomContent.getType()));

                roomContent.setTypeValue(roomContent.getType());
                roomContent.setTypeName(typeName);
            }
            map.put("roomContents",roomContents);
            return map;
        }



        //  1.会议室类型，2.人数，3.会议室设备，4.形式

    }

    @Override
    public List<ReservationDTO> selectMeetingRoomRecord(Long meetingRoomId) {

        ArrayList<ReservationDTO> list = new ArrayList<>();

        // 根据最近七天查询数据

        List<Date> reservations = reservationMapper.selectListByDate(meetingRoomId);
        System.out.println(reservations);
        for (Date dateTime : reservations) {
            ReservationDTO reservationDTO = new ReservationDTO();
            reservationDTO.setNowDate(DateUtil.format(dateTime,"yyyy-MM-dd"));
            // 查询会议室记录
            QueryWrapper<Reservation> wrapper = new QueryWrapper<>();
            String dateStr = dateTime.toString();
            wrapper.eq("room_content_id",meetingRoomId);
            wrapper.gt("start_time", DateUtil.format(dateTime,"yyyy-MM-dd")+ " 00:00:00");
            wrapper.lt("end_date",DateUtil.format(dateTime,"yyyy-MM-dd") + " 23:59:59");
            wrapper.ne("stauts",4);
            List<Reservation> reservation = reservationMapper.selectList(wrapper);
            for (Reservation reservation1 : reservation) {
                reservation1.setStatusValue(reservation1.getStauts().getValue());
                reservation1.setStatusName(reservation1.getStauts().getName());

                Long userId = reservation1.getUserId();
                IcsCustomerStaff customerStaff = staffService.selectIcsCustomerStaffById(userId);
                if (null != customerStaff){
                    reservation1.setUserName(customerStaff.getUsername());
                    reservation1.setPhone(customerStaff.getMobile());
                }
            }
            reservationDTO.setReservations(reservation);
            list.add(reservationDTO);
        }
        return list;
    }

    @Override
    public HashMap<String, Object>  selectMeetingRoomServiceAndEquipment(Long id) {

        HashMap<String, Object> map = new HashMap<>();
        RoomServeByRoom roomServeByRoom = new RoomServeByRoom();
        roomServeByRoom.setRomeContentId(id);
        List<RoomServe> roomServe1 = new ArrayList<>();
        List<RoomServe> roomServe2 = new ArrayList<>();
        List<RoomItem> roomItemList = new ArrayList<>();
        List<RoomServeByRoom> roomServeByRooms = iRoomServeByRoomService.selectRoomServeByRoomList(roomServeByRoom);
        if (CollUtil.isNotEmpty(roomServeByRooms)){
            for (RoomServeByRoom serveByRoom : roomServeByRooms) {
                RoomServe roomServe = iRoomServeService.selectRoomServeById(serveByRoom.getServeId());
                if (roomServe.getServeType() == 1){
                    roomServe1.add(roomServe);
                }else if (roomServe.getServeType() == 2){
                    roomServe2.add(roomServe);
                }
            }
            map.put("roomFreeServe",roomServe1);
            map.put("roomFServe",roomServe2);
        }
        RoomItemByRoom roomItemByRoom = new RoomItemByRoom();
        roomItemByRoom.setRoomContentId(id);
        List<RoomItemByRoom> roomItemByRooms = roomItemByRoomService.selectRoomItemByRoomList(roomItemByRoom);
        if (CollUtil.isNotEmpty(roomItemByRooms)){
            for (RoomItemByRoom itemByRoom : roomItemByRooms) {
                RoomItem roomItem = roomItemService.selectRoomItemById(itemByRoom.getItemId());
                roomItemList.add(roomItem);
            }
            map.put("roomItem",roomItemList);
        }
        return map;
    }

    @Override
    public int roomServeByRoom(RoomServeByRoom roomServeByRoom) {

        UpdateWrapper<RoomServeByRoom> wrapper = new UpdateWrapper<>();
        wrapper.eq("rome_content_id",roomServeByRoom.getRomeContentId());
        roomServeByRoomMapper.delete(wrapper);
        for (Long id : roomServeByRoom.getServeIds()) {
            RoomServeByRoom roomServeByRoom1 = new RoomServeByRoom();
            roomServeByRoom1.setServeId(id);
            roomServeByRoom1.setRomeContentId(roomServeByRoom.getRomeContentId());
            iRoomServeByRoomService.insertRoomServeByRoom(roomServeByRoom1);
        }
        return 1;

    }

    @Override
    public int addItemServe(RoomItemByRoom roomItemByRoom) {

        UpdateWrapper<RoomItemByRoom> wrapper = new UpdateWrapper<>();
        wrapper.eq("room_content_id",roomItemByRoom.getRoomContentId());
        roomItemByRoomMapper.delete(wrapper);
        for (Long id : roomItemByRoom.getItemIds()) {
            RoomItemByRoom roomItemByRoom1 = new RoomItemByRoom();
            roomItemByRoom1.setItemId(id);
            roomItemByRoom1.setRoomContentId(roomItemByRoom.getRoomContentId());
            roomItemByRoomService.insertRoomItemByRoom(roomItemByRoom1);
        }
        return 1;
    }

    @Override
    public List<Reservation> todayMeeting(RoomContent roomContent) {
        //查询当前之前以后，当前时间是否包含在会议室
        List<Reservation> reservations = reservationMapper.todayMeeting(roomContent.getId());
        for (Reservation reservation : reservations) {
            Long userId = reservation.getUserId();
            IcsCustomerStaff customerStaff = staffService.selectIcsCustomerStaffById(userId);
            if (null != customerStaff){
                reservation.setUserName(customerStaff.getUsername());
            }
        }
        return reservations;
    }

    @Override
    public RoomContent selectByRoomId(Long id) {

        QueryWrapper<RoomContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("room_id",id);
        return roomContentMapper.selectOne(queryWrapper);
    }

}
