package com.cf.imes.module.system.framework.sms.core.client.impl;

import cn.hutool.core.util.ObjectUtil;
import com.cf.imes.module.system.framework.sms.core.client.SmsClient;
import com.cf.imes.module.system.framework.sms.core.client.SmsClientFactory;
import com.cf.imes.module.system.framework.sms.core.client.impl.aliyun.AliyunSmsClient;
import com.cf.imes.module.system.framework.sms.core.client.impl.debug.DebugDingTalkSmsClient;
import com.cf.imes.module.system.framework.sms.core.enums.SmsChannelEnum;
import com.cf.imes.module.system.framework.sms.core.property.SmsChannelProperties;
import com.cf.imes.module.system.framework.sms.core.property.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 短信客户端工厂接口
 *
 * @author zzf
 */
@Validated
@Slf4j
@Service
public class SmsClientFactoryImpl implements SmsClientFactory {

    /**
     * 短信客户端 Map
     * key：渠道编码，使用 {@link SmsChannelProperties#getCode()} ()}
     *
     * 注意，一些场景下，需要获得某个渠道类型的客户端，所以需要使用它。
     * 例如说，解析短信接收结果，是相对通用的，不需要使用某个渠道编号的 {@link #channelIdClients}
     */
    private final ConcurrentMap<String, AbstractSmsClient> channelCodeClients = new ConcurrentHashMap<>();

    public SmsClientFactoryImpl(SmsProperties smsProperties) {
        // 从配置初始化对应的client客户端
        AbstractSmsClient client = createSmsClient(smsProperties);
        client.init();
        channelCodeClients.put(smsProperties.getChannel(), client);
    }

    @Override
    public SmsClient getSmsClient(SmsProperties smsProperties) {
        String channel = smsProperties.getChannel();
        AbstractSmsClient client = channelCodeClients.get(channel);
        // 1、新的短信类型；2、配置改变
        if (ObjectUtil.isNull(client)) {
            client = this.createSmsClient(smsProperties);
            client.init();
            channelCodeClients.put(channel, client);
        }
        return client;
    }

    private AbstractSmsClient createSmsClient(SmsProperties smsProperties) {
        String channel = smsProperties.getChannel();
        SmsChannelEnum channelEnum = SmsChannelEnum.getByCode(channel);
        Assert.notNull(channelEnum, String.format("渠道类型(%s) 为空", channel));
        // 创建客户端
        switch (channelEnum) {
            case ALIYUN: return new AliyunSmsClient(smsProperties);
            case DEBUG_DING_TALK: return new DebugDingTalkSmsClient(smsProperties);
        }
        // 创建失败，错误日志 + 抛出异常
        log.error("[createSmsClient][配置({}) 找不到合适的客户端实现]", smsProperties);
        throw new IllegalArgumentException(String.format("配置(%s) 找不到合适的客户端实现", smsProperties));
    }

}
