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

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.ReservationPerson;
import com.ics.admin.domain.meeting.RoomContent;
import com.ics.admin.domain.meeting.Ticket;
import com.ics.admin.domain.meeting.vo.MeetingAmountVo;
import com.ics.admin.mapper.meeting.RoomContentMapper;
import com.ics.admin.mapper.meeting.TicketMapper;
import com.ics.admin.service.IBuildingDetailService;
import com.ics.admin.service.IIcsCustomerStaffService;
import com.ics.admin.service.IRoomService;
import com.ics.admin.service.meeting.IRoomContentService;
import com.ics.common.core.domain.IcsCustomerStaff;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ics.admin.mapper.meeting.ReservationMapper;
import com.ics.admin.domain.meeting.Reservation;
import com.ics.admin.service.meeting.IReservationService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 预约记录Service业务层处理
 * 
 * @author chen
 * @date 2024-02-25
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private RoomContentMapper roomContentMapper;
    @Autowired
    private TicketMapper ticketMapper;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private IBuildingDetailService buildingDetailService;

    @Autowired
    private IIcsCustomerStaffService customerStaffService;
    /**
     * 查询预约记录
     * 
     * @param id 预约记录ID
     * @return 预约记录
     */
    @Override
    public Reservation selectReservationById(Long id) {
        return reservationMapper.selectById(id);
    }

    /**
     * 查询预约记录列表
     * 
     * @param reservation 预约记录
     * @return 预约记录
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(null != reservation.getTitle(), "title", reservation.getTitle());
        queryWrapper.eq(null != reservation.getStatusValue(), "stauts", reservation.getStatusValue());
        queryWrapper.eq(reservation.getParkId() !=null,"park_id", reservation.getParkId());
        queryWrapper.eq(reservation.getTenantId() !=null,"tenant_id", reservation.getTenantId());
        queryWrapper.eq(reservation.getCustomerId() !=null,"customer_id", reservation.getCustomerId());
        queryWrapper.orderByDesc("create_time");
        return reservationMapper.selectList(queryWrapper);
    }

    /**
     * 新增预约记录
     * 
     * @param reservation 预约记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertReservation(Reservation reservation) {
        return reservationMapper.insert(reservation);
    }

    /**
     * 修改预约记录
     * 
     * @param reservation 预约记录
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation) {
        return reservationMapper.updateById(reservation);
    }

    /**
     * 删除预约记录对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(String ids) {
        String[] idsArray = StrUtil.split(ids,",");
        return reservationMapper.deleteBatchIds(CollUtil.toList(idsArray));
    }

    /**
     * 删除预约记录信息
     * 
     * @param id 预约记录ID
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id) {
        return reservationMapper.deleteReservationById(id);
    }

    @Override
    public boolean selectFreeMeetingRoom(Reservation reservation) {

        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("room_content_id",reservation.getRoomContentId());
        queryWrapper.ne("stauts",4);

        Date startTime = reservation.getStartTime();
        Date endDate = reservation.getEndDate();
        List<Reservation> reservations = reservationMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(reservations)){
            for (Reservation reservation1 : reservations) {
                Boolean judge = judge(reservation1.getStartTime(), reservation1.getEndDate(), startTime, endDate);
                if (judge){
                    return true;
                }else {
                    continue;
                }
            }
        }
        return false;
    }

    @Override
    public MeetingAmountVo calculateMeetingRoomAmount(Reservation reservation) {
        MeetingAmountVo meetingAmountVo = new MeetingAmountVo();
        //获取时长
        long hour=DateUtil.between(reservation.getStartTime(),reservation.getEndDate(), DateUnit.HOUR);
        // 获取会议室id
        Long roomContentId = reservation.getRoomContentId();
        //根据会议室id 获取会议室
        RoomContent roomContent = roomContentMapper.selectById(roomContentId);
        // 根据时间获取对应时长
        Integer duration = roomContent.getDuration();
        //如果会议室时长大于 会议时长
        if (duration>hour){
            //起步金额 乘以时长
            BigDecimal totalMoney = new BigDecimal(roomContent.getMoney()).multiply(new BigDecimal(duration));
            meetingAmountVo.setTotalMoney(totalMoney);
            // duration去判断优惠卷
            if (null != reservation.getTicketId()){
                Ticket ticket = ticketMapper.selectTicketById(reservation.getTicketId());
                if (ticket.getDuration() ==null){
                    String discount = ticket.getDiscount();
                    BigDecimal paidMoney = new BigDecimal(roomContent.getMoney()).multiply(new BigDecimal(discount)).multiply(new BigDecimal(duration));
                    meetingAmountVo.setPaidMoney(paidMoney);
                    return meetingAmountVo;
                }
                // 获取优惠卷时长
                Integer duration1 = ticket.getDuration();
                if (duration1>duration){
                    BigDecimal bigDecimal = new BigDecimal("0.00");
                    meetingAmountVo.setPaidMoney(bigDecimal);
                    return meetingAmountVo;
                }else {
                    int i = duration - duration1;
                    BigDecimal paidMoney = new BigDecimal(roomContent.getMoney()).multiply(new BigDecimal(i));
                    meetingAmountVo.setPaidMoney(paidMoney);
                    return meetingAmountVo;
                }
            }else {
                // 没有优惠卷 duration * money
                String money = roomContent.getMoney();
                BigDecimal bigDecimal = new BigDecimal(money);
                BigDecimal bigDecimal1 = bigDecimal.multiply(new BigDecimal(duration));
                meetingAmountVo.setPaidMoney(bigDecimal1);
                return meetingAmountVo;
            }
        }else {
            BigDecimal totalMoney = new BigDecimal(roomContent.getMoney()).multiply(new BigDecimal(hour));
            meetingAmountVo.setTotalMoney(totalMoney);
            if (null != reservation.getTicketId()) {
                Ticket ticket = ticketMapper.selectTicketById(reservation.getTicketId());
                if (ticket.getDuration() ==null){
                    String discount = ticket.getDiscount();
                    BigDecimal paidMoney = new BigDecimal(roomContent.getMoney()).multiply(new BigDecimal(discount)).multiply(new BigDecimal(hour));
                    meetingAmountVo.setPaidMoney(paidMoney);
                    return meetingAmountVo;
                }

                // 获取优惠卷时长
                Integer duration1 = ticket.getDuration();
                if (duration1 > hour) {
                    BigDecimal bigDecimal = new BigDecimal("0.00");
                    meetingAmountVo.setPaidMoney(bigDecimal);
                    return meetingAmountVo;
                } else {
                    long i = hour - duration1;
                    BigDecimal multiply = new BigDecimal(roomContent.getMoney()).multiply(new BigDecimal(i));
                    meetingAmountVo.setPaidMoney(multiply);
                    return meetingAmountVo;
                }
            }else {
                // 没有优惠卷 duration * money
                String money = roomContent.getMoney();
                BigDecimal bigDecimal = new BigDecimal(money);
                BigDecimal bigDecimal1 = bigDecimal.multiply(new BigDecimal(hour));
                meetingAmountVo.setPaidMoney(bigDecimal1);
                return meetingAmountVo;
            }
        }
    }

    // 根据用户查询预约详情
    @Override
    public IPage<Reservation> selectReservationListByUserId(Reservation reservation, Integer pageNum, Integer pageSize) {

        IcsCustomerStaff staff = customerStaffService.selectIcsCustomerStaffById(reservation.getUserId());


        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
//        if (!staff.getDataType().equals("7")){
//        }
        queryWrapper.eq("user_id",reservation.getUserId());

        queryWrapper.eq("park_id",reservation.getParkId());
        queryWrapper.orderByDesc("start_time");
        IPage<Reservation> pages = new Page<>(pageNum,pageSize);
        IPage<Reservation> userIPage = reservationMapper.selectPage(pages,queryWrapper);
        for (Reservation reservation1 : userIPage.getRecords()) {
            reservation1.setStatusValue(reservation1.getStauts().getValue());
            reservation1.setStatusName(reservation1.getStauts().getName());
            Long roomContentId = reservation1.getRoomContentId();
            RoomContent roomContent = roomContentMapper.selectById(roomContentId);
            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());
                }
            }
            reservation1.setRoomContent(roomContent);
        }
        return userIPage;

    }

    @Override
    public Reservation selectByOrderNumber(String outTradeNo) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oder_number",outTradeNo);
        return reservationMapper.selectOne(queryWrapper);

    }

    @Override
    public void selectTimeByMeetingRoomTime(Reservation reservation) {



    }

    @Override
    public List<Reservation> selectByRoomContent(RoomContent roomContent) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("room_content_id",roomContent.getId());
//        queryWrapper.gt("start_time",new Date());
        return reservationMapper.selectList(queryWrapper);
    }

    @Override
    public List<Reservation> selectReservationListByDay() {

        return reservationMapper.selectReservationListByDay();
    }


    /**
     * 比较一个 HH:mm:ss 是否在一个时间段内
     * 如：14:33:00 是否在 09:30:00 和 12:00:00 内
     */
    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.after(begin) && date.before(end);
    }





    /**
     * 判断一个时间段是否包含另一个时间段，包含：TRUE，不包含：FALSE
     *
     * @param date1
     * @param date2
     * @param startTime
     * @param endTime
     * @return
     */
    public static Boolean judge(Date date1, Date date2, Date startTime, Date endTime) {
        long d1 = date1.getTime();
        long d2 = date2.getTime();
        long v = d2 - d1;
        long start = startTime.getTime();
        long end = endTime.getTime();
        if (((d1 - start) < 0) && ((end - d2) < 0) || ((d2 - start) > 0) && ((d1 - end) < 0)) {
            return true;
        }
        return false;
    }


}
