package com.bonus.canteen.core.allocation.api;

import cn.hutool.core.util.StrUtil;
import com.bonus.canteen.core.allocation.alloc.model.AllocPayModel;
import com.bonus.canteen.core.allocation.alloc.service.AllocMetadataService;
import com.bonus.canteen.core.common.enums.MetadataModelTypeEnum;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.order.utils.LeNumUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class AllocPayMetadataApi {
   private static final Logger log = LoggerFactory.getLogger(AllocPayMetadataApi.class);
   @Resource
   @Lazy
   private GlobalMetadataApi globalMetadataApi;
   @Resource
   @Lazy
   private AllocMetadataService allocMetadataService;

   @Value("${system.notify.unify-host}")
   private String unifyCallbackHost;

   public List<Integer> supportPayChannels(Long canteenId) {
      String supportChannels = this.globalMetadataApi.getAvailableValue(MetadataModelTypeEnum.PAY, "payTypes", canteenId, (Long)null);
      log.info("【支付配置】当前配置支持支付方式：{}", supportChannels);
      return (List) StrUtil.splitTrim(supportChannels, ",").stream().filter(Objects::nonNull).map(Integer::valueOf).collect(Collectors.toList());
   }

   public AllocPayModel queryAvailablePayModel(@Nullable Long canteenId) {
      String var10000 = this.allocMetadataService.getCacheKeyPrefix();
      String key = var10000 + "pay-model-canteen:" + String.valueOf(LeNumUtil.isValidId(canteenId) ? canteenId : "-1");
      Object cacheObj = RedisUtil.getObj(key);
      if (cacheObj instanceof AllocPayModel) {
         return (AllocPayModel)cacheObj;
      } else {
         AllocPayModel availableModel = (AllocPayModel)this.globalMetadataApi.getAvailableModel(MetadataModelTypeEnum.PAY, new AllocPayModel(), canteenId, (Long)null);
         RedisUtil.setObj(key, availableModel, 1800L);
         return availableModel;
      }
   }

   public String queryUnifyNotifyHost() {
      String value = this.globalMetadataApi.getAvailableValue(MetadataModelTypeEnum.PAY, "unifyPayNotifyHost", (Long)null, (Long)null);
      return StrUtil.isBlank(value) && StrUtil.isNotBlank(this.unifyCallbackHost) ? this.unifyCallbackHost : value;
   }
}
