package com.linkwechat.wecom.service;

import com.linkwechat.common.config.WeComeConfig;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.exception.wecom.WeComException;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.common.utils.spring.SpringUtils;

/**
 * @author sxw
 * @description 企业token业务抽象类
 * @date 2021/7/10 10:09
 **/
public abstract class IWeComCorpTokenService {
    /**
     * 获取企业id
     *
     * @return 企业id
     */
    protected String getCorpId() {
        String corpId = WeComeConfig.localCorpId.get();
        if(StringUtils.isEmpty(corpId)){
            corpId = SecurityUtils.getLoginUser().getUser().getCorpId();
        }
        return corpId;
    }

    /**
     * 获取企业配置信息
     *
     * @param corpId 企业id
     * @return 企业配置信息
     */
    protected WeCorpAccount getCorpConfigInfo(String corpId) {
        return SpringUtils.getBean(IWeCorpAccountService.class).getWeCorpAccount(corpId);
    }

    /**
     * 获取token
     *
     * @param corpConfigInfo 企业配置信息
     * @return 对应token
     */
    protected abstract String getToken(String accessTokenKey, WeCorpAccount corpConfigInfo);

    /**
     * 获取企业token
     *
     * @return 返回token
     */
    protected String getWeComToken(String accessTokenKey) {
        String corpId = getCorpId();
        if(StringUtils.isNotEmpty(corpId)){
            throw new WeComException("企业id为空，无法获取token");
        }
        WeCorpAccount corpConfigInfo = getCorpConfigInfo(corpId);
        if(corpConfigInfo == null){
            throw new WeComException("企业配置信息为空，无法获取token");
        }
        return getToken(accessTokenKey, corpConfigInfo);
    }


}
