package com.happy.action;

import com.baidubce.model.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.happy.Model.*;
import com.happy.Model.app.Tongji;
import com.happy.Model.weixin.Users;
import com.happy.Model.weixin.WeiXinUtil;
import com.happy.Until.*;
import com.happy.Until.Enum.TempEnum;
import com.happy.Until.Excel.toExcel;
import com.happy.common.http.Message;
import com.happy.dto.BookTypeEto;
import com.happy.dto.HouseNumberDto;
import com.happy.dto.IPage;
import com.happy.service.*;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
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;
import java.util.stream.Collectors;

public class bookAction extends ActionSupport implements ServletRequestAware {

    private HttpServletRequest request;
    public HttpServletResponse response;

    @Resource
    public BookService bookService;
    @Resource
    public UserService userService;
    @Resource
    public HotelDictService hotelDictService;
    @Resource
    public AdminManagerService adminManagerService;

    @Resource
    public HouseNumberStatusService houseNumberStatusService;

    @Resource
    public HouseNumberService houseNumberService;

    @Resource
    public HotelCoupomService hotelCoupomService;
    @Resource
    public HotelCoupomStatusService hotelCoupomStatusService;


    public int page; // 当前页
    public int rows;// 每页显示的行数rows
    public Integer id;
    public Integer type;
    public String orderStatus;//订单状态
    public String managerId;//商户Id
    public String payStartTime;//支付开始时间
    public String payEndTime;//支付结束时间
    public String ledgerParam;//台账列表查询参数
    public String hotelTownship;//所属乡镇
    public String minTotalPrice;//最小订单总价
    public String maxTotalPrice;//最大订单总价
    public String houseNumberIds; // 房间号ids
    public String leaveStartTime;  // 离店开始时间
    public String leaveEndTime;  // 离店结束
    public Integer saccountState;  // 清账状态

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    /**
     * 描述：修改订单状态接单、入住、退房
     *
     * @return
     */
    public String updateBookStatus() {
        JSONObject resultJson = new JSONObject();
        if (id == null) {
            resultJson.put("message", "请传入订单id");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        //根据id获取当前订单信息
        Booking book = bookService.getById(id);
        if (book == null) {
            resultJson.put("message", "未查询到订单");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        //获取用户openId
        Users user = userService.queryByUserId(book.getCreateUserid());
        if (user.getOpenid() == null) {
            resultJson.put("message", "用户openId为空，请该订单用户授权才能操作。");
            resultJson.put("code", 502);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        String msg = "";
        String sendMsg = "";
        try {
            switch (type) {
                case 1://接单
                    if (!"2".equals(book.getOrderStatus())) {
                        resultJson.put("message", "已支付状态才能接单");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    book.setOrderStatus("3");
                    book.setUpdateTime(UUIDUtil.getNewDate());
                    msg = "接单";
                    sendMsg = "商家已接单";
                    //验证民宿房态表
                    List<HouseNumber> houseNumbers = houseNumberService.queryHouseStatus(book);
                    List<HouseNumber> houseNumberList = houseNumberService.queryByHouseId(book.getHouseId());
                    List<String> Ids = new ArrayList<>();
                    AtomicInteger i = new AtomicInteger();
                    if (houseNumbers != null) {
//                        houseNumberList.forEach(houseNumber -> {
//                            //添加的房间不在不可添加的房间当中并且数量小于订房总数
//
//                        });
                        List<String> houseStrs = houseNumbers.stream().map(HouseNumber::getId).collect(Collectors.toList());
                        for (HouseNumber houseNumber : houseNumberList) {
                            if (!houseStrs.contains(houseNumber.getId()) && i.get() < book.getHouseOrderNumber()) {
                                Ids.add(houseNumber.getId());
                                i.getAndIncrement();
                            }
                        }

                    } else {
                        //所有房间都可以预定
                        houseNumberList.forEach(houseNumber -> {
                            //添加的房间不在不可添加的房间当中并且数量小于订房总数
                            if (i.get() < book.getHouseOrderNumber()) {
                                Ids.add(houseNumber.getId());
                                i.getAndIncrement();
                            }
                        });
                    }
                    //添加民宿房态表
                    List<HouseNumberStatus> list = handleHouseStatus(Ids, 5, book);
                    int m = houseNumberStatusService.saveBatch(list);
                    if (m == 0) {
                        resultJson.put("message", "确认失败");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    break;
                case 2://入住
                    if (!"3".equals(book.getOrderStatus())) {
                        resultJson.put("message", "待入住状态才能办理入住");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    if (houseNumberIds == null || "".equals(houseNumberIds)) {
                        resultJson.put("message", "请分配房间号");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    List<String> ids = Arrays.asList(houseNumberIds.split(","));
                    if (book.getHouseOrderNumber() != ids.size()) {
                        resultJson.put("message", "房间数不一致");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    List<HouseNumber> houseNumbers1 = houseNumberService.queryHouseStatus(book);

                    if (houseNumbers1 != null) {
                        for (String id : ids) {
                            for (HouseNumber houseNumber : houseNumbers1) {
                                if (houseNumber.getStatus() != null && houseNumber.getStatus() == 3 && id.equals(houseNumber.getId())) {
                                    resultJson.put("message", "选择的房间该时间段已有预定！请重新选择房间！");
                                    resultJson.put("code", 502);
                                    ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                                    return null;
                                }
                            }
                        }
                    }
                    //删除 预定房态
                    int a = houseNumberStatusService.updateHouseNumberStatus(String.valueOf(id));
                    if (a == 0) {
                        resultJson.put("message", "确认失败");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    //写入 入住数据
                    List<HouseNumberStatus> list1 = handleHouseStatus(ids, 6, book);
                    int n = houseNumberStatusService.saveBatch(list1);
                    if (n == 0) {
                        resultJson.put("message", "确认失败");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    book.setOrderStatus("4");
                    book.setLiveTime(UUIDUtil.getNewDate());
                    book.setUpdateTime(UUIDUtil.getNewDate());
                    userService.addhotelAndUsers(book.getHotelId(), book.getCreateUserid(), TempEnum.住过); // 办理入住，则将信息写入用户入住过的酒店  editor by xieli
                    msg = "入住办理";
                    break;
                case 3://退房
                    if (!"4".equals(book.getOrderStatus())) {
                        resultJson.put("message", "已入住状态才能办理退房");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    //房态删除
                    String sql = " and booking_id = " + id;
                    List<HouseNumberStatus> houseNumberStatuse = houseNumberStatusService.getList(sql);
                    int i1 = houseNumberStatusService.updateHouseNumberStatus(String.valueOf(id));
                    if (i1 == 0) {
                        resultJson.put("message", "退房失败");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    //房间设为脏房
                    String numberIds = houseNumberStatuse.stream().map(HouseNumberStatus::getNumberId).distinct().collect(Collectors.joining());
                    int i2 = houseNumberService.updateHouseStatus(numberIds);
                    if (i2 == 0) {
                        resultJson.put("message", "退房失败");
                        resultJson.put("code", 502);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    book.setCheckOutTime(UUIDUtil.getNewDate());//退房时间
                    book.setUpdateTime(UUIDUtil.getNewDate());
                    book.setOrderStatus("5");
                    msg = "退房";


                    //通过订单id找到所属优惠券
                    List<HotelCouponStatus> hotelCouponStatusList = hotelCoupomStatusService.getBookingId(book.getId() + "");
                    if (hotelCouponStatusList != null && hotelCouponStatusList.size() > 0) {
                        System.out.println("进入核销优惠券");
                        for (HotelCouponStatus hotelCouponStatus : hotelCouponStatusList) {
                            String complaintId = hotelCouponStatus.getComplaintId();
                            System.out.println("核销优惠券id:" + complaintId);
                            HotelCoupon hotelCoupon = hotelCoupomService.getById(complaintId);
                            if (hotelCoupon != null) {
                                Integer reversedNumber = hotelCoupon.getReversedNumber();
                                if (reversedNumber == null) {
                                    reversedNumber = 0;
                                }
                                hotelCoupon.setReversedNumber(reversedNumber + 1);
                                hotelCoupon.setModifyDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                                hotelCoupomService.updatReversedNumber(hotelCoupon);
                            }
                        }
                    }


                    break;
//                case 4://退单
//                    if(!"2".equals(book.getOrderStatus())){
//                        resultJson.put("message", "已支付状态才能退单");
//                        resultJson.put("code", 502);
//                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
//                        return null;
//                    }
//                    book.setOrderStatus("8");
//                    book.setUpdateTime(UUIDUtil.getNewDate());
//                    msg = "退单";
//                    sendMsg = "商家已退单";
//                    break;
            }
            int m = bookService.updateBooking(book);
            if (m > 0) {
                //推送信息
                if (!"".equals(sendMsg)) {
                    String liveTime = book.getOrderStartTime() != null ? book.getOrderStartTime().substring(0, 10) : "";
                    String endTime = book.getOrderEndTime() != null ? book.getOrderEndTime().substring(0, 10) : "";
                    String errmsg = Message.wxErrorMsg(Message.send(user.getOpenid(), book.getHotelName(), book.getOrderStatus(), liveTime, endTime, book.getHouseName()));
                    if ("请求成功".equals(errmsg)) {
                        resultJson.put("message", msg + "成功");
                        resultJson.put("code", 200);
                        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                        return null;
                    }
                    //resultJson.put("message", msg+"成功"+",推送消息失败，原因："+errmsg);
                    resultJson.put("message", "接单成功，因用户未订阅小程序消息，无法推送消息，请通过电话或者短信通知旅客！");
                    resultJson.put("code", 500);
                    ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                    return null;
                }
                resultJson.put("message", msg + "成功");
                resultJson.put("code", 200);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            } else {
                resultJson.put("message", msg + "失败");
                resultJson.put("code", 502);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultJson.put("message", "未知异常");
        resultJson.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }

    /**
     * 根据传入传入房间号写入状态
     */
    private List<HouseNumberStatus> handleHouseStatus(List<String> Ids, int status, Booking book) throws ParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime str = LocalDateTime.parse(book.getOrderStartTime(), inputFormatter);
        LocalDateTime end = LocalDateTime.parse(book.getOrderEndTime(), inputFormatter);
        String a = str.format(formatter);
        String B = end.format(formatter);
        LocalDate strDate = LocalDate.parse(a, formatter);
        LocalDate endDate = LocalDate.parse(B, formatter);
        List<HouseNumberStatus> list = new ArrayList<>();
        Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
        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(book.getId()));
                houseNumberStatus.setSetDate(date.format(formatter));
                houseNumberStatus.setStatus(status);//状态(0删除 1.正常 2.关房 3.脏房 4.净房 5.预定 6.入住)
                list.add(houseNumberStatus);
            }
        }
        return list;
    }

    /**
     * 描述：分页查询订单
     *
     * @return
     */
    public String quearyBookPage() {
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        if (managerId != null) {
            s1.append(" and hotel_manager_id = '").append(managerId).append("'");
        }
        if (ledgerParam != null) {
            s1.append(" and (order_num like '%").append(ledgerParam).append("%'")
                    .append(" or user_name like '%").append(ledgerParam).append("%'")
                    .append(" or user_phone like '%").append(ledgerParam).append("%')");
        }
        if (orderStatus != null) {
            s1.append(" and order_status = ").append(orderStatus);
        }
        if (payStartTime != null && payEndTime != null) {
            s1.append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') >= '").append(payStartTime).append("'")
                    .append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') <= '").append(payEndTime).append("'");
        }
        IPage<Booking> bookIPage = bookService.queryPage(s1.toString(), page, rows, "create_time");
        //获取订单汇总信息
        BookTypeEto bookTypeEto = bookService.getBookStatusSum(s1.toString());
        bookTypeEto.setSumAccount(new BigDecimal(bookTypeEto.getSumAccount()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        bookTypeEto.setBookIPage(bookIPage);

        if (bookTypeEto != null && !"".equals(bookTypeEto)) {
            resultJson.put("message", "查询分页成功");
            resultJson.put("code", 200);
            resultJson.put("data", bookTypeEto);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        } else {
            resultJson.put("message", "查询分页失败");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }
        return null;
    }

    /**
     * 描述：导出订单
     *
     * @return
     */
    public String toBookExcel() {
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        s1.append(" and hotel_manager_id = '").append(managerId).append("'");
        if (managerId == null) {
            resultJson.put("code", 500);
            resultJson.put("message", "managerId禁止为空");
            ResponseUtil.writeJson(ServletActionContext.getResponse(),
                    resultJson.toString());
        }
        if (ledgerParam != null) {
            s1.append(" and (order_num like '%").append(ledgerParam).append("%'")
                    .append(" or user_name like '%").append(ledgerParam).append("%'")
                    .append(" or user_phone like '%").append(ledgerParam).append("%')");
        }
        if (orderStatus != null) {
            s1.append(" and order_status = ").append(orderStatus);
        }
        if (payStartTime != null && payEndTime != null) {
            s1.append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') >= '").append(payStartTime).append("'")
                    .append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') <= '").append(payEndTime).append("'");
        }

        List<Booking> list = bookService.queryList(s1.toString()); // 查询分页
        List<Vector> vectorsList = new ArrayList<>();
        if (list == null) {
            resultJson.put("code", 500);
            resultJson.put("message", "无数据无法导出");
            ResponseUtil.writeJson(ServletActionContext.getResponse(),
                    resultJson.toString());
        }
        for (Booking book : list) {
            Vector columnValue = new Vector();
            columnValue.add(book.getOrderNum());
            columnValue.add(book.getOrderName());
            columnValue.add(book.getUserName());//用户名称
            columnValue.add(book.getUserPhone());//用户电话
            columnValue.add(book.getHouseName());//房型名称
            columnValue.add(book.getHouseOrderNumber());//订房数量
            columnValue.add(book.getHouseTotalPrice());//总价
            columnValue.add(book.getPayTime());
            vectorsList.add(columnValue);
        }
        // 项目路径地址
        String path = request.getSession().getServletContext()
                .getRealPath("/download/");// File.separator
        try {
            Vector columnName = new Vector();
            columnName.add("订单号");
            columnName.add("状态");
            columnName.add("预定人");
            columnName.add("手机号");
            columnName.add("预定房型");
            columnName.add("房间数");
            columnName.add("订单金额（元）");
            columnName.add("支付时间");

            String filePathName = "订单信息" + UUIDUtil.generateID() + "Report.xls";
            // 导出文件
            new toExcel().book(vectorsList, path + filePathName,
                    "sheet1", columnName);
            String url = WeiXinUtil.ip_h;//"https://chtech.ncjti.edu.cn/hotelReservation/mhotel";
            resultJson.put("downurl", url + "/download/" + filePathName);
            resultJson.put("code", 200);
            resultJson.put("message", "导出成功");
            ResponseUtil.writeJson(ServletActionContext.getResponse(),
                    resultJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 描述：分页查询台账（查询以消费订单数据）
     *
     * @return
     */
    public String quearyLedgerPage() {
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        s1.append(" and order_status in ('2','3','4','5','7','8','9','10') ");
        if (managerId != null) {
            s1.append(" and hotel_manager_id = '").append(managerId).append("'");
        }
        if (ledgerParam != null) {
            s1.append(" and (order_num like '%").append(ledgerParam).append("%'")
                    .append(" or hotel_name like '%").append(ledgerParam).append("%'")//民宿名称
                    .append(" or user_name like '%").append(ledgerParam).append("%'")
                    .append(" or user_phone like '%").append(ledgerParam).append("%')");
        }
        if (payStartTime != null && payEndTime != null) {
            s1.append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') >= '").append(payStartTime).append("'")
                    .append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') <= '").append(payEndTime).append("'");
        }
        if (leaveStartTime != null && leaveEndTime != null) {
            s1.append(" and DATE_FORMAT(check_out_time,'%Y-%m-%d') >= '").append(leaveStartTime).append("'")
                    .append(" and DATE_FORMAT(check_out_time,'%Y-%m-%d') <= '").append(leaveEndTime).append("'");
        }
        if (hotelTownship != null) {
            s1.append(" and hotel_township = '").append(hotelTownship).append("'");
        }
        if (minTotalPrice != null) {
            s1.append(" and house_total_price >= '").append(minTotalPrice).append("'");
        }
        if (maxTotalPrice != null) {
            s1.append(" and house_total_price <= '").append(maxTotalPrice).append("'");
        }
        if (saccountState != null) {
            s1.append(" and saccount_state = '").append(saccountState).append("'");
        }
        IPage<Booking> bookIPage = bookService.queryPage(s1.toString(), page, rows, "check_out_time");
        //获取订单汇总信息
        BookTypeEto bookTypeEto = bookService.getBookStatusSum(s1.toString());
        bookTypeEto.setBookIPage(bookIPage);
        if (bookTypeEto != null && !"".equals(bookTypeEto)) {
            resultJson.put("message", "查询分页成功");
            resultJson.put("code", 200);
            resultJson.put("data", bookTypeEto);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        } else {
            resultJson.put("message", "查询分页失败");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        }
        return null;
    }

    public String modifyAaccountStatus() throws IOException {
        JSONObject resultjson = new JSONObject();
        Gson gson = new Gson();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        System.out.println(json);
        if (json == null) {
            resultjson.put("message", "请传入参数");
            ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }
        Booking booking = null;
        try {
            booking = gson.fromJson(json.toString(), new TypeToken<Booking>() {
            }.getType());
            if (booking == null) {
                resultjson.put("message", "数据为空");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            if (booking.getSaccountState() == null || booking.getHotelConfigList() == null) {
                resultjson.put("message", "各参数不能为空");
                resultjson.put("code", 500);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
            booking.setSaccountTime(TimeExchange.getTime());
            int m = bookService.updateSaccount(booking);
            if (m > 0) {
                resultjson.put("message", "清账成功");
                resultjson.put("code", 200);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            } else {
                resultjson.put("message", "清账失败");
                resultjson.put("code", 502);
                ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultjson.put("message", "数据格式不正确");
        resultjson.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
        return null;
    }

    /**
     * 描述：台账统计
     *
     * @return
     */
    public String queryLedgerTj() {
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        s1.append(" and order_status in ('2','3','4','5','7','8','9','10') ");
        if (managerId != null) {
            s1.append(" and hotel_manager_id = '").append(managerId).append("'");
        }
        if (ledgerParam != null) {
            s1.append(" and (order_num like '%").append(ledgerParam).append("%'")
                    .append(" or hotel_name like '%").append(ledgerParam).append("%'")//民宿名称
                    .append(" or user_name like '%").append(ledgerParam).append("%'")
                    .append(" or user_phone like '%").append(ledgerParam).append("%')");
        }
        if (payStartTime != null && payEndTime != null) {
            s1.append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') >= '").append(payStartTime).append("'")
                    .append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') <= '").append(payEndTime).append("'");
        }
        if (leaveStartTime != null && leaveEndTime != null) {
            s1.append(" and DATE_FORMAT(check_out_time,'%Y-%m-%d') >= '").append(leaveStartTime).append("'")
                    .append(" and DATE_FORMAT(check_out_time,'%Y-%m-%d') <= '").append(leaveEndTime).append("'");
        }
        if (hotelTownship != null) {
            s1.append(" and hotel_township = '").append(hotelTownship).append("'");
        }
        if (minTotalPrice != null) {
            s1.append(" and house_total_price >= '").append(minTotalPrice).append("'");
        }
        if (maxTotalPrice != null) {
            s1.append(" and house_total_price <= '").append(maxTotalPrice).append("'");
        }
        if (saccountState != null) {
            s1.append(" and saccount_state = '").append(saccountState).append("'");
        }
        Tongji orderT = bookService.queryOrderT(s1.toString());
        Tongji payT = bookService.queryPayT(s1.toString());
        Tongji refundT = bookService.queryRefundT(s1.toString());
        Tongji inT = bookService.queryInT(s1.toString());
        resultJson.put("message", "返回成功");
        resultJson.put("code", 200);
        resultJson.put("orderT", orderT);
        resultJson.put("payT", payT);
        resultJson.put("refundT", refundT);
        resultJson.put("inT", inT);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
        return null;
    }

    /**
     * 描述：根据Id查询订单详细
     *
     * @return
     */
    public String getById() {
        JSONObject resultJson = new JSONObject();
        if (id == null) {
            resultJson.put("message", "请传入id");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        Booking book = bookService.getById(id);
        List<HouseNumber> houseNumbers = houseNumberService.queryCheckRoom(book);
        book.setHouseNumbers(houseNumbers);
        if (book != null) {
            resultJson.put("message", "查询成功");
            resultJson.put("code", 200);
            resultJson.put("data", book);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        } else {
            resultJson.put("message", "未查到用户信息");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
    }

    /**
     * 描述：导出台账
     *
     * @return
     */
    public String toLedgerExcel() {
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        s1.append(" and order_status in ('2','3','4','5','7','8','9','10') ");
        if (managerId != null) {
            s1.append(" and hotel_manager_id = '").append(managerId).append("'");
        }
        if (ledgerParam != null) {
            s1.append(" and (order_num like '%").append(ledgerParam).append("%'")
                    .append(" or hotel_name like '%").append(ledgerParam).append("%'")//民宿名称
                    .append(" or user_name like '%").append(ledgerParam).append("%'")
                    .append(" or user_phone like '%").append(ledgerParam).append("%')");
        }
        if (payStartTime != null && payEndTime != null) {
            s1.append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') >= '").append(payStartTime).append("'")
                    .append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') <= '").append(payEndTime).append("'");
        }
        if (leaveStartTime != null && leaveEndTime != null) {
            s1.append(" and DATE_FORMAT(check_out_time,'%Y-%m-%d') >= '").append(leaveStartTime).append("'")
                    .append(" and DATE_FORMAT(check_out_time,'%Y-%m-%d') <= '").append(leaveEndTime).append("'");
        }
        if (hotelTownship != null) {
            s1.append(" and hotel_township = '").append(hotelTownship).append("'");
        }
        if (minTotalPrice != null) {
            s1.append(" and house_total_price >= '").append(minTotalPrice).append("'");
        }
        if (maxTotalPrice != null) {
            s1.append(" and house_total_price <= '").append(maxTotalPrice).append("'");
        }
        if (saccountState != null) {
            s1.append(" and saccount_state = '").append(saccountState).append("'");
        }

        List<Booking> list = bookService.queryList(s1.toString() + " order by check_out_time desc"); // 查询列表
        if (list == null) {
            resultJson.put("code", 500);
            resultJson.put("message", "无数据无法导出");
            ResponseUtil.writeJson(ServletActionContext.getResponse(),
                    resultJson.toString());
        }
        List<Vector> vectorsList = new ArrayList<>();
        for (Booking book : list) {
            Vector columnValue = new Vector();
            columnValue.add(book.getOrderNum());
            columnValue.add(book.getUserName());
            columnValue.add(book.getUserPhone());
            columnValue.add(book.getHouseOrderNumber());
            columnValue.add(book.getPayAccount());
            columnValue.add(book.getCheckOutTime());
            vectorsList.add(columnValue);
        }
        // 项目路径地址
        String path = request.getSession().getServletContext()
                .getRealPath("/download/");
        ;// File.separator

        try {
            Vector columnName = new Vector();
            columnName.add("订单号");
            columnName.add("预定人");
            columnName.add("手机号");
            columnName.add("房间数");
            columnName.add("订单金额");
            columnName.add("退房时间");

            String filePathName = "台账信息" + UUIDUtil.generateID() + "Report.xls";
            // 导出文件
            new toExcel().book(vectorsList, path + filePathName,
                    "sheet1", columnName);
            String url = WeiXinUtil.ip_h;//"https://chtech.ncjti.edu.cn/hotelReservation/mhotel";
            resultJson.put("downurl", url + "/download/" + filePathName);
            resultJson.put("code", 200);
            resultJson.put("message", "导出成功");
            ResponseUtil.writeJson(ServletActionContext.getResponse(),
                    resultJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 描述：导出台账 管理端
     *
     * @return
     */
    public String toLedgerAdmimnExcel() {
        JSONObject resultJson = new JSONObject();
        StringBuilder s1 = new StringBuilder("");
        s1.append(" and order_status = 5");
        if (ledgerParam != null) {
            s1.append(" and (order_num like '%").append(ledgerParam).append("%'")
                    .append(" or user_name like '%").append(ledgerParam).append("%'")
                    .append(" or user_phone like '%").append(ledgerParam).append("%')");
        }
        if (payStartTime != null && payEndTime != null) {
            s1.append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') >= '").append(payStartTime).append("'")
                    .append(" and DATE_FORMAT(pay_time,'%Y-%m-%d') <= '").append(payEndTime).append("'");
        }
        if (hotelTownship != null) {
            s1.append(" and hotel_township = '").append(payStartTime).append("'");
        }
        if (minTotalPrice != null) {
            s1.append(" and house_total_price >= '").append(minTotalPrice).append("'");
        }
        if (maxTotalPrice != null) {
            s1.append(" and house_total_price <= '").append(maxTotalPrice).append("'");
        }

        List<Booking> list = bookService.queryList(s1.toString() + " order by check_out_time desc"); // 查询列表
        List<HotelDict> hotelDicts = hotelDictService.queryList("and code = 10");
        Map<Integer, String> dictMap = null;
        if (hotelDicts != null && hotelDicts.size() > 0) {
            dictMap = hotelDicts.stream().collect(Collectors.toMap(HotelDict::getId, HotelDict::getName, (key1, key2) -> key1));
        } else {
            resultJson.put("message", "未查到民宿乡镇信息");
            resultJson.put("code", 500);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
            return null;
        }
        List<Vector> vectorsList = new ArrayList<>();
        for (Booking book : list) {
            Vector columnValue = new Vector();
            AdminManager adminManager = adminManagerService.getById(book.getHotelManagerId());
            if (adminManager != null) {
                columnValue.add(dictMap.get(Integer.valueOf(adminManager.getHotelTownship())));//所属乡镇
                columnValue.add(adminManager.getHotelName());//乡宿名称
            } else {
                columnValue.add("");//所属乡镇
                columnValue.add("");//乡宿名称
            }
            columnValue.add(book.getOrderNum());//订单号
            columnValue.add(book.getPayAccount());//订单金额
            columnValue.add(book.getCheckOutTime());//退房时间
            vectorsList.add(columnValue);
        }
        // 项目路径地址
        String path = request.getSession().getServletContext()
                .getRealPath("/download/");// File.separator

        System.out.println("导出接口：" + path);

        try {
            Vector columnName = new Vector();
            columnName.add("所属乡镇");
            columnName.add("民宿名称");
            columnName.add("订单号");
            columnName.add("订单金额(元)");
            columnName.add("退房时间");

            String filePathName = "台账信息" + UUIDUtil.generateID() + "Report.xls";
            // 导出文件
            new toExcel().book(vectorsList, path + filePathName,
                    "sheet1", columnName);
            String url = WeiXinUtil.ip_h;//"https://chtech.ncjti.edu.cn/hotelReservation/mhotel";
            resultJson.put("downurl", url + "/download/" + filePathName);
            resultJson.put("code", 200);
            resultJson.put("message", "导出成功");
            ResponseUtil.writeJson(ServletActionContext.getResponse(),
                    resultJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 定时任务
     * 搞定超时未处理的手动接单数据
     */
    public void setBookStatus() throws Exception {

        System.out.println("手动接单定时程序");

        HotelDict respTime = hotelDictService.getById(1111111111);//响应时间

        System.out.println("手动接单定时程序1");

        HotelDict operate = hotelDictService.getById(1000011002);//响应时间 1手动接单 2自动拒单

        System.out.println("手动接单定时程序2");
        String dateTime = TimeExchange.TimeRangeI(TimeExchange.getTime(), Integer.valueOf(respTime.getName()), "yyyy-MM-dd HH:mm:ss");
        String sqlx = " and create_time <= '" + dateTime + "' and order_status = 2 and hotel_is_order = 2";
        List<Booking> bookings = bookService.queryList(sqlx);

        System.out.println("手动接单定时程序3：" + sqlx);

        String result = bookings == null ? "" : bookings.stream().map(Booking::getOrderNum).collect(Collectors.joining());

        System.out.println("手动接单,订单编号：" + result + "；拼接条件：" + sqlx);

        AtomicInteger n = new AtomicInteger();
        if ("1".equals(operate.getName())) {
            System.out.println("手动接单定时程序4");
            for (Booking booking : bookings) {
                System.out.println("手动接单定时程序5");
                List<HouseNumberStatus> list = new ArrayList<>();
                //不可入住的房间
                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();
                        }
                    });
                } else {
                    //所有房间都可以预定
                    houseNumberList.forEach(houseNumber -> {
                        //添加的房间不在不可添加的房间当中并且数量小于订房总数
                        if (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);
                    }
                }
                int m = houseNumberStatusService.saveBatch(list);
                Users users = userService.queryByUserId(booking.getCreateUserid());
                if (m > 0) {
                    n.getAndIncrement();
                    booking.setOrderStatus("3");
                    booking.setUpdateTime(UUIDUtil.getNewDate());
                    bookService.updateBooking(booking);
                    Message.send(users.getOpenid(), booking.getHotelName(), booking.getOrderStatus(), booking.getOrderStartTime(), booking.getOrderEndTime(), booking.getHouseName());
                }
            }
        } else {
            System.out.println("手动接单定时程序6");
            HotelDict dict = hotelDictService.getById(1000011999);
            for (Booking booking : bookings) {
                Map<String, String> params = new HashMap<>();
                params.put("bookingId", String.valueOf(booking.getId()));
                try {
                    String msg = HttpUtils.post(dict.getFileUrl(), params);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
