package com.wteam.framework.modules.pay.serviceimpl.handler;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import com.egzosn.pay.common.api.PayMessageHandler;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayMessage;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import com.wteam.framework.common.enums.CardTypeEnum;
import com.wteam.framework.common.enums.OrderStatus;
import com.wteam.framework.common.enums.OrderStatusEnum;
import com.wteam.framework.common.enums.ResultCode;
import com.wteam.framework.common.exception.ServiceException;
import com.wteam.framework.modules.book.entity.Card;
import com.wteam.framework.modules.book.entity.OrderInfo;
import com.wteam.framework.modules.book.entity.Store;
import com.wteam.framework.modules.book.entity.Venue;
import com.wteam.framework.modules.book.entity.vo.TimeCodeVo;
import com.wteam.framework.modules.book.mapper.CardMapper;
import com.wteam.framework.modules.book.mapper.OrderInfoMapper;
import com.wteam.framework.modules.book.mapper.StoreMapper;
import com.wteam.framework.modules.book.mapper.VenueMapper;
import com.wteam.framework.modules.book.service.CardService;
import com.wteam.framework.modules.book.service.OrderInfoService;
import com.wteam.framework.modules.card.entity.CbCardAdmin;
import com.wteam.framework.modules.card.mapper.CardAdminMapper;
import com.wteam.framework.modules.hardware.ApiCallerUtil;
import com.wteam.framework.modules.hardware.QrCodeRegistrationUtil;
import com.wteam.framework.modules.user.entity.User;
import com.wteam.framework.modules.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;


@Slf4j
@Component
public class MyPayMessageHandler implements PayMessageHandler {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private CardService cardService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private CardAdminMapper cardAdminMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VenueMapper venueMapper;

    /**
     * 重写这个接口处理支付业务请求
     *
     * @param payMessage 支付消息
     * @param context    上下文，如果handler或interceptor之间有信息要传递，可以用这个
     * @param payService 支付服务
     * @throws PayErrorException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayOutMessage handle(PayMessage payMessage, Map context, PayService payService) throws PayErrorException {
        try {
            // 输入验证
            if (payMessage == null || payMessage.getPayMessage() == null) {
                throw new IllegalArgumentException("Invalid payMessage");
            }

            //TODO ：这里需要的是map集合里面的另外两个参数

            // 处理支付逻辑
            String outTradeNo = payMessage.getOutTradeNo(); // 获取交易订单号
            log.info("此时的支付订单号为{}", outTradeNo);

            Map<String, Object> message = payMessage.getPayMessage();
            // 获取transaction_id
            String transactionId = (String) message.get("transaction_id");
            log.info("此时的transactionId为：{}", transactionId);

            // 根据订单ID查询订单信息
            OrderInfo orderInfo = orderInfoMapper.selectById(outTradeNo);
            orderInfo.setTransactionId(transactionId);
            log.info("此时的order信息为{}", orderInfo);

//            //如果是超时的情况，单独考虑
//            Double overPrice = orderInfo.getOverPrice();
//            if (overPrice != null && overPrice > 0) {
//                // overPrice 大于 0 表示超时，需要处理超时情况
//                // 在这里可以执行超时处理的逻辑
//                //生成一个只能通过一次的二维码
//                // 获取当前日期
//                LocalDate currentDate = LocalDate.now();
//                //TODO ：这里的
//
//                String numbers = RandomUtil.randomNumbers(5);
//                // 格式化日期为字符串
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
//                String formattedDate = currentDate.format(formatter);
//                String data = "pxo_" + formattedDate + "_" + numbers + "_" + orderInfo.getId() + "_00";
//                log.info("此时生成的二维码为：{} ", data);
//
//                //更新数据库里面此时二维码信息
//                orderInfo.setQrCode(data);
//                orderInfo.setOrderState(String.valueOf(OrderStatusEnum.IN_USE));
//                orderInfoMapper.updateById(orderInfo);
//
//                // 注册二维码
//                // 接口地址和参数
//                String apiUrl = "https://xiaofeng.pankzone.com/api/openapi/reg_access_qcode.x";
//                String mac1 = "863569068849199";
//                String mac2 = "863569068848969";
//                String tk = ApiCallerUtil.callApi(mac1);
//                log.info("此时获取到的token为：{} ", tk);
//
//                // 拼接两个 MAC 地址，以逗号分隔
//                String macParam = mac1 + "_" + mac2;
//                log.info("此时拼接的macParam为：{}", macParam);
//
//                //调用hutool接口注册二维码信息
//                HttpResponse response = HttpRequest.post(apiUrl).form("mac", macParam).form("tk", tk)
//                        .form("qcodetxt", data)
//                        .form("enablecount", 1).execute();
//
//                //获取响应结果
//                String body = response.body();
//
//                // 处理返回结果
//                JSONObject json = new JSONObject(body);
//                int code = json.getInt("code");
//                log.info("此时的超时的code为：{}", code);
//                String qcodetxt = json.getStr("qcodetxt");
//                log.info("此时返回的qcodetxt为：{}", qcodetxt);
//                String desc = json.getStr("desc");
//                log.info("此时返回的desc为：{}", desc);
//
//                //对响应结果处理
//                if (code != 0) {
//                    throw new ServiceException("硬件回调url设置接口异常！");
//                }
//                log.info("此时接口响应数据为：{} (不要记录敏感信息在日志中)", body);
//            }

            //这里根据订单的类型生成不同的二维码注销
            String orderType = orderInfo.getOrderType();

            /**
             * 租场订单-->生成的二维码有时间限制，前30后30，进出次数不限制
             * 门票订单-->生成的二维码没有时间限制，任何时候来都可以，但是进出限制2次，一出一进就结束
             * 计时订单-->生成的二维码没有时间限制，也是先支付一个小时的钱，支付成功后修改订单状态！
             * 月卡订单-->生成的二维码截至时间为月卡结束时间，进出没有限制
             * 储值卡订单-->直接完成支付业务逻辑即可
             */

