package com.happy.action;

import com.happy.Model.*;
import com.happy.Model.weixin.PayResult;
import com.happy.Model.weixin.Users;
import com.happy.Model.weixin.WechatUnifiedOrder;
import com.happy.Model.weixin.WeiXinUtil;
import com.happy.Until.*;
import com.happy.Until.Enum.B;
import com.happy.Until.Enum.OrderEnum;
import com.happy.Until.Enum.PayEnum;
import com.happy.Until.weixin.EndPay;
import com.happy.Until.weixin.JaxbUtil;
import com.happy.Until.weixin.PayWxUtil;
import com.happy.Until.weixin.TongYiReturn;
import com.happy.common.http.Message;
import com.happy.common.http.Message2;
import com.happy.common.wx.WxUtil;
import com.happy.constant.ResultStatusCode;
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.BufferedReader;
import java.io.PrintWriter;
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;

/**
 * 订单进去Action请求交互
 */
public class AppBookingAction extends ActionSupport implements ServletRequestAware {

    private HttpServletRequest request;
    public HttpServletResponse response;

    @Resource
    public BookService bookService;
    @Resource
    public BookinglogService bookinglogService;
    @Resource
    public UserService userService;
    @Resource
    public AppBookService appBookService;
    @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 String status;
    public String hotelId; // 酒店id
    public String houseId; // 房型id
    public String startTime; // 订房开始时间
    public String endTime;   // 订房结束时间
    public String houseOrderNumber; // 订房数量
    public String userName; // 住客姓名
    public String userPhone; // 住客联系电话
    public String userId; // 下单人id

    public String getBookingId() {
        return bookingId;
    }

    public void setBookingId(String bookingId) {
        this.bookingId = bookingId;
    }

    private String bookingId; // 订单Id
    private String open_id; // 用户open_Id

    public HttpServletRequest getRequest() {
        return request;
    }

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

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

    public HttpServletResponse getResponse() {
        return response;
    }

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

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String complaintId;
    public String useId;

    public String getComplaintId() {
        return complaintId;
    }

    public void setComplaintId(String complaintId) {
        this.complaintId = complaintId;
    }

    public String getUseId() {
        return useId;
    }

    public void setUseId(String useId) {
        this.useId = useId;
    }

