package com.test.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.test.bean.Order;
import com.test.bean.PageBean;
import com.test.mapper.OrderMapper;
import com.test.mapper.RoomTypeMapper;
import com.test.service.OrderService;
import com.test.util.DateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    DateTimeUtils dateTimeUtils;
    @Autowired
    RoomTypeMapper roomTypeMapper;

    @Override
    public PageBean getAllOrderByPage(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        ArrayList<Order> orderList = orderMapper.getAllOrder();
        Page<Order> orderPage = (Page<Order>) orderList;
        return new PageBean(orderPage.getTotal(), orderPage.getResult());
    }

    @Override
    public Order getOrderById(Long id) {
        return orderMapper.getOrderById(id);
    }

    @Override
    public boolean createOrder(Order order) {
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        //0为未结账， 1为已结账
        order.setStatus(0);
        //获取经过了几晚
        int night = dateTimeUtils.calculateNights(order.getBeginTime(), order.getEndTime());
        //获取房价
        double roomPrice = roomTypeMapper.getRoomTypeById(order.getRoomTypeId()).getPrice();
        order.setPrice(night * roomPrice);
//        order.setUserIdJson(JSON.toJSONString(order.getUserId()));


        return orderMapper.createOrder(order);
    }

    @Override
    public Order checkoutOrder(Long id) {
        int i = orderMapper.checkoutOrder(id, LocalDateTime.now());
        if (i > 0) {
            return orderMapper.getOrderById(id);
        } else {
            return null;
        }

    }

    @Override
    public boolean updateOrder(Order order) {
        order.setUpdateTime(LocalDateTime.now());
        int night = dateTimeUtils.calculateNights(order.getBeginTime(), order.getEndTime());
        double roomPrice = roomTypeMapper.getRoomTypeById(order.getRoomTypeId()).getPrice();
        System.out.println(roomPrice);
        order.setPrice(night * roomPrice);
        int i = orderMapper.updateOrder(order);
        return i > 0;
    }
}