            switch (orderType) {
                case "RENTAL":
                    // 处理租场订单类型的支付逻辑
                    return RentalOrder(orderInfo);
                case "TICKET":
                    // 处理门票订单类型的支付逻辑
                    return TicketOrder(orderInfo);
                case "TIMER":
                    // 处理计时订单类型的支付逻辑
                    return TimerOrder(orderInfo);
                case "MONTHLY":
                    // 处理月卡订单类型的支付逻辑
                    return MonthlyOrder(orderInfo);
                case "STORED_VALUE":
                    // 合并储值卡订单和散客储值卡订单的支付逻辑
                    // 处理储值卡订单类型的支付逻辑
                    return CardOrder(orderInfo);
                case "PERSON_CARD":
                    // 处理散客储值卡订单类型的支付逻辑
                    return PersonCardOrder(orderInfo);
                default:
                    // 处理未知订单类型的情况
                    break;
            }
        } catch (Exception e) {
            log.info("此时的异常为：{}", e.getMessage());
        }
        return PayOutMessage.TEXT().content("fail").build();
    }

    //TODO：散客储值卡购买完成并没有获取到
    private PayOutMessage PersonCardOrder(OrderInfo orderInfo) {

        // 修改订单支付方式和支付状态
        orderInfo.setPaymentMethods("WECHAT");
        orderInfo.setOrderState(String.valueOf(OrderStatus.PAYMENT_SUCCESSFUL));
        orderInfoMapper.updateById(orderInfo);

        // 格式化日期为字符串
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);

        // 微信购买卡之后支付回调信息
        Integer cardId = orderInfo.getCardId();
        log.info("此时卡id为{}", cardId);

        /**
         * 可能是储值卡充值也可能是购买储值卡
         */
        // 储值卡充值
        Card card = cardMapper.selectById(cardId);
        log.info("此时卡信息为{}", card);

        String userId = null;

        if (card != null) {
            userId = card.getUserId();
            log.info("此时的useId为：{}", userId);
            // 这种情况就证明此时该用户进行的是储值卡充值的操作
            Double orderPrice = orderInfo.getOrderPrice();
            Double currentBalance = card.getCurrentBalance();
            double v = orderPrice + currentBalance;
            log.info("此时的储值卡充值之后的余额为：{}", v);
            card.setCurrentBalance(v);
            cardMapper.updateById(card);
            // 给用户加上累计消费
            // addUserTotalConsumption(orderInfo);
            return PayOutMessage.TEXT().content("success").build();
        }

        // 购买储值卡
        CbCardAdmin cbCardAdmin = cardAdminMapper.selectById(cardId);

        if (cbCardAdmin != null) {
            Card cardUser = new Card();

            // 获取余额
            Integer faceValue = cbCardAdmin.getFaceValue();
            cardUser.setCreateTime(new Date());
            cardUser.setCardName(cbCardAdmin.getCardName());
            cardUser.setCardType(cbCardAdmin.getCardType());
            Integer days = cbCardAdmin.getDays();
            cardUser.setDays(days);
            cardUser.setStartDate(formattedDate);

            // 将天数添加到日期
            LocalDate newDate = currentDate.plusDays(days);

            // 将新日期格式化为字符串
            String newFormattedDate = newDate.format(formatter);
            cardUser.setEndDate(newFormattedDate);
            cardUser.setFaceValue(faceValue);
            cardUser.setBonusAmount(cbCardAdmin.getBonusAmount());
            cardUser.setCurrentBalance(Double.valueOf(faceValue + cbCardAdmin.getBonusAmount()));
            cardUser.setUserId(orderInfo.getUserId());
            cardUser.setStoreId(9376L);
            cardUser.setDiscountValue(cbCardAdmin.getDiscountValue());
            cardUser.setOrderId(orderInfo.getId());
            log.info("此时的cardUser信息为：{}", cardUser);
            // 给用户加上累计消费
            // addUserTotalConsumption(orderInfo);
            boolean save = cardService.save(cardUser);

            Integer cardUserId = cardUser.getId();
            orderInfo.setCardId(cardUserId);
            log.info("此时的卡id为：{}", cardUserId);
            orderInfoMapper.updateById(orderInfo);

            if (save) {
                return PayOutMessage.TEXT().content("success").build();
            }
        }

        return PayOutMessage.TEXT().content("fail").build();

    }


    /**
     * 购买储值卡之后的支付回调
     *
     * @param orderInfo
     * @return
     */

