package com.ruoyi.jarvis.service.erp;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.erp.request.ERPAccount;
import com.ruoyi.erp.request.IERPAccount;
import com.ruoyi.jarvis.domain.ErpOpenConfig;
import com.ruoyi.jarvis.service.IErpOpenConfigService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ErpAccountResolver {

    @Resource
    private IErpOpenConfigService erpOpenConfigService;

    /**
     * 优先库表启用配置，其次兼容历史枚举，最后默认胡歌
     */
    public IERPAccount resolve(String appid) {
        if (StringUtils.isNotEmpty(appid)) {
            ErpOpenConfig cfg = erpOpenConfigService.selectByAppKey(appid.trim());
            if (cfg != null && "0".equals(cfg.getStatus())) {
                return cfg;
            }
            for (ERPAccount a : ERPAccount.values()) {
                if (a.getApiKey().equals(appid.trim())) {
                    return a;
                }
            }
        }
        ErpOpenConfig first = erpOpenConfigService.selectFirstEnabled();
        if (first != null) {
            return first;
        }
        return ERPAccount.ACCOUNT_HUGE;
    }

    /** 校验回调签名时须严格对应 appid，不允许回落到默认账号 */
    public IERPAccount resolveStrict(String appid) {
        if (StringUtils.isEmpty(appid)) {
            return null;
        }
        ErpOpenConfig cfg = erpOpenConfigService.selectByAppKey(appid.trim());
        if (cfg != null && "0".equals(cfg.getStatus())) {
            return cfg;
        }
        for (ERPAccount a : ERPAccount.values()) {
            if (a.getApiKey().equals(appid.trim())) {
                return a;
            }
        }
        return null;
    }
}