    /**
     * 定时任务
     *
     * @return
     */
    public String scheduledTasks() {
        // 获取所有的订单待支付状态
        StringBuffer strSqlBook = new StringBuffer();
        strSqlBook.append(" and order_status = '").append(PayEnum.待支付.getNum()).append("' ");
        List<Booking> bookingList = bookService.queryList(strSqlBook.toString());
        if (bookingList == null || bookingList.size() <= 0) {
            return null;
        }

        try {
            for (Booking booking : bookingList) {
                if (booking == null || Func.checkNull(booking.getCreateTime()) || Func.checkNull(booking.getLockTime()))
                    continue;

                Date createTime = DateUtil.parseDate(booking.getCreateTime(), DateUtil.Time_Formatter_Second);
                // 对订单时间进行累加
                String lockTime = TimeExchange.TimeRangeM(DateUtil.getFormatPaternDate(createTime), Func.parseInt(booking.getLockTime()));
                // 当前时间 大于 锁定时间 为true  且支付状态
                boolean flag = TimeExchange.CompareDate(lockTime, TimeExchange.getDate());
                if (flag) {
                    // 如果超时，则将订单状态修改为已超时
                    booking.setOrderStatus(Func.parseStr(PayEnum.支付超时.getNum()));
                    booking.setUpdateTime(TimeExchange.getDate());
                    bookService.updateBooking(booking);
                    List<HotelCouponStatus> list = hotelCoupomStatusService.getBookingId(booking.getId() + "");
                    if (list != null && list.size() > 0) {
                        hotelCoupomStatusService.restitution(list);
                    }
                    // 将状态修改为已超时订单时，写入数据操作
                    bookinglogService.addBooklog(OrderEnum.将订单设置为已超时.toString(), booking);

                    System.out.println("已将订单" + booking.getOrderNum() + "标识为支付超时");
                }
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 进行更新数据将订单状态修改为已超时。
     *
     * @return
     */
    public String updateOrderStatus() {
        JSONObject jsonObject = new JSONObject();
        if (Func.checkNull(bookingId)) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, "未传入bookingId---updateOrderStatus");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        try {
            Booking booking = bookService.getById(Func.parseInt(bookingId));
            Date createTime = DateUtil.parseDate(booking.getCreateTime(), DateUtil.Time_Formatter_Second);
            // 对订单时间进行累加
            String lockTime = TimeExchange.TimeRangeM(DateUtil.getFormatPaternDate(createTime), Func.parseInt(booking.getLockTime()));
            // 当前时间 大于 锁定时间 为true  且支付状态
            boolean flag = TimeExchange.CompareDate(lockTime, TimeExchange.getDate());
            if (flag) {
                // 如果超时，则将订单状态修改为已超时
                booking.setOrderStatus(Func.parseStr(PayEnum.支付超时.getNum()));
                booking.setUpdateTime(TimeExchange.getDate());
                bookService.updateBooking(booking);

                // 将状态修改为已超时订单时，写入数据操作
                bookinglogService.addBooklog(OrderEnum.将订单设置为已超时.toString(), booking);

                List<HotelCouponStatus> list = hotelCoupomStatusService.getBookingId(booking.getId() + "");
                if (list != null && list.size() > 0) {
                    hotelCoupomStatusService.restitution(list);
                    System.out.println("返回优惠券");
                }
                System.out.println("已将订单" + booking.getOrderNum() + "标识为支付超时");

                jsonObject.put(B.code, ResultStatusCode.OK.getStatus());
                jsonObject.put(B.message, "已将订单" + booking.getOrderNum() + "标识为支付超时");
                ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


    /**
     * houseId; // 房型id
     * startTime; // 订房开始时间 2023/08/04
     * endTime;   // 订房结束时间 2023/08/05
     * houseOrderNumber; // 订房数量
     * userName; // 住客姓名
     * userPhone; // 住客联系电话
     * userId; // 下单人id
     * 用户点击订房操作，生成订单
     */
    public String createOrder() throws ParseException {
        // 插入订单数据到表中
        JSONObject jsonObject = new JSONObject();
        if (Func.checkNull(houseId) || Func.checkNull(startTime) || Func.checkNull(endTime)
                || Func.checkNull(houseOrderNumber) || Func.checkNull(userName) || Func.checkNull(userPhone) || Func.checkNull(userId)) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, ResultStatusCode.BAD_REQUEST.getMsg());
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        // 将时间统一转化为 yyyy/MM/dd
        String startDate = DateUtil.parseDateToStr((Func.parseDate(startTime)), DateUtil.Time_Formatter_Day);
        String endDate = DateUtil.parseDateToStr((Func.parseDate(endTime)), DateUtil.Time_Formatter_Day);

        // 创建订单之前，先验证是否有房间
        String backMessage = appBookService.varificationHouse(houseId, startDate, endDate, houseOrderNumber);
        if (!Func.checkNull(backMessage)) {
            jsonObject.put(B.code, ResultStatusCode.CANNTBOOKING.getStatus());
            jsonObject.put(B.message, backMessage);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        String bookingId = Func.parseStr(UUIDUtil.generateID());
        String mess = appBookService.createOrder(bookingId, houseId, startDate, endDate, houseOrderNumber, userName, userPhone, userId, complaintId, useId);
        if (!Func.checkNull(mess)) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, mess);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        jsonObject.put(B.code, ResultStatusCode.OK.getStatus());
        jsonObject.put(B.message, ResultStatusCode.OK.getMsg());
        jsonObject.put(B.data, bookingId);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }


    /**
     * bookingId 订单id
     * 商家在已支付，待入住时点退单 ，进入退款流程后退单
     * 在已入住，时点退单，进入退款流程后退款
     *
     * @return
     */
    public String chargeback() throws Exception {
        if (Func.checkNull(bookingId))
            return null;

        JSONObject jsonObject = new JSONObject();
        Booking book = bookService.getById(Func.parseInt(bookingId));
        Users users = userService.queryByUserId(book.getCreateUserid());
        if (book == null || users == null)
            return null;

        //1待支付,2已支付,3待入住,4已入住,5已消费,6支付超时,7已取消,8已退单,9已退款,10退款中
        int status = Func.parseInt(book.getOrderStatus());
        if (status == PayEnum.待支付.getNum()) {
            book.setOrderStatus(Func.parseStr(PayEnum.已取消.getNum())); // 如果在1待支付情况，用户点击取消订单按钮，后台直接修改取消订单操作
            book.setUpdateTime(DateUtil.getFormatPaternDate(new Date()));
            bookService.updateBooking(book);

            // 用户在待支付状态下取消了订单时，写入数据操作
            bookinglogService.addBooklog("用户在待支付状态下,取消了订单", book);
//            返回优惠券
            List<HotelCouponStatus> list = hotelCoupomStatusService.getBookingId(book.getId() + "");
            if (list != null && list.size() > 0) {
                hotelCoupomStatusService.restitution(list);
            }
            Message.send(users.getOpenid(), book.getHotelName(), book.getOrderStatus(), book.getOrderStartTime(), book.getOrderEndTime(), book.getHouseName());
            jsonObject.put(B.code, ResultStatusCode.OK.getStatus());
            jsonObject.put(B.message, ResultStatusCode.OK.getMsg());
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        } else if (status == PayEnum.已支付.getNum() || status == PayEnum.待入住.getNum()) {
            book.setOrderStatus(Func.parseStr(PayEnum.退款中.getNum())); // 如果在2已支付,3待入住 情况，商家点击取消订单按钮，后台先修改状态为退款中，然后走退款流程
            book.setRemake(Func.parseStr(PayEnum.已退单.getPayStatus()));
            List<HotelCouponStatus> list = hotelCoupomStatusService.getBookingId(book.getId() + "");
            if (list != null && list.size() > 0) {
                hotelCoupomStatusService.restitution(list);
            }
            Message.send(users.getOpenid(), book.getHotelName(), book.getOrderStatus(), book.getOrderStartTime(), book.getOrderEndTime(), book.getHouseName());
        } else if (status == PayEnum.已入住.getNum()) {
            book.setOrderStatus(Func.parseStr(PayEnum.退款中.getNum())); // 如果在2已支付,3待入住 情况，商家点击取消订单按钮，后台先修改状态为退款中，然后走退款流程
            book.setRemake(Func.parseStr(PayEnum.已退款.getPayStatus()));
            List<HotelCouponStatus> list = hotelCoupomStatusService.getBookingId(book.getId() + "");
            if (list != null && list.size() > 0) {
                hotelCoupomStatusService.restitution(list);
            }
            Message.send(users.getOpenid(), book.getHotelName(), book.getOrderStatus(), book.getOrderStartTime(), book.getOrderEndTime(), book.getHouseName());
        }

        if (book.getPayAccount() > 0) {
            // 注明如果支付金额大于0，则需要退款: （标识走退款操作）
            book.setRefundWay(OrderEnum.微信退款.toString());
        }
        jsonObject = refundMethod(book, users.getOpenid());
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }


    /**
     * bookingId 订单id
     * open_id
     * 取消订单功能： 用户点击
     * //1待支付,2已支付,3待入住,4已入住,5已消费,6支付超时,7已取消,8已退单,9已退款,10退款中
     *
     * @return
     */
    public String cancelBooking() throws Exception {
        JSONObject jsonObject = new JSONObject();
        if (Func.checkNull(this.bookingId)) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, "未传入bookingId");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        // 取消订单，修改订单的支付状态
        Booking book = bookService.getById(Func.parseInt(bookingId));
        if (book == null) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, "未获取到订单信息，请重新查询");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        // 查询用户信息
        Users users = userService.queryByUserId(book.getCreateUserid());
        if (users == null) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, "未查询到当前用户数据users,请先授权");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //是否能取消订单（1是 2否）
        if (Func.parseInt(book.getHotelIsCanorder()) == 2) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, "商家设置不可取消订单，请联系商家");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //1待支付,2已支付,3待入住,4已入住,5已消费,6支付超时,7已取消,8已退单,9已退款,10退款中
        int status = Func.parseInt(book.getOrderStatus());
        if (status == PayEnum.待支付.getNum() || status == PayEnum.支付超时.getNum()) {
            book.setOrderStatus(Func.parseStr(PayEnum.已取消.getNum())); // 如果在1待支付情况，用户点击取消订单按钮，后台直接修改取消订单操作
            book.setUpdateTime(DateUtil.getFormatPaternDate(new Date()));
            book.setRemake(Func.parseStr(PayEnum.已取消.getPayStatus()));
            int i = bookService.updateBooking(book);
//            返还优惠券
            List<HotelCouponStatus> list = hotelCoupomStatusService.getBookingId(book.getId() + "");
            if (list != null && list.size() > 0) {
                hotelCoupomStatusService.restitution(list);
            }

            jsonObject.put(B.code, ResultStatusCode.OK.getStatus());
            jsonObject.put(B.message, "已取消");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        if (status == PayEnum.已入住.getNum()) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, "已入住，请前往前台办理退款");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        if (status == PayEnum.已消费.getNum() || status == PayEnum.已取消.getNum() || status == PayEnum.已退单.getNum() || status == PayEnum.已退款.getNum()) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, "订单已完成，不可进行操作");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        if (status == PayEnum.退款中.getNum()) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, "退款中，请勿重复操作");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        // 退款操作
        book.setRemake(Func.parseStr(PayEnum.已取消.getPayStatus()));
        book.setRefundWay(OrderEnum.微信退款.toString());
        jsonObject = refundMethod(book, users.getOpenid());
        jsonObject.put(B.data, book);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    /**
     * 退款方法
     *
     * @param book
     * @param open_id
     * @return
     * @throws Exception
     */
    public JSONObject refundMethod(Booking book, String open_id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        if (book == null || Func.checkNull(open_id)) {
            jsonObject.put("code", 400);
            jsonObject.put("message", "未传入book和open_id数据---refundMethod");
            return jsonObject;
        }
        // 进行判断如果订单是退款中，并且标识字段微信退款，则进入退款流程
        String ip = WeiXinUtil.ip;
        double money = book.getPayAccount();
        int a = (int) (money * 100);
        WechatUnifiedOrder w = new WechatUnifiedOrder();
        w.setAppid(WeiXinUtil.appid_c);
        w.setAttach("chuanghai");
        w.setBody("chuanghai");
        w.setMch_id(WeiXinUtil.account);
        w.setNonce_str(PayWxUtil.getNonceStr());// 随机支付串
        w.setNotify_url(WeiXinUtil.ip_h + "/abkquery_refund.action");// 支付结果回调地址
        w.setOpenid(open_id);
        w.setOut_trade_no(book.getOrderNum());
        String refund_order = WxUtil.mchOrderNo();
        w.setOut_refund_no(refund_order);   // 退款单号
        w.setSpbill_create_ip(ip);
        w.setTotal_fee(a);
        w.setRefund_fee(a);   // 退款金额
        w.setTrade_type("JSAPI");
        SortedMap<String, String> params = new TreeMap<>();
        params.put("appid", w.getAppid());
        params.put("mch_id", w.getMch_id());
        params.put("nonce_str", w.getNonce_str());
        params.put("notify_url", w.getNotify_url());
        params.put("out_refund_no", w.getOut_refund_no());   // 退款单号
        params.put("out_trade_no", w.getOut_trade_no());
        params.put("refund_fee", w.getRefund_fee() + "");  // 退款金额
        params.put("total_fee", w.getTotal_fee() + "");

        w.setSign(PayWxUtil.getSign(params, WeiXinUtil.key));
        params.put("sign", w.getSign());
        //String retXml = JaxbUtil.getRequestXml(params);
        String xml = "<xml>" +
                "<appid>" + w.getAppid() + "</appid>" +
                "<mch_id>" + w.getMch_id() + "</mch_id>" +
                "<nonce_str>" + w.getNonce_str() + "</nonce_str>" +
                "<notify_url>" + w.getNotify_url() + "</notify_url>" +
                "<out_refund_no>" + w.getOut_refund_no() + "</out_refund_no>" +
                "<out_trade_no>" + w.getOut_trade_no() + "</out_trade_no>" +
                "<refund_fee>" + w.getRefund_fee() + "" + "</refund_fee>" +
                "<total_fee>" + w.getTotal_fee() + "" + "</total_fee>" +
                "<sign>" + w.getSign() + "</sign>" +
                "</xml>";
        //String msg = HttpsClient.sendPost2("https://api.mch.weixin.qq.com/secapi/pay/refund", retXml);
        String msg = HttpUtils.post2("https://api.mch.weixin.qq.com/secapi/pay/refund", xml);
        if (msg.indexOf("FAIL") > -1) {
            jsonObject.put("code", 507);
            jsonObject.put("message", "退款失败");
            ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        // 设置订单状态为退款中
        book.setOrderStatus(Func.parseStr(PayEnum.退款中.getNum()));
        book.setUpdateTime(DateUtil.parseDateToStr(new Date(), DateUtil.Time_Formatter_Second));
        bookService.updateBooking(book);  // 退款中
        // 用户在待支付状态下取消了订单时，写入数据操作
        bookinglogService.addBooklog("用户在取消了订单，正进入退款流程", book);
        jsonObject.put("code", 200);
        jsonObject.put("message", "申请已提交，请稍候查询");
        return jsonObject;
    }


//    /**
//     * open_id
//     * bookingId
//     * 微信退款功能
//     */
//    public String refundBooking() throws Exception {
//        JSONObject resultJson = new JSONObject();
//        if (Func.checkNull(this.open_id) || Func.checkNull(this.bookingId)) {
//            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
//            resultJson.put(B.message,  "未传入open_id和bookingId");
//            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
//            return null;
//        }
//
//        Users users = userService.queryByOpenid(open_id); // 用户信息
//        Booking booking = bookService.getById(Func.parseInt(bookingId)); // 订单信息
//        if (users == null || booking == null) {
//            resultJson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
//            resultJson.put(B.message, "未查询到当前用户数据users,请先授权");
//            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
//            return null;
//        }
//
//        String ip = WeiXinUtil.ip;
//        double money = booking.getPayAccount();
//        int a = (int) (money * 100);
//        WechatUnifiedOrder w = new WechatUnifiedOrder();
//        w.setAppid(WeiXinUtil.appid_c);
//        w.setAttach("chuanghai");
//        w.setBody("chuanghai");
//        w.setMch_id(WeiXinUtil.account);
//        w.setNonce_str(PayWxUtil.getNonceStr());// 随机支付串
//        w.setNotify_url(WeiXinUtil.ip_h + "/abkquery_refund.action");// 支付结果回调地址
//        w.setOpenid(open_id);
//        w.setOut_trade_no(booking.getOrderNum());
//        String refund_order = WxUtil.mchOrderNo();
//        w.setOut_refund_no(refund_order);   // 退款单号
//        w.setSpbill_create_ip(ip);
//        w.setTotal_fee(a);
//        w.setRefund_fee(a);   // 退款金额
//        w.setTrade_type("JSAPI");
//        SortedMap<String, String> params = new TreeMap<>();
//        params.put("appid", w.getAppid());
//        params.put("mch_id", w.getMch_id());
//        params.put("nonce_str", w.getNonce_str());
//        params.put("notify_url", w.getNotify_url());
//        params.put("out_refund_no", w.getOut_refund_no());   // 退款单号
//        params.put("out_trade_no", w.getOut_trade_no());
//        params.put("refund_fee",w.getRefund_fee()+"");  // 退款金额
//        params.put("total_fee", w.getTotal_fee() + "");
//
//        w.setSign(PayWxUtil.getSign(params, WeiXinUtil.key));
//        params.put("sign", w.getSign());
//        //String retXml = JaxbUtil.getRequestXml(params);
//        String xml = "<xml>" +
//                "<appid>" + w.getAppid() + "</appid>" +
//                "<mch_id>" + w.getMch_id() + "</mch_id>" +
//                "<nonce_str>" + w.getNonce_str() + "</nonce_str>" +
//                "<notify_url>" + w.getNotify_url() + "</notify_url>" +
//                "<out_refund_no>" + w.getOut_refund_no() + "</out_refund_no>" +
//                "<out_trade_no>" + w.getOut_trade_no() + "</out_trade_no>"	+
//                "<refund_fee>" + w.getRefund_fee()+"" + "</refund_fee>" +
//                "<total_fee>" + w.getTotal_fee() + "" + "</total_fee>" +
//                "<sign>" + w.getSign() + "</sign>"	+
//                "</xml>";
//        //String msg = HttpsClient.sendPost2("https://api.mch.weixin.qq.com/secapi/pay/refund", retXml);
//        String msg = HttpUtils.post2("https://api.mch.weixin.qq.com/secapi/pay/refund", xml);
//        if (msg.indexOf("FAIL") > -1) {
//            resultJson.put("code", 507);
//            resultJson.put("message", "退款失败");
//            ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
//            return null;
//        }
//
//        // 设置订单状态为退款中
//        booking.setOrderStatus(Func.parseStr(PayEnum.TEN.getNum()));
//        booking.setUpdateTime(DateUtil.parseDateToStr(new Date(),DateUtil.Time_Formatter_Second));
//        bookService.updateBooking(booking);  // 退款中
//
//        resultJson.put("code", 200);
//        resultJson.put("message", "退款申请已提交，请稍候查询");
//        ResUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
//        return null;
//    }

    /* 退款回调 */
    public String query_refund() throws Exception {

        // 查询本地数据库中，正在退款中
        StringBuffer strSqlBook = new StringBuffer();
        strSqlBook.append(" and order_status = '").append(PayEnum.退款中.getNum()).append("' ");
        List<Booking> booking = bookService.queryList(strSqlBook.toString());
        if (booking == null) {
            return null;
        }
        WechatUnifiedOrder w = new WechatUnifiedOrder();
        Map<String, String> params = new HashMap<String, String>();
        Booking book = new Booking();
        for (int i = 0; i < booking.size(); i++) {
            if (booking.get(i) == null)
                continue;

            book = booking.get(i);
            w = new WechatUnifiedOrder();
            w.setAppid(WeiXinUtil.appid_c);
            w.setAttach("chuanghai");
            w.setBody("chuanghai");
            w.setMch_id(WeiXinUtil.account);
            w.setNonce_str(PayWxUtil.getNonceStr());// 随机支付串
            w.setOut_trade_no(book.getOrderNum());
            w.setTrade_type("JSAPI");
            params = new HashMap<String, String>();
            params.put("appid", w.getAppid());
            params.put("mch_id", w.getMch_id());
            params.put("out_trade_no", w.getOut_trade_no());
            params.put("nonce_str", w.getNonce_str());
            w.setSign(PayWxUtil.getSign(params, WeiXinUtil.key));
            params.put("sign", w.getSign());
            String retXml = JaxbUtil.getRequestXml(params);
            String msg = HttpUtils.post("https://api.mch.weixin.qq.com/pay/refundquery", retXml);
            if (msg.indexOf("<refund_status_0><![CDATA[SUCCESS]]></refund_status_0>") > 0) {
                //退款的数据删除一下房态删除
                String sql = " and booking_id = " + book.getId();
                List<HouseNumberStatus> houseNumberStatuse = houseNumberStatusService.getList(sql);
                houseNumberStatusService.updateHouseNumberStatus(String.valueOf(book.getId()));

                // 退款成功，将数据写入本地数据库
                book.setRefundTime(DateUtil.parseDateToStr(new Date(), DateUtil.Time_Formatter_Second));
                book.setRefundAmount(book.getHouseTotalPrice());
                book.setUpdateTime(DateUtil.parseDateToStr(new Date(), DateUtil.Time_Formatter_Second));
                book.setOrderStatus(Func.parseStr(PayEnum.getKeyByValue(book.getRemake()))); // 将走微信前的标识，写入回调函数
                bookService.updateBooking(book);

                // 退款成功后，写入数据操作
                bookinglogService.addBooklog("用户在取消了订单，已退款成功,退款金额是" + book.getRefundAmount(), book);

                // 发送成功消息给商家和用户
                AdminManager adminManager = adminManagerService.getById(Func.parseInt(book.getHotelManagerId()));
                Users users = userService.queryByUserId(book.getCreateUserid());
                String sendMsg = book.getRemake();
                // 推给用户（需求确定，用户点取消退款以后[标识订单状态已取消]只发商家，不发用户。  商家点拒单以后[标识订单状态已退单]只发用户不发商家）
                int status = Func.parseInt(book.getOrderStatus());
                if (status == PayEnum.已退单.getNum()) {
                    Message.send(users.getOpenid(), book.getHotelName(), book.getOrderStatus(), book.getOrderStartTime(), book.getOrderEndTime(), book.getHouseName());
                }

                // 推给商家
                String live_end = book.getOrderStartTime().substring(0, 10) + "~" + book.getOrderEndTime().substring(0, 10);
                String hotelName = Func.checkNull(book.getHotelName()) ? book.getHotelName() : book.getHouseName();
                if (status == PayEnum.已取消.getNum()) {
                    Message2.send(adminManager.getOpenid(), book.getHotelType(), book.getHouseName(), live_end, book.getUserName(), hotelName, Func.parseStr(book.getId()));
                }
            }
        }
        String returnMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(returnMsg);
        out.flush();
        out.close();

        return null;
    }

    /**
     * bookingId 订单id
     * 删除订单功能(假删除)
     *
     * @return
     */
    public String delBooking() {
        if (Func.checkNull(getBookingId()))
            return null;

        JSONObject jsonObject = new JSONObject();

        String mess = bookService.delBooking(getBookingId());

        if (!Func.checkNull(mess)) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, mess);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        jsonObject.put(B.code, ResultStatusCode.OK.getStatus());
        jsonObject.put(B.message, ResultStatusCode.OK.getMsg());
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }


    /**
     * 验证是否有房间
     * houseId, 房型id
     * startTime, 开始时间
     * endTime 结束时间
     *
     * @return
     */
    public String varificationHouse() {
        JSONObject jsonObject = new JSONObject();
        if (Func.checkNull(houseId) || Func.checkNull(startTime) || Func.checkNull(endTime)) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, ResultStatusCode.BAD_REQUEST.getMsg());
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        String backMessage = appBookService.varificationHouse(houseId, startTime, endTime, houseOrderNumber);

        if (!Func.checkNull(backMessage)) {
            jsonObject.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put(B.message, backMessage);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        jsonObject.put(B.code, ResultStatusCode.OK.getStatus());
        jsonObject.put(B.message, OrderEnum.有空房.toString());
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }


    /**
     * open_id
     * bookingId
     * 用户支付操作
     *
     * @return
     */
    public String pay() {
        JSONObject resultjson = new JSONObject();
        if (Func.checkNull(this.open_id) || Func.checkNull(this.bookingId)) {
            resultjson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultjson.put(B.message, ResultStatusCode.BAD_REQUEST.getMsg());
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }

        Users users = userService.queryByOpenid(open_id); // 用户信息
        Booking booking = bookService.getById(Func.parseInt(bookingId)); // 订单信息
        if (users == null || booking == null || booking.getOrderStatus().equals(Func.parseStr(PayEnum.支付超时.getNum()))) {
            resultjson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultjson.put(B.message, ResultStatusCode.BAD_REQUEST.getMsg());
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }

        try {
            // 支付费用
            double totalPrice = booking.getHouseTotalPrice();
            int totalfee = Func.parseInt(totalPrice * 100);

            WechatUnifiedOrder w = new WechatUnifiedOrder();
            w.setAppid(WeiXinUtil.appid_c);
            w.setAttach("chuanghai");
            w.setBody("chuanghai");
            w.setMch_id(WeiXinUtil.account);
            w.setNonce_str(PayWxUtil.getNonceStr());// 随机支付串
            w.setNotify_url(WeiXinUtil.ip_h + "/abkpayResulet.action");// 支付结果回调地址
            w.setOpenid(this.open_id);
            String orderNo = booking.getOrderNum(); // 订单编号
            w.setOut_trade_no(orderNo);
            w.setSpbill_create_ip(WeiXinUtil.ip);
            w.setTotal_fee(totalfee);
            w.setTrade_type("JSAPI");
            Map<String, String> params = new HashMap<String, String>();
            params.put("attach", w.getAttach());
            params.put("appid", w.getAppid());
            params.put("mch_id", w.getMch_id());
            params.put("nonce_str", w.getNonce_str());
            params.put("body", w.getBody());
            params.put("out_trade_no", w.getOut_trade_no());
            params.put("total_fee", Func.parseStr(w.getTotal_fee()));
            params.put("spbill_create_ip", w.getSpbill_create_ip());
            params.put("notify_url", w.getNotify_url());
            params.put("trade_type", w.getTrade_type());
            params.put("openid", w.getOpenid());
            w.setSign(PayWxUtil.getSign(params, WeiXinUtil.key));
            params.put("sign", w.getSign());
            String retXml = JaxbUtil.getRequestXml(params);
            String msg = HttpUtils.post("https://api.mch.weixin.qq.com/pay/unifiedorder", retXml);
            System.out.println(msg);
            // 支付失败
            if (msg.indexOf("FAIL") > -1) {
                resultjson.put("code", "205");
                resultjson.put("message", "支付异常205");
                ResUtil.write(resultjson, ServletActionContext.getResponse());
                return null;
            }

            JaxbUtil requestBinder = new JaxbUtil(TongYiReturn.class, JaxbUtil.CollectionWrapper.class);
            TongYiReturn to = requestBinder.fromXml(msg);
            // 支付成功
            if (to.getReturn_code().equals("SUCCESS") && to.getResult_code().equals("SUCCESS")) {
                EndPay pay = new EndPay();
                pay.setAppId(WeiXinUtil.appid_c);
                pay.setSignType("MD5");
                pay.setTimeStamp(System.currentTimeMillis() / 1000 + "");
                pay.setPrepay_id(to.getPrepay_id());
                pay.setNonceStr(PayWxUtil.getNonceStr());
                Map<String, String> requestMap = new HashMap<String, String>();
                requestMap.put("appId", pay.getAppId());
                requestMap.put("timeStamp", pay.getTimeStamp());
                requestMap.put("nonceStr", pay.getNonceStr());
                requestMap.put("package", "prepay_id=" + pay.getPrepay_id());
                requestMap.put("signType", "MD5");
                pay.setPaySign(PayWxUtil.getSign(requestMap, WeiXinUtil.key));
                // 保存支付信息
                booking.setUpdateTime(DateUtil.getFormatPaternDate(new Date()));
                booking.setOrderStatus(Func.parseStr(PayEnum.待支付.getNum()));
                //booking.setPayAccount(0);
                booking.setPayWay(OrderEnum.微信支付.toString());
                bookService.updateBooking(booking);

                //用户开启支付，写入数据操作
                bookinglogService.addBooklog("用户点击订单，进行支付", booking);


                resultjson.put(B.code, ResultStatusCode.OK.getStatus());
                resultjson.put(B.message, "返回成功");
                resultjson.put(B.data, pay);
                ResponseUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            }
        } catch (Exception e) {
            resultjson.put(B.code, ResultStatusCode.BAD_REQUEST.getStatus());
            resultjson.put(B.message, e.getMessage());
            ResponseUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
        }
        return null;
    }

    /**
     * 支付成功后回调,推送消息给商家
     */
    public String payResulet() {
        System.out.println("进入支付回调====");
        JSONObject resultjson = new JSONObject();
        try {
            BufferedReader reader = null;// BufferedReader 字符输入流
            reader = request.getReader();
            String line = "";
            String xmlString = null;
            StringBuilder inputString = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            xmlString = inputString.toString();
            request.getReader().close();
            JaxbUtil requestBinder = new JaxbUtil(PayResult.class, PayResult.class);
            PayResult result = requestBinder.fromXml(xmlString);// Xml到Java，用fromXML()方法
            String order_num = result.getOut_trade_no();
            System.out.println("支付成功回调，订单号：" + order_num);
            Booking book = bookService.queryByOrder(order_num);
            // 支付成功
            if (result.getResult_code().equals("SUCCESS") && book != null && ("1").equals(book.getOrderStatus())) {

                // 保存支付信息
                book.setUpdateTime(DateUtil.getFormatPaternDate(new Date()));
                book.setOrderStatus(Func.parseStr(PayEnum.已支付.getNum()));
                book.setPayTime(DateUtil.getFormatPaternDate(new Date()));
                book.setPayWay(OrderEnum.微信支付.toString());
                // 进行业务判断，如果是商家设定了自动接单，则支付状态直接变为待入住  接单设置（1自动接单 2手动接单）
                //目前付完钱之后如果是设置的自动接单就进行自动接单
                if ("1".equals(book.getHotelIsOrder())) {
                    AtomicInteger n = new AtomicInteger();
                    String userId = book.getCreateUserid();
                    Users users = userService.queryByUserId(userId);
                    String mess = "您已成功订房，订单号：" + order_num;
                    Message.send(users.getOpenid(), book.getHotelName(), book.getOrderStatus(), book.getOrderStartTime(), book.getOrderEndTime(), book.getHouseName());

                    System.out.println("手动接单定时程序5");
                    List<HouseNumberStatus> list = new ArrayList<>();
                    //不可入住的房间
                    List<HouseNumber> houseNumbers = houseNumberService.queryHouseStatus(book);
                    //所有房间
                    List<HouseNumber> houseNumberList = houseNumberService.queryByHouseId(book.getHouseId());
                    AtomicInteger i = new AtomicInteger();
                    List<String> Ids = new ArrayList<>();
                    if (houseNumbers != null) {
                        houseNumberList.forEach(houseNumber -> {
                            //添加的房间不在不可添加的房间当中并且数量小于订房总数
                            if (!houseNumbers.contains(houseNumber) && 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();
                            }
                        });
                    }

                    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);
                    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(book.getId()));
                            houseNumberStatus.setSetDate(date.format(formatter));
                            houseNumberStatus.setStatus(5);//状态(0删除 1.正常 2.关房 3.脏房 4.净房 5.预定 6.入住)
                            list.add(houseNumberStatus);
                        }
                    }
                    int m = houseNumberStatusService.saveBatch(list);
                    if (m > 0) {
                        n.getAndIncrement();
                        // 自动接单，订单状态修改为待入住
                        book.setOrderStatus(Func.parseStr(PayEnum.待入住.getNum()));
                        book.setUpdateTime(UUIDUtil.getNewDate());
                    }
                }

                // 手动接单，发消息给商家
                AdminManager adminManager = adminManagerService.getById(Func.parseInt(book.getHotelManagerId()));
                String live_end = book.getOrderStartTime().substring(0, 10) + "~" + book.getOrderEndTime().substring(0, 10);
                String hotelName = book.getHotelName();
                if (Func.checkNull(book.getHotelName())) {
                    hotelName = book.getHouseName();
                }
                Message2.send(adminManager.getOpenid(), order_num, book.getHouseName(), live_end, book.getUserName(), hotelName, Func.parseStr(book.getId()));
                double totalPrice = book.getHouseTotalPrice();
                book.setPayAccount(totalPrice);
                int m = bookService.updateBooking(book);
                //用户支付，写入数据操作
                bookinglogService.addBooklog("用户支付成功", book);

                if (m > 0) {
                    String returnMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    HttpServletResponse response = ServletActionContext.getResponse();
                    response.setContentType("text/html;charset=utf-8");
                    PrintWriter out = response.getWriter();
                    out.println(returnMsg);
                    out.flush();
                    out.close(); // 发送成功消息给商家
                }
                return null;
            }
        } catch (Exception e) {
            resultjson.put("message", "支付失败");
            resultjson.put("code", 205);
            ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
            return null;
        }
        resultjson.put("message", "支付失败");
        resultjson.put("code", 205);
        ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
        return null;
    }


    public String getOpen_id() {
        return open_id;
    }

    public void setOpen_id(String open_id) {
        this.open_id = open_id;
    }
}