//TODO ：储值卡不能重复购买 购买前需要先行校验
    private PayOutMessage CardOrder(OrderInfo orderInfo) {
        //修改订单支付方式和支付状态
        orderInfo.setPaymentMethods("WECHAT");
        orderInfo.setOrderState(String.valueOf(OrderStatus.PAYMENT_SUCCESSFUL));
        orderInfoMapper.updateById(orderInfo);

        // 格式化日期为字符串
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);

        //微信购买卡之后支付回调信息
        Integer cardId = orderInfo.getCardId();
        log.info("此时卡id为{}", cardId);

        /**
         * 可能是储值卡充值 也可能是购买储值卡
         */
        //储值卡充值
        Card card = cardMapper.selectById(cardId);
        log.info("此时卡信息为{}", card);
        String userId = null;
        if (card != null) {
            userId = card.getUserId();
            log.info("此时的useId为：{}", userId);
            // 这种情况就证明此时该用户进行的是储值卡充值的操作
            Double orderPrice = orderInfo.getOrderPrice();
            Double currentBalance = card.getCurrentBalance();
            double v = orderPrice + currentBalance;
            log.info("此时的储值卡充值之后的余额为：{}", v);
            card.setCurrentBalance(v);
            cardMapper.updateById(card);
            //给用户加上累计消费
//                addUserTotalConsumption(orderInfo);
            return PayOutMessage.TEXT().content("success").build();
        }

        // 购买储值卡
        CbCardAdmin cbCardAdmin = cardAdminMapper.selectById(cardId);
        Card cardUser = new Card();

        //获取余额
        Integer faceValue = cbCardAdmin.getFaceValue();
        cardUser.setCreateTime(new Date());
        cardUser.setCardName(cbCardAdmin.getCardName());
        cardUser.setCardType(cbCardAdmin.getCardType());
        cardUser.setUserId(orderInfo.getUserId());
        Integer days = cbCardAdmin.getDays();
        cardUser.setDays(days);
        cardUser.setStartDate(formattedDate);

        // 将天数添加到日期
        LocalDate newDate = currentDate.plusDays(days);

        // 将新日期格式化为字符串
        String newFormattedDate = newDate.format(formatter);
        cardUser.setEndDate(newFormattedDate);
        cardUser.setFaceValue(faceValue);
        cardUser.setBonusAmount(cbCardAdmin.getBonusAmount());
        cardUser.setCurrentBalance(Double.valueOf(faceValue + cbCardAdmin.getBonusAmount()));
        cardUser.setUserId(orderInfo.getUserId());
        cardUser.setStoreId(9376L);
        cardUser.setDiscountValue(cbCardAdmin.getDiscountValue());
        cardUser.setOrderId(orderInfo.getId());
        log.info("此时的cardUser信息为：{}", cardUser);
        //给用户加上累计消费
