package com.gxwebsoft;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.glt.entity.GltUserTicket;
import com.gxwebsoft.glt.service.GltTicketRevokeService;
import com.gxwebsoft.glt.service.GltUserTicketService;
import com.gxwebsoft.hjm.controller.PushCallback;
import com.gxwebsoft.hjm.entity.HjmCar;
import com.gxwebsoft.hjm.service.HjmCarService;
import com.gxwebsoft.shop.entity.ShopOrder;
import com.gxwebsoft.shop.entity.ShopOrderGoods;
import com.gxwebsoft.shop.service.ShopOrderGoodsService;
import com.gxwebsoft.shop.service.ShopOrderService;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by WebSoft on 2020-03-23 23:37
 */
@SpringBootTest
public class TestMain {
  private static final Logger logger = LoggerFactory.getLogger(PushCallback.class);

  @Resource
  private HjmCarService hjmCarService;

  @Resource
  private ShopOrderService shopOrderService;
  @Resource
  private ShopOrderGoodsService shopOrderGoodsService;
  @Resource
  private GltUserTicketService gltUserTicketService;
  @Resource
  private GltTicketRevokeService gltTicketRevokeService;

  /**
   * 查询已退款订单ShopOrder关联的gltUserTicket，仅处理租户ID=10584
   */
  @Test
  public void testOrderData() {
    final int tenantId = 10584;
    final int ORDER_STATUS_REFUND_SUCCESS = 6;

    // 安全开关：默认只查询/打印；如需实际撤销，将其改为 true
    final boolean doRevoke = false;

    int lastOrderId = 0;
    int batchSize = 200;

    int scannedOrders = 0;
    int ordersWithTickets = 0;
    int matchedTickets = 0;
    int revokedTickets = 0;

    while (true) {
      List<ShopOrder> orders = shopOrderService.list(new LambdaQueryWrapper<ShopOrder>()
        .select(ShopOrder::getOrderId, ShopOrder::getOrderNo, ShopOrder::getRefundTime, ShopOrder::getRefundMoney,
          ShopOrder::getOrderStatus, ShopOrder::getPayStatus, ShopOrder::getCreateTime)
        .eq(ShopOrder::getTenantId, tenantId)
        .eq(ShopOrder::getDeleted, 0)
        .eq(ShopOrder::getOrderStatus, ORDER_STATUS_REFUND_SUCCESS)
        .gt(ShopOrder::getOrderId, lastOrderId)
        .orderByAsc(ShopOrder::getOrderId)
        .last("limit " + batchSize));

      if (orders == null || orders.isEmpty()) {
        break;
      }

      for (ShopOrder o : orders) {
        if (o == null || o.getOrderId() == null) {
          continue;
        }
        scannedOrders++;
        lastOrderId = Math.max(lastOrderId, o.getOrderId());

        List<GltUserTicket> tickets = findTicketsByOrder(tenantId, o.getOrderId(), o.getOrderNo());
        if (tickets == null || tickets.isEmpty()) {
          tickets = findTicketsByOrderGoodsFallback(tenantId, o.getOrderId());
        }
        if (tickets == null || tickets.isEmpty()) {
          continue;
        }

        ordersWithTickets++;
        matchedTickets += tickets.size();

        logger.info("已退款订单关联水票 - tenantId={}, orderId={}, orderNo={}, refundMoney={}, refundTime={}, tickets={}",
          tenantId, o.getOrderId(), o.getOrderNo(), o.getRefundMoney(), o.getRefundTime(),
          tickets.stream().filter(Objects::nonNull).map(GltUserTicket::getId).collect(Collectors.toList()));

        if (doRevoke) {
          int revoked = gltTicketRevokeService.revokeByShopOrder(
            tenantId,
            o.getOrderId(),
            o.getOrderNo(),
            "TestMain: 历史退款订单撤销水票"
          );
          revokedTickets += revoked;
        }
      }
    }

    logger.info("扫描完成 - tenantId={}, scannedOrders={}, ordersWithTickets={}, matchedTickets={}, doRevoke={}, revokedTickets={}",
      tenantId, scannedOrders, ordersWithTickets, matchedTickets, doRevoke, revokedTickets);

  }

