package com.ics.controller.mobile.meeting;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ics.admin.domain.*;
import com.ics.admin.domain.meeting.*;
import com.ics.admin.domain.meeting.vo.MeetingAmountVo;
import com.ics.admin.domain.meeting.vo.UserCustomerVo;
import com.ics.admin.mapper.meeting.RoomContentMapper;
import com.ics.admin.mapper.meeting.RoomEquipmentMapper;
import com.ics.admin.service.*;
import com.ics.admin.service.meeting.*;
import com.ics.common.core.controller.BaseController;
import com.ics.common.core.domain.IcsCustomerStaff;
import com.ics.common.core.domain.R;
import com.ics.common.core.page.PageDomain;
import com.ics.common.core.page.TableSupport;
import com.ics.common.utils.Sample;
import com.ics.controller.mobile.pay.wx.WxPayCommon;
import com.ics.controller.mobile.pay.wx.constant.WxNotifyConstants;
import com.ics.controller.mobile.pay.wx.dto.WxChatBasePayDto;
import com.ics.controller.mobile.pay.wx.dto.WxChatPayDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.Ignore;
import org.wf.jwtp.annotation.RequiresPermissions;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/roomContent")
public class ApiRoomContentController extends BaseController {

    @Autowired
    private IRoomContentService roomContentService;


    @Autowired
    private ICustomerTicketService customerTicketService;

    @Autowired
    private IReservationService reservationService;

    @Autowired
    private IReservationPersonService reservationPersonService;


    @Autowired
    private RoomContentMapper roomContentMapper;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private IBuildingDetailService buildingDetailService;

    @Autowired
    private IIcsCustomerStaffService customerStaffService;

    @Autowired
    private ITicketService ticketService;

    @Autowired
    private IParkService parkService;

    @Autowired
    private IRoomEquipmentService roomEquipmentService;

    @Autowired
    WxPayCommon wxPayCommon;

    @Autowired
    private IUserEquipmentService userEquipmentService;

    @Autowired
    private IDetailEquipmentService detailEquipmentService;

    @Autowired
    private IReservationServeService reservationServeService;

    @Autowired
    private IRoomServeService roomServeService;