//        addUserTotalConsumption(orderInfo);
        boolean save = cardService.save(cardUser);

        Integer cardUserId = cardUser.getId();
        orderInfo.setCardId(cardUserId);
        log.info("此时的卡id为：{}", cardUserId);
        orderInfoMapper.updateById(orderInfo);

        if (save) {
            return PayOutMessage.TEXT()

                    .content("success")

                    .build();
        }
        return PayOutMessage.TEXT().

                content("fail").

                build();

    }

    //TODO:月卡无法进入

    private PayOutMessage MonthlyOrder(OrderInfo orderInfo) throws ParseException {
        // 修改订单状态为已支付
        orderInfo.setOrderState(String.valueOf(OrderStatus.PAYMENT_SUCCESSFUL));
        log.info("此时的OrderState信息为{}", orderInfo.getOrderState());

        // 修改订单支付方式
        orderInfo.setPaymentMethods("WECHAT");
        log.info("此时的PaymentMethods信息为{}", orderInfo.getPaymentMethods());

        orderInfoMapper.updateById(orderInfo);

//        //给用户加上累计消费
//        addUserTotalConsumption(orderInfo);

        // 获得
        String id = orderInfo.getId();
        log.info("此时的orderId为：{}", id);

        //获取卡信息
        Integer cardId = orderInfo.getCardId();
        log.info("此时的卡id为:{}", cardId);
        CbCardAdmin card = cardAdminMapper.selectById(cardId);
        log.info("此时的基础卡信息为:{}", card);


        // 格式化日期为字符串
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);

        //创建卡信息
        Card cardUser = new Card();
        cardUser.setCreateTime(new Date());
        cardUser.setCardName(card.getCardName());
        cardUser.setCardType(card.getCardType());
        Integer days = card.getDays();
        cardUser.setDays(days);
        cardUser.setStartDate(formattedDate);

        // 将天数添加到日期
        LocalDate newDate = currentDate.plusDays(days);

        // 将新日期格式化为字符串
        String newFormattedDate = newDate.format(formatter);
        cardUser.setEndDate(newFormattedDate);
        cardUser.setUserId(orderInfo.getUserId());
        cardUser.setStoreId(9376L);
        cardUser.setOrderId(id);
        log.info("此时的cardUser信息为：{}", cardUser);
        cardService.save(cardUser);

        //将购买的卡存入对应的订单信息
        Integer cardUserId = cardUser.getId();
        orderInfo.setCardId(cardUserId);
        log.info("此时的卡id为：{}", cardUserId);
        orderInfoMapper.updateById(orderInfo);


//        // 获取当前日期
//        LocalDate currentDate1 = LocalDate.now();
//        log.info("此时的时间为{}", currentDate1);

        String numbers = RandomUtil.randomNumbers(5);


//        // 格式化日期为字符串
//        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
//        String formattedDate1 = currentDate1.format(formatter1);
//        log.info("此时格式化的日期为:{}", formattedDate);

        String data = "pxo_" + formattedDate + "_" + numbers + "_" + id + "_00";
        log.info("此时生成的二维码为：{} ", data);
        orderInfo.setQrCode(data);
        orderInfoMapper.updateById(orderInfo);

//        此时的结束时间为卡二维码截至时间
        // 创建 SimpleDateFormat 对象，指定日期格式
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        // 将日期字符串解析为 Date 对象
//        Date date = sdf.parse(newFormattedDate);
//        log.info("此时的date为:{}", date);
//
//        // 将 Date 对象转化为秒级时间戳
//        // 除以1000以获取秒级时间戳
//        long EdTimestamp = date.getTime() / 1000;
//
//        // 将时间戳转换为Date对象
//        Date endTime = new Date(EdTimestamp * 1000);
//        log.info("此时的有效截至时间为：{}", endTime);
//
//        // 获取当前时间的时间戳（秒级） 这是的时间戳为月卡的开始有效时间戳
//        long StTimestamp = System.currentTimeMillis() / 1000;
//        Date StTime = new Date(StTimestamp * 1000);
//        log.info("此时的有效开始时间为：{}", StTime);

