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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bonus.canteen.core.allocation.alloc.model.AllocMetadata;
import com.bonus.canteen.core.allocation.alloc.model.AllocPayModel;
import com.bonus.canteen.core.allocation.alloc.model.MerchantLoginApp;
import com.bonus.canteen.core.allocation.alloc.service.AllocMetadataService;
import com.bonus.canteen.core.allocation.alloc.service.MerchantLoginAppService;
import com.bonus.canteen.core.allocation.canteen.dto.AllocCanteenPayDTO;
import com.bonus.canteen.core.common.enums.AllocMobilePayConfEnum;
import com.bonus.canteen.core.common.enums.MetadataModelTypeEnum;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.order.utils.LeNumUtil;
import com.bonus.canteen.core.pay.channel.abc.entity.dto.AbcMerchantAddOrUpdateDTO;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.canteen.core.allocation.util.MetadataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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;

   @Resource
   private MerchantLoginAppService merchantLoginAppService;

   public List<Integer> supportPayChannels(Long canteenId) {
      String supportChannels = this.globalMetadataApi.getAvailableValue(MetadataModelTypeEnum.PAY, "payTypes", canteenId, (Long)null);
      log.info("【支付配置】当前配置支持支付方式：{}", supportChannels);
      return 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;
   }

   public void saveCanteenPay(AllocCanteenPayDTO payDTO, Long canteenId) {
      if (StrUtil.isNotBlank(payDTO.getPayTypes()) && StrUtil.isBlank(this.queryUnifyNotifyHost())) {
         throw new ServiceException(I18n.getMessage("alloc_metadata_no_call_back_addr", new Object[0]));
      } else {
         List<AllocMetadata> payMetadataList = MetadataUtil.transferPayMetadataList(payDTO, canteenId);
         this.globalMetadataApi.saveList(payMetadataList);
//         AbcMerchantAddOrUpdateDTO abcDTO = MetadataUtil.transferAbcPayToDTO(payDTO.getPayMap(), canteenId);
//         if (ObjectUtil.isNotNull(abcDTO)) {
//            this.abcPayApi.saveAbcMerchantInfo(abcDTO);
//         } // 注释农行逻辑 2025-02-03 dgw

         List<MerchantLoginApp> loginAppList = new ArrayList();
         MerchantLoginApp rechargeMerNoMetadata;
//         if (payDTO.getPayMap().containsKey("cmbMerId")) {
//            rechargeMerNoMetadata = new MerchantLoginApp(TenantContextHolder.getTenantId(), "cmbMerId", (String)payDTO.getPayMap().get("cmbMerId"));
//            loginAppList.add(rechargeMerNoMetadata);
//         }
//
//         if (payDTO.getPayMap().containsKey("fuiouMerId")) {
//            rechargeMerNoMetadata = new MerchantLoginApp(TenantContextHolder.getTenantId(), "fuiouMerId", (String)payDTO.getPayMap().get("fuiouMerId"));
//            loginAppList.add(rechargeMerNoMetadata);
//         }
//
//         if (payDTO.getPayMap().containsKey("njcbStoreNo")) {
//            rechargeMerNoMetadata = new MerchantLoginApp(TenantContextHolder.getTenantId(), "njcbStoreNo", (String)payDTO.getPayMap().get("njcbStoreNo"));
//            loginAppList.add(rechargeMerNoMetadata);
//         }

//         if (payDTO.getPayMap().containsKey("tcrcbMerId")) {
//            rechargeMerNoMetadata = new MerchantLoginApp(TenantContextHolder.getTenantId(), "tcrcbMerId", (String)payDTO.getPayMap().get("tcrcbMerId"));
//            loginAppList.add(rechargeMerNoMetadata);
//            TCRCBPayDTO tcrcbPayDTO = new TCRCBPayDTO();
//            tcrcbPayDTO.setTcrcbMerId((String)payDTO.getPayMap().get("tcrcbMerId"));
//            tcrcbPayDTO.setTcrcbMerPriKeyFileUrl((String)payDTO.getPayMap().get("tcrcbMerPriKeyFileUrl"));
//            tcrcbPayDTO.setTcrcbMerPubKeyFileUrl((String)payDTO.getPayMap().get("tcrcbMerPubKeyFileUrl"));
//            tcrcbPayDTO.setTcrcbPlatformPubKeyFileUrl((String)payDTO.getPayMap().get("tcrcbPlatformPubKeyFileUrl"));
//            tcrcbPayDTO.setTcrcbMerPriKeyCertPwd((String)payDTO.getPayMap().get("tcrcbMerPriKeyCertPwd"));
//            TcrcbConfigInitializer.updateCertConfigMap(tcrcbPayDTO);
//         }

//         if (payDTO.getPayMap().containsKey("wxrcbPalmRechargeMerNo") || payDTO.getPayMap().containsKey("wxrcbOnlineMerNo")) {
//            rechargeMerNoMetadata = new MerchantLoginApp(TenantContextHolder.getTenantId(), "wxrcbPalmRechargeMerNo", (String)payDTO.getPayMap().get("wxrcbPalmRechargeMerNo"));
//            MerchantLoginApp onlineMerNoMetadata = new MerchantLoginApp(TenantContextHolder.getTenantId(), "wxrcbOnlineMerNo", (String)payDTO.getPayMap().get("wxrcbOnlineMerNo"));
//            loginAppList.add(rechargeMerNoMetadata);
//            loginAppList.add(onlineMerNoMetadata);
//            TCRCBPayDTO tcrcbPayDTO = new TCRCBPayDTO();
//            tcrcbPayDTO.setTcrcbMerId((String)payDTO.getPayMap().get("wxrcbOnlineMerNo"));
//            tcrcbPayDTO.setTcrcbMerPriKeyFileUrl((String)payDTO.getPayMap().get("wxrcbMerPriKeyFileUrl"));
//            tcrcbPayDTO.setTcrcbMerPubKeyFileUrl((String)payDTO.getPayMap().get("wxrcbMerPubKeyFileUrl"));
//            tcrcbPayDTO.setTcrcbPlatformPubKeyFileUrl((String)payDTO.getPayMap().get("wxrcbPlatformPubKeyFileUrl"));
//            tcrcbPayDTO.setTcrcbMerPriKeyCertPwd((String)payDTO.getPayMap().get("wxrcbPrivateKeyCertPwd"));
//            TcrcbConfigInitializer.updateCertConfigMap(tcrcbPayDTO);
//         }

         if (CollUtil.isNotEmpty(loginAppList)) {
            this.merchantLoginAppService.saveList(loginAppList);
         }

      }
   }

   public AllocCanteenPayDTO getAllocCanteenPayDTO(Long canteenId) {
      Map<String, String> payMap = this.globalMetadataApi.getMap(MetadataModelTypeEnum.PAY, canteenId, (Long)null);
      if (!payMap.containsKey("alipayMobilePayConf")) {
         payMap.put("alipayMobilePayConf", AllocMobilePayConfEnum.ALLOW_RECHARGE_CONSUME.getKey());
      }

      if (!payMap.containsKey("wechatMobilePayConf")) {
         payMap.put("wechatMobilePayConf", AllocMobilePayConfEnum.ALLOW_RECHARGE_CONSUME.getKey());
      }

//      AbcMerchantQueryVO abcVO = this.abcPayApi.queryAbcMerchantInfo(canteenId);
//      Map<String, String> abcMap = MetadataUtil.transferAbcPayToMap(abcVO);
//      payMap.putAll(abcMap); 2025-03-04 dgw 注释 农行
      return new AllocCanteenPayDTO((String)payMap.get("ifEnablePay"), (String)payMap.get("payTypes"), payMap);
   }
}