    /**
     * 查询条件筛选
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("searchInfo/{type}")
    public R searchInfo(@PathVariable("type") Integer type) {
        //  1.会议室类型，2.人数，3.会议室设备，4.形式

        Map<String, Object> map = roomContentService.selectSearchInfoByType(type);
        return R.ok(map);
    }

    /**
     * 获取房间内容
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("list")
    public R list(@RequestBody RoomContent roomContent) {
        List<RoomContent> roomContents = roomContentService.selectApiRoomList(roomContent);

        return result(roomContents);
    }


    /**
     * 获取房间详情信息
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("/info/{id}")
    public R infoById(@PathVariable("id") Long id) {
        RoomContent roomContents = roomContentService.selectInfoById(id);
        return R.ok().put("roomContent", roomContents);
    }

    /**
     * 优惠卷列表
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/getCustomerTicket")
    public R getCustomerTicket(@RequestBody UserCustomerVo userCustomerVo) {
        //根据用户获取对应的企业id，查询该企业下对应的优惠卷

        List<CustomerTicket> list = customerTicketService.getCustomerTicket(userCustomerVo);

        return R.ok().put("data", list);
    }

    /**
     * 查询长阳展示会议列表，当天会议室的预约时间
     * date:2024-06-25
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("/getMeetingRoomRecord/{meetingRoomId}")
    public R getMeetingRoomRecord(@PathVariable("meetingRoomId") Long meetingRoomId) {
        //根据用户获取对应的企业id，查询该企业下对应的优惠卷
//        meetingRoomId
        List<ReservationDTO> reservationList = roomContentService.selectMeetingRoomRecord(meetingRoomId);

        return R.ok().put("data", reservationList);
    }


    /**
     * 查询长阳空闲的会议室
     * date:2024-06-24
     * @param reservation
     * @return
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/selectFreeMeetingRoom")
    public R selectFreeMeetingRoom(@RequestBody Reservation reservation) {

        String msg = "";

        boolean count = true;

        RoomContent roomContent = roomContentMapper.selectById(reservation.getRoomContentId());
        if (null != roomContent) {
            Assert.isTrue(roomContent != null, "该会议室不存在");
        }

        Date startTime = reservation.getStartTime();
        String startFormat = DateUtil.format(startTime, "HH:mm:ss");
        Date endDate = reservation.getEndDate();
        String endFormat = DateUtil.format(endDate, "HH:mm:ss");

        Date startTime1 = roomContent.getStartTime();
        String startFormat1 = DateUtil.format(startTime1, "HH:mm:ss");
        Date endDate1 = roomContent.getEndDate();

        String endFormat1 = DateUtil.format(endDate1, "HH:mm:ss");


        boolean b = timeIsInRound(startFormat, startFormat1, endFormat1);

        if (!b) {
            msg = !b ? "请在" + startFormat1 + "到" + endFormat1 + "的时间段内预约会议时间" : "会议室可用";
            count = true;
            return R.ok().put("count", count).put("msg", msg);
        }
        boolean b1 = timeIsInRound(endFormat, startFormat1, endFormat1);
        if (!b1) {
            msg = !b1 ? "请在" + startFormat1 + "到" + endFormat1 + "的时间段内预约会议时间" : "会议室可用";
            count = true;
            return R.ok().put("count", count).put("msg", msg);
        }


        count = reservationService.selectFreeMeetingRoom(reservation);
        msg = count ? "该时间段已被预约" : "会议室可用";
        return R.ok().put("count", count).put("msg", msg);
    }

    /**
     * message:上海会议预约记录
     * project:上海长阳
     * date:2024-06-23
     *
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/saveChangyangMeetingRecord")
    public R saveMeetingRoomRecord(@RequestBody Reservation reservation) throws Exception {
        reservation.setStauts(Reservation.Status.APPOINTMENT);


        reservation.setOderNumber(RandomUtil.randomNumbers(18));
        boolean b = reservationService.selectFreeMeetingRoom(reservation);
        Assert.isFalse(b, "会议室不可用");
        IcsCustomerStaff customerStaff = customerStaffService.selectIcsCustomerStaffById(reservation.getUserId());
        Assert.isTrue(customerStaff != null, "用户不存在");
        reservation.setCreateTime(new Date());
        reservation.setCreateBy(customerStaff.getUsername());
        boolean save = reservationService.save(reservation);
        Assert.isTrue(save, "预约失败");

        //新增预约服务数据

        List<String> serveNames = new ArrayList<>();

        for (ReservationServe reservationServe : reservation.getReservationServes()) {

            reservationServe.setReservationId(reservation.getId());
            reservationServe.setParkId(reservation.getParkId());
            reservationServe.setTenantId(reservation.getTenantId());
            reservationServeService.insertReservationServe(reservationServe);
            Long serveId = reservationServe.getServeId();
            RoomServe roomServe = roomServeService.selectRoomServeById(serveId);
            System.out.println("roomServe为：" + roomServe);
            if (roomServe != null && roomServe.getServeType() == 2) {
                String serveName = reservationServe.getServeName();
                serveNames.add(serveName);
            }
        }
        //判断预约服务
        Long roomContentId = reservation.getRoomContentId();
        RoomContent roomContent = roomContentService.selectRoomContentById(roomContentId);
        if (roomContent != null) {
            //获取手机号
            String expandNum = roomContent.getExpandNum();
            Date startTime = reservation.getStartTime();
            String name = customerStaff.getName();
            if (serveNames.size() > 3) return R.error("预约服务不能超过3个");
            if (CollUtil.isNotEmpty(serveNames)) {
                if (serveNames.size() == 1) {
                    Sample.send1(expandNum, name, startTime, roomContent.getMeetingName(), serveNames.get(0));
                } else if (serveNames.size() == 2) {
                    Sample.send2(expandNum, name, startTime, roomContent.getMeetingName(), serveNames.get(0), serveNames.get(1));
                } else if (serveNames.size() == 3) {
                    Sample.send3(expandNum, name, startTime, roomContent.getMeetingName(), serveNames.get(0), serveNames.get(1), serveNames.get(2));

                }
            }
        }


        Long id = reservation.getId();
        return  toAjax(save).put("reservationId", id);
    }

    /**
     * 提交会议预约记录
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/saveMeetingRecord")
    public R saveMeetingRecord(@RequestBody Reservation reservation) {
        //根据用户获取对应的企业id，查询该企业下对应的优惠卷
        reservation.setStauts(Reservation.Status.APPOINTMENT);

        reservation.setOderNumber(RandomUtil.randomNumbers(18));
        boolean b = reservationService.selectFreeMeetingRoom(reservation);
        Assert.isFalse(b, "会议室不可用");

        IcsCustomerStaff customerStaff = customerStaffService.selectIcsCustomerStaffById(reservation.getUserId());
        Assert.isTrue(customerStaff != null, "用户不存在");

        BigDecimal price = new BigDecimal(reservation.getOrderMoney());

        if (price.compareTo(BigDecimal.ZERO) == 1) {
            WxChatBasePayDto wxChatBasePayDto = new WxChatBasePayDto();
            wxChatBasePayDto.setDescription("会议室支付");
            wxChatBasePayDto.setOrderId(reservation.getOderNumber());
            wxChatBasePayDto.setPrice(price);
            wxChatBasePayDto.setNotify(WxNotifyConstants.CASE_PAY_NOTIFY);
            wxChatBasePayDto.setOpenId(customerStaff.getOpenid());
            String prepayId = wxPayCommon.wxJsApiPay(wxChatBasePayDto);
            reservation.setPrepayId(prepayId);
            reservation.setStauts(Reservation.Status.TO_BE_PAID);
            Long userId = reservation.getUserId();

            if (reservation.getCreateBy() == null) {
                reservation.setCreateBy(customerStaff.getUsername());
            }
//            reservation.setCreateBy();
            reservation.setCreateTime(new Date());
            boolean save = reservationService.save(reservation);

            if (save) {
                if (null != reservation.getTicketId()) {
                    Ticket ticket = ticketService.selectTicketById(reservation.getTicketId());
                    if (ticket.getType() == 2) {
                        CustomerTicket customerTicket = new CustomerTicket();
                        customerTicket.setTicketId(reservation.getTicketId());
                        customerTicket.setCustomerId(reservation.getCustomerId());
                        customerTicket.setStaffId(reservation.getUserId());
                        customerTicketService.insertCustomerTicket(customerTicket);
                    } else {
                        CustomerTicket customerTicket = new CustomerTicket();
                        customerTicket.setTicketId(reservation.getTicketId());
                        customerTicket.setCustomerId(reservation.getCustomerId());
                        customerTicket.setStaffId(reservation.getUserId());
                        customerTicketService.updateCustomerTicketBYUserId(customerTicket);
                    }
                }

                ArrayList<Long> ids = new ArrayList<>();
                Reservation reservation2 = reservationService.selectReservationById(reservation.getId());
                if (null != reservation2) {
                    RoomContent roomContent = roomContentService.selectRoomContentById(reservation2.getRoomContentId());
                    if (null != roomContent) {
                        Room room = roomService.selectRoomById(roomContent.getRoomId());
                        if (null != room) {
                            Long id = room.getId();
                            List<RoomEquipment> roomEquipment = roomEquipmentService.selectByRoomId(id);
                            if (CollUtil.isNotEmpty(roomEquipment)) {
                                for (RoomEquipment equipment : roomEquipment) {
                                    ids.add(equipment.getEquipmentId());
                                }
                            }
                            List<DetailEquipment> detailEquipments = detailEquipmentService.selectByRoomId(room.getBuildingDetailId());
                            if (CollUtil.isNotEmpty(detailEquipments)) {
                                for (DetailEquipment detailEquipment : detailEquipments) {
                                    ids.add(detailEquipment.getEquipmentId());
                                }
                            }
                        }
                    }
                    if (CollUtil.isNotEmpty(ids)) {
                        for (Long id : ids) {
                            UserEquipment userEquipment = new UserEquipment();
                            userEquipment.setEquipmentId(id);
                            userEquipment.setUserId(reservation.getUserId());
                            userEquipment.setStartTime(reservation.getStartTime());
                            userEquipment.setEndDate(reservation.getEndDate());
                            userEquipmentService.insertUserEquipment(userEquipment);
                        }
                    }
                }

            }
            Long id = reservation.getId();
            return toAjax(save).put("reservationId", id);
        } else {
            if (reservation.getCreateBy() == null) {
                reservation.setCreateBy(customerStaff.getUsername());
            }
            boolean save = reservationService.save(reservation);
            if (save) {
                if (null != reservation.getTicketId()) {
                    Ticket ticket = ticketService.selectTicketById(reservation.getTicketId());
                    if (ticket.getType() == 2) {
                        CustomerTicket customerTicket = new CustomerTicket();
                        customerTicket.setTicketId(reservation.getTicketId());
                        customerTicket.setCustomerId(reservation.getCustomerId());
                        customerTicket.setStaffId(reservation.getUserId());
                        customerTicketService.insertCustomerTicket(customerTicket);
                    } else {
                        CustomerTicket customerTicket = new CustomerTicket();
                        customerTicket.setTicketId(reservation.getTicketId());
                        customerTicket.setCustomerId(reservation.getCustomerId());
                        customerTicket.setStaffId(reservation.getUserId());
                        customerTicketService.updateCustomerTicketBYUserId(customerTicket);
                    }
                }
                ArrayList<Long> ids = new ArrayList<>();
                Reservation reservation2 = reservationService.selectReservationById(reservation.getId());
                if (null != reservation2) {
                    RoomContent roomContent = roomContentService.selectRoomContentById(reservation2.getRoomContentId());
                    if (null != roomContent) {
                        Room room = roomService.selectRoomById(roomContent.getRoomId());
                        if (null != room) {
                            Long id = room.getId();
                            List<RoomEquipment> roomEquipment = roomEquipmentService.selectByRoomId(id);
                            if (CollUtil.isNotEmpty(roomEquipment)) {
                                for (RoomEquipment equipment : roomEquipment) {
                                    ids.add(equipment.getEquipmentId());
                                }
                            }
                            List<DetailEquipment> detailEquipments = detailEquipmentService.selectByRoomId(room.getBuildingDetailId());
                            if (CollUtil.isNotEmpty(detailEquipments)) {
                                for (DetailEquipment detailEquipment : detailEquipments) {
                                    ids.add(detailEquipment.getEquipmentId());
                                }
                            }
                        }
                    }
                    if (CollUtil.isNotEmpty(ids)) {
                        for (Long id : ids) {
                            UserEquipment userEquipment = new UserEquipment();
                            userEquipment.setEquipmentId(id);
                            userEquipment.setUserId(reservation.getUserId());
                            userEquipment.setStartTime(reservation.getStartTime());
                            userEquipment.setEndDate(reservation.getEndDate());
                            userEquipmentService.insertUserEquipment(userEquipment);
                        }
                    }
                }
            }
            Long id = reservation.getId();
            return toAjax(save).put("reservationId", id);
        }
    }

    /**
     * 根据会议室id查询所有的会议室服务与设备
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("/getMeetingRoomServiceAndEquipment/{meetingRoomId}")
    public R getMeetingRoomServiceAndEquipment(@PathVariable("meetingRoomId") Long meetingRoomId) {
        //根据用户获取对应的企业id，查询该企业下对应的优惠卷
        Map<String, Object> map = roomContentService.selectMeetingRoomServiceAndEquipment(meetingRoomId);
        return R.ok().put("data", map);
    }

    /**
     * 计算会议室金额
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/calculateMeetingRoomAmount")
    public R calculateMeetingRoomAmount(@RequestBody Reservation reservation) {
        //根据用户获取对应的企业id，查询该企业下对应的优惠卷
        MeetingAmountVo amount = reservationService.calculateMeetingRoomAmount(reservation);
        return R.ok().put("amount", amount);
    }

    /**
     * 预约列表
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("selectReservationListByUserId")
    public R selectReservationListByUserId(@RequestBody Reservation reservation) {

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        IPage<Reservation> list = reservationService.selectReservationListByUserId(reservation, pageNum, pageSize);

        return R.ok().put("page", list);
    }

    // 根据id查询预约信息
    @RequiresPermissions("member:center:view")
    @GetMapping("selectReservationById/{id}")
    public R selectReservationById(@PathVariable("id") Long id) {
        Reservation reservation = reservationService.selectReservationById(id);
        if (null != reservation) {
            reservation.setStatusValue(reservation.getStauts().getValue());
            reservation.setStatusName(reservation.getStauts().getName());
        }
        IcsCustomerStaff icsCustomerStaff = customerStaffService.selectIcsCustomerStaffById(reservation.getUserId());
        if (null != icsCustomerStaff) {
            reservation.setUserName(icsCustomerStaff.getUsername());
            reservation.setPhone(icsCustomerStaff.getMobile());
            reservation.setAvatar(icsCustomerStaff.getAvatar());
        }



        Ticket ticket = ticketService.selectTicketById(reservation.getTicketId());
        if (null != ticket) {
            reservation.setTicketName(ticket.getTitle());
        }

        Long roomContentId = reservation.getRoomContentId();
        RoomContent roomContent = roomContentMapper.selectById(roomContentId);
        Room room = roomService.selectRoomById(roomContent.getRoomId());
        if (room != null) {
            roomContent.setRoomId(room.getId());

            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() + "F");
            }
        }
        reservation.setRoomContent(roomContent);

        List<ReservationServe> reservationServes = reservationServeService.selectReservationServeByReservationId(reservation.getId());
        if (CollUtil.isNotEmpty(reservationServes)) {
            for (ReservationServe reservationServe : reservationServes) {
                reservationServe.setServeName(roomServeService.selectRoomServeById(reservationServe.getServeId()).getServeName());
            }
        }
        reservation.setReservationServes(reservationServes);
        return R.ok().put("data", reservation);
    }

    /*
    获取坐标信息
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("/selectCoordinate")
    public R selectCoordinate(Long parkId) {
        //根据用户获取对应的企业id，查询该企业下对应的优惠卷
        Park park = parkService.selectParkById(parkId);

        return R.ok().put("lat", park.getLat()).put("lng", park.getLng()).put("address", park.getAddress());
    }


    /**
     * 判断预约参观人员
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/isVisitor")
    public R isVisitor(@RequestBody ReservationPerson reservationPerson) {

        ReservationPerson visitor = reservationPersonService.isVisitor(reservationPerson);
        if (visitor != null) {
            return R.error(500, "该人员已预约");
        }
        return R.ok("该人员未预约");
    }

    /**
     * 添加 邀请人员接口
     */
    @RequiresPermissions("member:center:view")
    @PostMapping("/addVisitor")
    public R addVisitor(@RequestBody ReservationPerson reservationPerson) {



        reservationPerson.setStatus("1");
        reservationPerson.setJoinTime(new Date());
        IcsCustomerStaff customerStaff = customerStaffService.selectIcsCustomerStaffById(reservationPerson.getParticipantId());
        if (null != customerStaff) {
            reservationPerson.setParticipantName(customerStaff.getUsername());
        }
        int i = reservationPersonService.insertReservationPerson(reservationPerson);
        if (i > 0) {

            //  预约成功后，给对应的人员添加设备的权限
            // 查询预约信息，根据预约信息查询会议室
            // todo 重复使用
            ArrayList<Long> ids = new ArrayList<>();

            Reservation reservation = reservationService.selectReservationById(reservationPerson.getReservationId());
            if (null != reservation) {
                RoomContent roomContent = roomContentService.selectRoomContentById(reservation.getRoomContentId());
                if (null != roomContent) {
                    Room room = roomService.selectRoomById(roomContent.getRoomId());
                    if (null != room) {
                        Long id = room.getId();
                        List<RoomEquipment> roomEquipment = roomEquipmentService.selectByRoomId(id);
                        if (CollUtil.isNotEmpty(roomEquipment)) {
                            for (RoomEquipment equipment : roomEquipment) {
                                ids.add(equipment.getEquipmentId());
                            }
                        }
                        List<DetailEquipment> detailEquipments = detailEquipmentService.selectByRoomId(room.getBuildingDetailId());
                        if (CollUtil.isNotEmpty(detailEquipments)) {
                            for (DetailEquipment detailEquipment : detailEquipments) {
                                ids.add(detailEquipment.getEquipmentId());
                            }
                        }
                    }
                }
                if (CollUtil.isNotEmpty(ids)) {
                    for (Long id : ids) {
//                        UserEquipment equipment = userEquipmentService.selectUserAndEquipment(reservationPerson.getReservationId(), id);
//                        if (null == equipment) {
                        UserEquipment userEquipment = new UserEquipment();
                        userEquipment.setEquipmentId(id);
                        userEquipment.setUserId(reservationPerson.getParticipantId());
                        userEquipment.setStartTime(reservation.getStartTime());
                        userEquipment.setEndDate(reservation.getEndDate());
                        userEquipmentService.insertUserEquipment(userEquipment);
//                        }
                    }
                }
                return R.ok("预约成功");
            }
        }
        return R.ok("该人员未预约");
    }