//        // 注册二维码
//        // 接口地址和参数
//        String apiUrl = "https://xiaofeng.pankzone.com/api/openapi/reg_access_qcode.x";
//        String mac1 = "863569068849199";
//        String mac2 = "863569068848969";
//        String tk = ApiCallerUtil.callApi(mac2);
//        log.info("此时获取到的token为：{} ", tk);
//
//        String macParam = mac1 + "_" + mac2;
//        log.info("此时拼接的macParam为：{}", macParam);
//
//        //使用hutool调用接口
//        HttpResponse response = HttpRequest.post(apiUrl)
//                .form("mac", macParam)
//                .form("tk", tk)
//                .form("qcodetxt", data)
////                .form("starttime", StTimestamp)
////                .form("enabletime", EdTimestamp)
//                .form("enablecount", 100)
//                .execute();
//
//        //获取响应结果
//        String body = response.body();
//        // 处理返回结果
//        JSONObject json = new JSONObject(body);
//        int code = json.getInt("code");
//        log.info("此时返回的code为：{}", code);
//        String qcodetxt = json.getStr("qcodetxt");
//        log.info("此时返回的qcodetxt为：{}", qcodetxt);
//        String desc = json.getStr("desc");
//        log.info("此时返回的desc为：{}", desc);
//
//        //对响应结果处理
//        if (code != 0) {
//            throw new ServiceException("硬件回调url设置接口异常！");
//        }
//        log.info("此时接口响应数据为：{} (不要记录敏感信息在日志中)", body);
//        // 返回适当的PayOutMessage
//        return PayOutMessage.TEXT().content("success").build();
        Boolean b = QrCodeRegistrationUtil.registerMonthQrCode(data);
        if (b) {
            return PayOutMessage.TEXT().content("success").build();
        }
        return PayOutMessage.TEXT().content("fail").build();
    }


    private PayOutMessage TimerOrder(OrderInfo orderInfo) {
        // 要分为超时的支付情况和正常的支付情况
        // 获取此时的超时金额
        Double overPrice = orderInfo.getOverPrice();

        if (overPrice != null) {

            orderInfo.setOrderState(String.valueOf(OrderStatusEnum.IN_USE));
            return PayOutMessage.TEXT().content("success").build();

        }

        // 正常的支付情况
        orderInfo.setOrderState(String.valueOf(OrderStatusEnum.IN_USE));
        log.info("此时的OrderState信息为{}", orderInfo.getOrderState());

        // 修改订单支付方式
        orderInfo.setPaymentMethods("WECHAT");
        log.info("此时的PaymentMethods信息为{}", orderInfo.getPaymentMethods());

        // 获取当前日期
        LocalDate currentDate1 = LocalDate.now();
        // 格式化日期为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate1.format(formatter);

        //生成一个随机数字
        String numbers = RandomUtil.randomNumbers(5);

        String data = "pxo_" + formattedDate + "_" + numbers + "_" + orderInfo.getId() + "_00";

        // 获取当前时间戳
        long currentTime = System.currentTimeMillis() / 1000;

        // 获取60秒之后的时间戳
        long sixtySecondsLater = currentTime + 60;


        String apiUrl = "https://xiaofeng.pankzone.com/api/openapi/reg_access_qcode.x";
        String mac1 = "863569068849199";
        String mac2 = "863569068848969";
        String tk = ApiCallerUtil.callApi(mac1);
        log.info("此时获取到的token为：{} ", tk);

        String macParam = mac1 + "_" + mac2;
        log.info("此时拼接的macParam为：{}", macParam);

        HttpResponse response = HttpRequest.post(apiUrl)
                .form("mac", macParam)
                .form("tk", tk)
                .form("qcodetxt", data)
                .form("starttime", currentTime)
                .form("enabletime", sixtySecondsLater)
                .form("enablecount", 2)
                .execute();

        String body = response.body();
        JSONObject json = new JSONObject(body);
        int code = json.getInt("code");
        log.info("此时返回的code为：{}", code);
        String qcodetxt = json.getStr("qcodetxt");
        log.info("此时返回的qcodetxt为：{}", qcodetxt);
        String desc = json.getStr("desc");
        log.info("此时返回的desc为：{}", desc);

        if (code != 0 && code != 4) {
            throw new ServiceException("硬件回调url设置接口异常！");
        }

        log.info("此时接口响应数据为：{} (不要记录敏感信息在日志中)", body);


        orderInfo.setQrCode(data);


        int i = orderInfoMapper.updateById(orderInfo);

//        //设置进出时间
//        orderInfo.setStartTime(new Date());

//        //格式转化一下
//        String id = orderInfo.getId();
//        log.info("此时获得的订单id为：{}：", id);

//        int i = orderInfoMapper.updateById(orderInfo);

        if (i > 0) {
            return PayOutMessage.TEXT().content("success").build();
        }
        // 返回适当的PayOutMessage
        return PayOutMessage.TEXT().

                content("fail").

                build();

    }


    private PayOutMessage TicketOrder(OrderInfo orderInfo) {
        // 修改订单状态为已支付
        orderInfo.setOrderState(String.valueOf(OrderStatusEnum.WAITING_TO_USE));
        log.info("此时的OrderState信息为{}", orderInfo.getOrderState());

        // 修改订单支付方式
        orderInfo.setPaymentMethods("WECHAT");
        log.info("此时的PaymentMethods信息为{}", orderInfo.getPaymentMethods());

        orderInfoMapper.updateById(orderInfo);


        //给用户加上累计消费
//        addUserTotalConsumption(orderInfo);

        //得到此时的cardId
        Integer cardId = orderInfo.getCardId();
        CbCardAdmin cbCardAdmin = cardAdminMapper.selectById(cardId);
        Integer days = cbCardAdmin.getDays();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        //格式转化一下
        String id = orderInfo.getId();
        log.info("此时得到的订单id为：{}：", id);

        //创建卡信息
        Card cardUser = new Card();
        cardUser.setCreateTime(new Date());
        cardUser.setCardName("篮球次卡");
        cardUser.setCardType(String.valueOf(CardTypeEnum.TICKET));
        cardUser.setDays(days);
        cardUser.setUserId(orderInfo.getUserId());
        cardUser.setStoreId(9376L);
        cardUser.setDiscountValue(null);
        cardUser.setTimes(cbCardAdmin.getTimes());
        cardUser.setOrderId(id);
        log.info("此时的card信息为：{}", cardUser);

        //存入数据库
        cardService.save(cardUser);

        //修改订单表里面的对应的卡id
        Integer cardUserId = cardUser.getId();
        orderInfo.setCardId(cardUserId);
        orderInfoMapper.updateById(orderInfo);
        log.info("此时的卡id为：{}", cardUserId);

        //生成5位随机数字
        String numbers = RandomUtil.randomNumbers(5);

        // 格式化日期为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);
        String data = "pxo_" + formattedDate + "_" + numbers + "_" + id + "_00";
        log.info("此时生成的二维码为：{} ", data);

        // 二维码保存入数据库
        orderInfo.setQrCode(data);
        log.info("此时的orderInfo为:{}", orderInfo);
        orderInfoService.updateById(orderInfo);
        Boolean b = QrCodeRegistrationUtil.registerTicketQrCode(data);

        if (b) {
            // 返回适当的PayOutMessage
            return PayOutMessage.TEXT().content("success").build();
        }
        // 返回适当的PayOutMessage
        return PayOutMessage.TEXT().content("fail").build();
    }

    public void addUserTotalConsumption(OrderInfo orderInfo) {
        String userId = orderInfo.getUserId();
        User user = userMapper.selectById(userId);

        if (user != null) {
            double newCredit = user.getCredit() + orderInfo.getOrderPrice() + orderInfo.getOverPrice();
            log.info("此时的消费为：{}", newCredit);
            user.setCredit(newCredit);
            userMapper.updateById(user);
        } else {
            log.error("用户不存在，无法更新消费信息。");
            // 可以抛出异常或记录其他错误信息，具体根据需求而定。
        }
    }


    private PayOutMessage RentalOrder(OrderInfo orderInfo) {
        //这里也要区分是否是超时支付超时的情况
        //如果是补款超时金额的情况 只需要将其订单状态改为已完成订单即可
        if (orderInfo.getOverPrice() != null) {
            orderInfo.setOrderState(String.valueOf(OrderStatusEnum.USED));
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            //生成随机5位数字
            String numbers1 = RandomUtil.randomNumbers(5);
            String numbers2 = RandomUtil.randomNumbers(5);
            // 格式化日期为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            String formattedDate = currentDate.format(formatter);
            String data = "pxo_" + formattedDate + "_" + numbers1 + "_" + numbers2 + "_e0";
            String qrCode = QrCodeRegistrationUtil.registerOneQrCode(data);
            log.info("生成的一次核销的二维码为：{}", qrCode);
            orderInfo.setQrCode(qrCode);
            orderInfoMapper.updateById(orderInfo);

            // 返回适当的PayOutMessage
            return PayOutMessage.TEXT().content("success").build();
        }

        // 修改订单状态为已支付
        orderInfo.setOrderState(String.valueOf(OrderStatusEnum.WAITING_TO_USE));
        log.info("此时的OrderState信息为{}", orderInfo.getOrderState());

        // 修改订单支付方式
        orderInfo.setPaymentMethods("WECHAT");
        log.info("此时的PaymentMethods信息为{}", orderInfo.getPaymentMethods());

        Long venueId = orderInfo.getVenueId();
        Venue venue = venueMapper.selectById(venueId);
        Integer realTime = Integer.valueOf(venue.getShareFrequency());
        realTime = realTime * 2;
        log.info("此时的核销次数为：{}", realTime);

        orderInfoMapper.updateById(orderInfo);

//        //给用户加上累计消费
//        addUserTotalConsumption(orderInfo);

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        //格式转化一下
        String id = orderInfo.getId();
        log.info("此时获取到的订单id为：{}", id);

        //生成随机5位数字
        String numbers = RandomUtil.randomNumbers(5);

        // 格式化日期为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);
        String data = "pxo_" + formattedDate + "_" + numbers + "_" + id + "_00";
        log.info("此时生成的二维码为：{} ", data);

        // 保存入数据库
        orderInfo.setQrCode(data);
        int save = orderInfoMapper.updateById(orderInfo);

        if (save > 0) {
            // 接口地址和参数
            String apiUrl = "https://xiaofeng.pankzone.com/api/openapi/reg_access_qcode.x";
            String mac1 = "863569068849199";
            String mac2 = "863569068848969";
            String tk = ApiCallerUtil.callApi(mac1);
            log.info("此时获取到的token为：{} ", tk);

            //获取订单开始和结束时间
            Date orderSt = orderInfo.getOrderSt();
            Date orderEd = orderInfo.getOrderEd();

            // todo：第1个问题订场提前半小时内可以进，刚才离开开场前33分钟也能进
            // 转化为时间戳
            // 前30后30
            // 获取当前时间的时间戳（秒级）
            long currentTimeMillis = System.currentTimeMillis() / 1000;

            // 将订单开始时间前推30分钟并转换为时间戳
            long orderStTimestamp = (orderSt.getTime() / 1000) - (30 * 60);
            log.info("此时的订单开始时间戳为：{}", orderStTimestamp);
            Date stTime = new Date(orderStTimestamp * 1000);
            log.info("订单{}" + "的订单开始时间（二维码有效开始时间）为：{}", id, stTime);


            // 将订单结束时间后推30分钟并转换为时间戳
            long orderEdTimestamp = (orderEd.getTime() / 1000) + (30 * 60);
            log.info("此时的订单结束时间戳为：{}", orderEdTimestamp);
            Date endTime = new Date(orderEdTimestamp * 1000);
            log.info("订单{}" + "的订单结束时间（二维码失效时间）为：{}", id, endTime);

            // 如果需要确保不早于当前时间，可以添加以下逻辑
            orderStTimestamp = Math.max(orderStTimestamp, currentTimeMillis);
            orderEdTimestamp = Math.max(orderEdTimestamp, currentTimeMillis);

            // 拼接两个 MAC 地址，以逗号分隔
            String macParam = mac1 + "_" + mac2;
            log.info("此时拼接的macParam为：{}", macParam);

            //使用hutool调用接口
            HttpResponse response = HttpRequest.post(apiUrl).form("mac", macParam).form("tk", tk).form("qcodetxt", data).form("starttime", orderStTimestamp).form("enabletime", orderEdTimestamp).form("enablecount", realTime).execute();

            //获取响应结果
            String body = response.body();

            // 处理返回结果
            JSONObject json = new JSONObject(body);
            int code = json.getInt("code");
            log.info("此时返回的code为：{}", code);

            String qcodetxt = json.getStr("qcodetxt");
            log.info("此时返回的qcodetxt为：{}", qcodetxt);

            String desc = json.getStr("desc");
            log.info("此时返回的desc为：{}", desc);

            //对响应结果处理
            if (code != 0) {
                throw new ServiceException("硬件回调url设置接口异常！");
            }
            log.info("此时接口响应数据为：{} (不要记录敏感信息在日志中)", body);
        }
        // 返回适当的PayOutMessage
        return PayOutMessage.TEXT().content("success").build();
    }
}
