package com.happy.service.impl;

import com.happy.Model.Booking;
import com.happy.Model.HotelDict;
import com.happy.Model.HouseNumber;
import com.happy.Model.HouseNumberStatus;
import com.happy.Until.DateUtil;
import com.happy.Until.Enum.PayEnum;
import com.happy.Until.Func;
import com.happy.Until.HttpUtils;
import com.happy.dao.BookDao;
import com.happy.dto.BookTypeEto;
import com.happy.dto.IPage;
import com.happy.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service("BookService")
public class BookImplService implements BookService {

    @Resource
    public BookDao bookDao;
    @Resource
    public BookinglogService bookinglogService;
    @Resource
    public AdminManagerService adminManagerService;

    @Resource
    public HotelDictService hotelDictService;

    @Resource
    public HouseNumberService houseNumberService;

    @Resource
    public HouseNumberStatusService houseNumberStatusService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public int insertBooking(Booking book) {
        return bookDao.insertBooking(book);
    }

    @Override
    public int updateBooking(Booking book) {
        return bookDao.updateBooking(book);
    }

    @Override
    public int delBooking(int id) {
        return bookDao.delBooking(id);
    }

    @Override
    public Booking getById(int id) {
        return bookDao.getById(id);
    }

    @Override
    public IPage<Booking> queryPage(String sqlx, int page, int rows) {
        IPage<Booking> iPage = new IPage();
        List<Booking> bookList = bookDao.queryPage(sqlx,page,rows);
        int total = bookDao.queryTotal(sqlx);
        iPage.setPageList(bookList);
        iPage.setPage(page);
        iPage.setTotalPage( (int)Math.ceil((double)total/rows));
        iPage.setRows(rows);
        iPage.setTotal(total);
        return iPage;
    }

    @Override
    public List<Booking> queryList(String sqlx) {
        return bookDao.queryList(sqlx);
    }

    @Override
    public Booking getOen(String sqlx){
        List<Booking> list = bookDao.queryList(sqlx);
        if(list!=null && list.size()>0) return list.get(0);
        return null;
    }

    @Override
    public Double sumAccount(String sqlx){
        return bookDao.sumAccount(sqlx);
    }

    @Override
    public BookTypeEto getBookStatusSum(String sqlx){
        return bookDao.getBookStatusSum(sqlx);
    }

//    @Override
//    public String cancelBooking(String bookingId) throws Exception {
//        if (Func.checkNull(bookingId))
//            return "未传入订单id";
//
//        Booking book = bookDao.getById(Func.parseInt(bookingId));
//        //是否能取消订单（1是 2否）
//        if (Func.parseInt(book.getHotelIsCanorder()) == 2)
//            return "商家设置不可取消订单，请联系商家";
//
//        AdminManager adminManager = adminManagerService.getById(Func.parseInt(book.getHotelManagerId()));
//
//        //1待支付,2已支付,3待入住,4已入住,5已消费,6支付超时,7已取消,8已退单,9已退款,10退款中
//        int status = Func.parseInt(book.getOrderStatus());
//        if (status == 1)
//        {
//            book.setOrderStatus(Func.parseStr(PayEnum.SEVEN.getNum())); // 如果在1待支付情况，用户点击取消订单按钮，后台直接修改取消订单操作
//            book.setUpdateTime(DateUtil.getFormatPaternDate(new Date()));
//            book.setRemake(Func.parseStr(PayEnum.FIVE.getPayStatus()));
//            bookDao.updateBooking(book);
//
//            return null;
//        }else if (status == 2 || status == 3)
//        {
//            book.setOrderStatus(Func.parseStr(PayEnum.TEN.getNum())); // 如果在2已支付,3待入住 情况，用户点击取消订单按钮，后台先修改状态为退款中，然后走退款流程
//            book.setUpdateTime(DateUtil.getFormatPaternDate(new Date()));
//            book.setRemake(Func.parseStr(PayEnum.FIVE.getPayStatus()));
//            if (book.getPayAccount() > 0)
//            {
//                // 注明如果支付金额大于0，则需要退款: （标识走退款操作）
//                book.setRefundWay(OrderEnum.微信退款.toString());
//            }
//            bookDao.updateBooking(book);
//
//            return null;
//        }
//        return "当前状态下，不可取消订单";
//    }

