package com.bonus.common.houqin.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;

import java.util.Iterator;
import java.util.Map;

public class HeaderFetchUtil {
   public static String getMachineSn(Map<String, String> headers) {
      String value = getValueFromHeadersIgnoreCase(headers, "machine-sn");
      if (value == null) {
         value = getValueFromHeadersIgnoreCase(headers, "machineSn");
      }

      return value;
   }

   public static String getMachineNum(Map<String, String> headers) {
      String value = getValueFromHeadersIgnoreCase(headers, "machine-num");
      if (value == null) {
         value = getValueFromHeadersIgnoreCase(headers, "machineNum");
      }

      return value;
   }

   public static String getFaceVer(Map<String, String> headers) {
      return getValueFromHeadersIgnoreCase(headers, "face-ver");
   }

   public static Long getMerchant(Map<String, String> headers) {
      String value = getValueFromHeadersIgnoreCase(headers, "MERCHANT-ID");
      return NumberUtil.isNumber(value) ? Long.valueOf(value) : null;
   }

   public static Integer getSourceType(Map<String, String> headers) {
      String value = getValueFromHeadersIgnoreCase(headers, "source-type");
      if (value == null) {
         value = getValueFromHeadersIgnoreCase(headers, "sourceType");
      }

      return NumberUtil.isNumber(value) ? Integer.valueOf(value) : null;
   }

   public static String getOpenid(Map<String, String> headers) {
      String value = getValueFromHeadersIgnoreCase(headers, "openid");
      if (value == null) {
         value = getValueFromHeadersIgnoreCase(headers, "open-id");
      }

      return value;
   }

   public static Long getCustId(Map<String, String> headers) {
      String value = getValueFromHeadersIgnoreCase(headers, "custId");
      return CharSequenceUtil.isNotBlank(value) ? Long.valueOf(value) : null;
   }

   public static Integer getAppletType(Map<String, String> headers) {
      String value = getValueFromHeadersIgnoreCase(headers, "applet-type");
      return NumberUtil.isNumber(value) ? Integer.valueOf(value) : null;
   }

   public static String getValueFromHeadersIgnoreCase(Map<String, String> headers, String targetKey) {
      if (CollUtil.isEmpty(headers)) {
         return null;
      } else {
         Iterator var2 = headers.keySet().iterator();

         String key;
         do {
            if (!var2.hasNext()) {
               return null;
            }

            key = (String)var2.next();
         } while(!CharSequenceUtil.equalsAnyIgnoreCase(targetKey, new CharSequence[]{key}));

         return (String)headers.get(key);
      }
   }
}