    //取消订单
    @RequiresPermissions("member:center:view")
    @PostMapping("/cancelOrder")
    public R cancelOrder(@RequestBody Reservation reservation) {

        Assert.notNull(reservation.getId(), "当前预约信息不存在");
        reservation.setStauts(Reservation.Status.CANCELED);
        reservation.setCancelResaon("用户取消原因:" + reservation.getCancelResaon());
        reservation.setCancelTime(new Date());
        int i = reservationService.updateReservation(reservation);

        //取消订单，返还优惠券
        if (i > 0) {
            Long ticketId = reservation.getTicketId();
            if (ticketId != null) {
                Ticket ticket = ticketService.selectTicketById(ticketId);
                if (ticket != null) {
                    Long customerId = reservation.getCustomerId();
                    CustomerTicket customerTicket = new CustomerTicket();
                    customerTicket.setTicketId(ticketId);
                    customerTicket.setCustomerId(customerId);
                    customerTicket.setType(ticket.getType());
                    customerTicket.setIsVerification(0);
                    int i1 = customerTicketService.insertCustomerTicket(customerTicket);
                }

            }


        }


        return toAjax(i);
    }

    //支付订单
    @RequiresPermissions("member:center:view")
    @PostMapping("/payOrder")
    public R payOrder(@RequestBody Reservation reservation) {
        Reservation reservation1 = reservationService.selectReservationById(reservation.getId());
        Reservation.Status stauts = reservation1.getStauts();
        System.out.println(stauts);
        Assert.isFalse(reservation1.getStauts().equals(Reservation.Status.APPOINTMENT), "您已经支付成功，请勿重复支付");
//        WxChatPayDto wxChatPayDto = wxPayCommon.wxPayCall(prepayId);
        Assert.notNull(reservation.getId(), "当前预约信息不存在");
        reservation.setStauts(Reservation.Status.APPOINTMENT);
        reservation.setOrderTime(new Date());
        int i = reservationService.updateReservation(reservation);


        // todo 支付订单后，需要测试
        ArrayList<Long> ids = new ArrayList<>();

        Reservation reservation2 = reservationService.selectReservationById(reservation.getId());
        if (null != reservation2) {
            RoomContent roomContent = roomContentService.selectRoomContentById(reservation2.getRoomContentId());
            if (null != roomContent) {
                Room room = roomService.selectRoomById(roomContent.getRoomId());
                if (null != room) {
                    Long id = room.getId();
                    List<RoomEquipment> roomEquipment = roomEquipmentService.selectByRoomId(id);
                    if (CollUtil.isNotEmpty(roomEquipment)) {
                        for (RoomEquipment equipment : roomEquipment) {
                            ids.add(equipment.getEquipmentId());
                        }
                    }
                    List<DetailEquipment> detailEquipments = detailEquipmentService.selectByRoomId(room.getBuildingDetailId());
                    if (CollUtil.isNotEmpty(detailEquipments)) {
                        for (DetailEquipment detailEquipment : detailEquipments) {
                            ids.add(detailEquipment.getEquipmentId());
                        }
                    }
                }
            }
            if (CollUtil.isNotEmpty(ids)) {
                for (Long id : ids) {
//                    UserEquipment equipment =userEquipmentService.selectUserAndEquipment(reservation.getUserId(), id);
//                    if (null == equipment){
                    UserEquipment userEquipment = new UserEquipment();
                    userEquipment.setEquipmentId(id);
                    userEquipment.setStartTime(reservation.getStartTime());
                    userEquipment.setEndDate(reservation.getEndDate());
                    userEquipment.setUserId(reservation.getUserId());
                    userEquipmentService.insertUserEquipment(userEquipment);
//                    }
                }
            }
        }
        return toAjax(i);
    }

    /**
     * 预约邀请记录
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("inviteRecord")
    public R list(ReservationPerson reservationPerson) {
        List<ReservationPerson> reservationPeople = reservationPersonService.selectReservationPersonList(reservationPerson);
        for (ReservationPerson person : reservationPeople) {

            IcsCustomerStaff participant = customerStaffService.selectIcsCustomerStaffById(person.getParticipantId());
            if (null != participant) {
                person.setAvatar(participant.getAvatar());
                person.setUserName(participant.getUsername());
            }
        }
        return R.data(reservationPeople);
    }

    /**
     * 获取人员列表（上海长阳）
     * date:2024-06-19
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("getChangyangPersonList")
    public R getChangyangPersonList() {
        List<IcsCustomerStaff> icsCustomerStaffs = customerStaffService.selectListByCustomerId();
        return R.data(icsCustomerStaffs);

    }




    public static boolean timeIsInRound(String str1, String start, String end) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        Date now = null;
        Date beginTime = null;
        Date endTime = null;

        try {
            now = df.parse(str1);
            beginTime = df.parse(start);
            endTime = df.parse(end);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return belongCalendar(now, beginTime, endTime);
    }


    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.compareTo(begin) >= 0 && date.compareTo(end) <= 0;
    }


}