    @Override
    public String delBooking(String bookingId) {
        if (Func.checkNull(bookingId))
            return "未传入订单id";

        // 是否假删除：0删除，1正常
        Booking book = bookDao.getById(Func.parseInt(bookingId));
        if (book == null)
            return "无此订单，请重新查询";

        book.setStatus_del(0);
        book.setUpdateTime(DateUtil.getFormatPaternDate(new Date()));

        int status = Func.parseInt(book.getOrderStatus());
        if (status == PayEnum.待支付.getNum()) {
            book.setOrderStatus(Func.parseStr(PayEnum.已取消.getNum())); // 如果在1待支付情况，用户点击删除订单按钮，后台直接修改取消订单操作,(应当释放房间)
            book.setUpdateTime(DateUtil.getFormatPaternDate(new Date()));
            book.setRemake(Func.parseStr(PayEnum.已取消.getPayStatus()));
        }
        bookDao.updateBooking(book);

        // 退款成功后，写入数据操作
        bookinglogService.addBooklog("用户删除了这条订单的显示数据"  ,book);

        return null;
    }

    @Override
    public Booking queryByOrder(String orderNum) {
        List<Booking> list = bookDao.queryList("and order_num = '"+orderNum+"'");
        if(list!=null && list.size()>0) return list.get(0);
        return null;
    }

    @Override
    public int updateBookStatus() {
        HotelDict respTime = hotelDictService.getById(1997956735);//响应时间 状态1为10分、2为20分、3为30分
        String times = String.valueOf(respTime.getCode() * 10);
        HotelDict operate = hotelDictService.getById(1997956736);//响应时间 1自动接单 2自动拒单
        String sqlx = " and create_time <= DATE_SUB(NOW(), INTERVAL " + times + " MINUTE) and order_status = 2 ";
        List<Booking> bookings = bookDao.queryList(sqlx);
        List<HouseNumberStatus> list = new ArrayList<>();
        if (operate.getCode() == 1){
            bookings.forEach(booking -> {
                //不可入住的房间
                List<HouseNumber> houseNumbers = houseNumberService.queryHouseStatus(booking);
                //所有房间
                List<HouseNumber> houseNumberList = houseNumberService.queryByHouseId(booking.getHouseId());
                AtomicInteger i = new AtomicInteger();
                List<String> Ids = new ArrayList<>();
                if (houseNumbers != null){
                    houseNumberList.forEach(houseNumber -> {
                        //添加的房间不在不可添加的房间当中并且数量小于订房总数
                        if (!houseNumbers.contains(houseNumber) && i.get() < booking.getHouseOrderNumber()){
                            Ids.add(houseNumber.getId());
                            i.getAndIncrement();
                        }
                    });
                }

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime str = LocalDateTime.parse(booking.getOrderStartTime(), inputFormatter);
                LocalDateTime end = LocalDateTime.parse(booking.getOrderEndTime(), inputFormatter);
                String a = str.format(formatter);
                String B = end.format(formatter);
                LocalDate strDate = LocalDate.parse(a, formatter);
                LocalDate endDate = LocalDate.parse(B, formatter);
                Date now = null;
                try {
                    now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                for (String number : Ids){
                    for (LocalDate date = strDate; !date.isAfter(endDate.minusDays(1)); date = date.plusDays(1)){
                        HouseNumberStatus houseNumberStatus = new HouseNumberStatus();
                        houseNumberStatus.setNumberId(number);
                        houseNumberStatus.setId(String.valueOf(UUID.randomUUID()));
                        houseNumberStatus.setCreateDate(now);
                        houseNumberStatus.setModifyDate(now);
                        houseNumberStatus.setRemark("");
                        houseNumberStatus.setBookingId(String.valueOf(booking.getId()));
                        houseNumberStatus.setSetDate(date.format(formatter));
                        houseNumberStatus.setStatus(5);//状态(0删除 1.正常 2.关房 3.脏房 4.净房 5.预定 6.入住)
                        list.add(houseNumberStatus);
                    }
                }
            });
            return houseNumberStatusService.saveBatch(list);
        }else {
            String ip = request.getServerName();
            ip += "/mhotel/abkchargeback.action";
            String finalIp = ip;
            bookings.forEach(booking -> {
                Map<String, String> params = new HashMap<String, String>();
                params.put("bookingId", String.valueOf(booking.getId()));
                try {
                    String msg = HttpUtils.post(finalIp, params);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        return 0;
    }



}
