package com.red.circle.order.app.scheduler;

import com.google.api.services.androidpublisher.model.VoidedPurchase;
import com.google.api.services.androidpublisher.model.VoidedPurchasesListResponse;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.component.pay.google.GoogleVerifyService;
import com.red.circle.component.redis.annotation.TaskCacheLock;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.framework.web.props.EnvProperties;
import com.red.circle.order.app.common.RecycleReimburseOrderProductCommon;
import com.red.circle.order.domain.tuple.KeyValuePair;
import com.red.circle.order.infra.database.rds.entity.order.OrderGoogleVoidedPurchase;
import com.red.circle.order.infra.database.rds.service.order.OrderCacheService;
import com.red.circle.order.infra.database.rds.service.order.OrderGoogleVoidedPurchaseService;
import com.red.circle.order.infra.database.rds.service.order.OrderPurchaseHistoryService;
import com.red.circle.tool.core.date.TimestampUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * google 退款检查.
 *
 * @author pengliang on 2021/5/24
 */
@Slf4j
@Component
@AllArgsConstructor
public class GoogleReimburseCheckTask {

  private final OrderCacheService orderCacheService;
  private final EnvProperties envProperties;
  private final GoogleVerifyService googleVerifyService;
  private final OrderPurchaseHistoryService orderPurchaseHistoryService;
  private final OrderGoogleVoidedPurchaseService orderGoogleVoidedPurchaseService;
  private final RecycleReimburseOrderProductCommon recycleReimburseOrderProductCommon;

  @Scheduled(cron = "0 */10 * * * ?")
  @TaskCacheLock(key = "GOOGLE_REIMBURSE_CHECK", expireSecond = 540)
  public void googleReimburseCheck() {
    long startTime = System.currentTimeMillis();
    log.warn("exec google_reimburse_check_job start");
    if (!envProperties.isProd()) {
      log.warn("not prod execute googleReimburseCheck.");
      return;
    }

    executeReimburse(20);
    log.warn("exec google_reimburse_check_job end with {}",System.currentTimeMillis()-startTime);
  }

  public void executeReimburse(int latestMinutes) {
      List.of(
              KeyValuePair.of(SysOriginPlatformEnum.LIKEI, "com.tkm.likei")
      ).forEach(keyValuePair -> {

      VoidedPurchasesListResponse response = googleVerifyService
          .getVoidedPurchases(keyValuePair.getKey(), keyValuePair.getValue(),
              TimestampUtils.nowMinusMinutes(latestMinutes));

      if (Objects.isNull(response)) {
        return;
      }

      List<VoidedPurchase> voidedPurchases = response.getVoidedPurchases();
      log.warn("voidedPurchases: {}", voidedPurchases);

      if (CollectionUtils.isEmpty(voidedPurchases)) {
        return;
      }

      voidedPurchases.forEach(voidedPurchase -> {
        if (!orderCacheService.lock("G-REIMBURSE:" + voidedPurchase.getOrderId())) {
          log.warn("[Reimburse]订单已已处理-cache:{}", voidedPurchase);
          return;
        }
        if (orderGoogleVoidedPurchaseService.existsOrder(voidedPurchase.getOrderId())) {
          log.warn("[Reimburse]订单已已处理-db:{}", voidedPurchase);
          return;
        }
        orderGoogleVoidedPurchaseService.save(toOrderGoogleVoidedPurchase(keyValuePair.getKey(),
            orderPurchaseHistoryService.getUserIdByOrderId(voidedPurchase.getOrderId()),
            voidedPurchase));

        recycleReimburseOrderProductCommon.recyclePlatformOrderId(voidedPurchase.getOrderId());
      });

    });
  }

  private OrderGoogleVoidedPurchase toOrderGoogleVoidedPurchase(
      SysOriginPlatformEnum sysOriginPlatform,
      Long userId,
      VoidedPurchase voidedPurchase) {

    OrderGoogleVoidedPurchase googleVoidedPurchase = new OrderGoogleVoidedPurchase();
    googleVoidedPurchase.setSysOrigin(sysOriginPlatform.name());
    googleVoidedPurchase.setUserId(userId);
    googleVoidedPurchase.setOrderId(voidedPurchase.getOrderId());
    googleVoidedPurchase.setPurchaseTimeMillis(new Timestamp(voidedPurchase.getPurchaseTimeMillis()));
    googleVoidedPurchase.setPurchaseToken(voidedPurchase.getPurchaseToken());
    googleVoidedPurchase.setVoidedSource(voidedPurchase.getVoidedSource());
    googleVoidedPurchase.setVoidedReason(voidedPurchase.getVoidedReason());

    if (Objects.isNull(userId)) {
      googleVoidedPurchase.setDescription(
          "【异常】没有站内关联，发起者:" + googleVoidedPurchase.getVoidedSourceString() + "，退款原因:"
              + googleVoidedPurchase.getVoidedReasonString());
      return googleVoidedPurchase;
    }
    googleVoidedPurchase.setDescription(
        "发起者:" + googleVoidedPurchase.getVoidedSourceString() + "，退款原因:"
            + googleVoidedPurchase.getVoidedReasonString());
    return googleVoidedPurchase;
  }


}