  private List<GltUserTicket> findTicketsByOrder(Integer tenantId, Integer orderId, String orderNo) {
    LambdaQueryWrapper<GltUserTicket> qw = new LambdaQueryWrapper<GltUserTicket>()
      .eq(GltUserTicket::getTenantId, tenantId)
      .eq(GltUserTicket::getDeleted, 0);
    if (orderId != null && StrUtil.isNotBlank(orderNo)) {
      qw.and(w -> w.eq(GltUserTicket::getOrderId, orderId).or().eq(GltUserTicket::getOrderNo, orderNo));
    } else if (orderId != null) {
      qw.eq(GltUserTicket::getOrderId, orderId);
    } else if (StrUtil.isNotBlank(orderNo)) {
      qw.eq(GltUserTicket::getOrderNo, orderNo);
    } else {
      return List.of();
    }
    return gltUserTicketService.list(qw);
  }

  /**
   * 兼容历史数据：部分水票仅记录了 order_goods_id，未回填 order_id/order_no。
   */
  private List<GltUserTicket> findTicketsByOrderGoodsFallback(Integer tenantId, Integer orderId) {
    if (tenantId == null || orderId == null) {
      return List.of();
    }
    List<ShopOrderGoods> goods = shopOrderGoodsService.list(new LambdaQueryWrapper<ShopOrderGoods>()
      .select(ShopOrderGoods::getId)
      .eq(ShopOrderGoods::getTenantId, tenantId)
      .eq(ShopOrderGoods::getOrderId, orderId));
    if (goods == null || goods.isEmpty()) {
      return List.of();
    }
    List<Integer> orderGoodsIds = goods.stream()
      .map(ShopOrderGoods::getId)
      .filter(Objects::nonNull)
      .distinct()
      .collect(Collectors.toList());
    if (orderGoodsIds.isEmpty()) {
      return List.of();
    }
    return gltUserTicketService.list(new LambdaQueryWrapper<GltUserTicket>()
      .eq(GltUserTicket::getTenantId, tenantId)
      .eq(GltUserTicket::getDeleted, 0)
      .in(GltUserTicket::getOrderGoodsId, orderGoodsIds));
  }
  /**
   * 生成唯一的key用于jwt工具类
   */
  @Test
  public void testGenJwtKey() {

    BigDecimal bigDecimal = new BigDecimal(NumberUtil.decimalFormat("0.00", 1 * 0.01));
    System.out.println("实际付款金额111111111 = " + bigDecimal);

    final HjmCar byGpsNo = hjmCarService.getByGpsNo("gps1");
    System.out.println("byGpsNo = " + byGpsNo.getSpeed());
    if(StrUtil.isBlank(byGpsNo.getSpeed())){
      System.out.println("空的 = ");
    }
    if(byGpsNo.getSpeed() == null){
      System.out.println("getSpeed = ");
    }
//    System.out.println(JwtUtil.encodeKey(JwtUtil.randomKey()));

//    final String encrypt = CommonUtil.encrypt("123456");
//    System.out.println("encrypt = " + encrypt);
//
//    final String decrypt = CommonUtil.decrypt(encrypt);
//    System.out.println("decrypt = " + decrypt);
  }

//  @Test
//  public void mqtt() throws MqttException {
////tcp://MQTT安装的服务器地址:MQTT定义的端口号
//    String HOST = "tcp://1.14.159.185:1883";
//
//    //定义MQTT的ID，可以在MQTT服务配置中指定
//    String clientid = "mqttx_aec633ca2";
//
//    MqttClient client;
//    String userName = "swdev";
//    String passWord = "Sw20250523";
//
//    client = new MqttClient(HOST, clientid, new MemoryPersistence());
//
//    final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
//    mqttConnectOptions.setUserName(userName);
//    mqttConnectOptions.setPassword(passWord.toCharArray());
//    mqttConnectOptions.setCleanSession(true);
//
//    client.setCallback(new MqttCallback() {
//      @Override
//      public void connectionLost(Throwable throwable) {
//        logger.info("连接丢失.............");
//      }
//
//      @Override
//      public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
//        logger.info("接收消息主题 : " + topic);
//        logger.info("接收消息Qos : " + mqttMessage.getQos());
//        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));
//      }
//
//      @Override
//      public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//        logger.info("deliveryComplete.............");
//      }
//    });
//    client.connect(mqttConnectOptions);
//    client.subscribe("/SW_GSP/#", 2);
//    while (true);
//  }
}
