package jnpf.personnels.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.base.Joiner;
import jnpf.base.ActionResult;
import jnpf.base.SmsModel;
import jnpf.util.JsonUtil;
import jnpf.util.StringUtil;
import jnpf.util.message.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SmsSendUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsProperties smsProperties;
    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信
     *
     * @param phoneList        手机号
     * @param templateCode
     * @return
     */
    public void sendSms(List<String> phoneList, String templateCode, Map<String, Object> map, String tenantId) throws Exception {
        SmsTemplate template = null;
        //验证短信模板是否配置
        List<SmsTemplate> smsTemplateList;
        SmsConfig.TenantConfig tenantConfig;
        if (smsConfig != null) {
            tenantConfig = smsConfig.getTenants().get(tenantId);
            if (null == tenantConfig) {
                tenantConfig = smsConfig.getTenants().get("common");
            }
            if (null == tenantConfig) {
                throw new Exception("短信配置异常");
            }
            smsTemplateList = tenantConfig.getSmsTemplateList();
        } else {
            smsTemplateList = smsProperties.getSmsTemplateList();
            tenantConfig = JsonUtil.getJsonToBean(smsProperties, SmsConfig.TenantConfig.class);
        }
        if (CollectionUtil.isEmpty(smsTemplateList) || !smsTemplateList.stream().map(SmsTemplate::getCode).collect(Collectors.toList()).contains(templateCode)) {
            log.error("未配置相应的短信模板，请到配置中心配置相应的模板");
            throw new Exception("未配置相应的短信模板，请到配置中心配置相应的模板");
        } else {
            template = smsTemplateList.stream().filter(v -> v.getCode().equals(templateCode)).collect(Collectors.toList()).get(0);
        }
        SmsModel smsModel = new SmsModel();
        smsModel.setTencentSecretId(tenantConfig.getSmsSecretId());
        smsModel.setTencentSecretKey(tenantConfig.getSmsSecretKey());
        smsModel.setTencentAppId(tenantConfig.getSmsSdkAppId());
        smsModel.setTencentAppKey(tenantConfig.getSmsSdkAppKey());
//        phoneList.removeIf(item -> !isPhone(item));
        String respStr = SmsUtil.sentSms(2, smsModel, tenantConfig.getSmsEndpoint(), tenantConfig.getSmsRegion(),
                String.join(", ", phoneList), tenantConfig.getSmsSignContent(), template.getTemplateId(), map);
        if (!respStr.equals(AuthServerConstant.SUCCESS)) {
            throw new Exception(respStr);
        }
    }

    /**
     * 校验短信验证码是否正确
     *
     * @param code
     * @param phone
     * @return
     */
    public ActionResult checkCode(String code, String phone, Integer smsTimeOut) {
        try {
            String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
            if (!StringUtils.isEmpty(redisCode)) {
                String codeRedis = redisCode.split("_")[0];
                if (!codeRedis.equals(code)) {
                    return ActionResult.fail("短信验证码错误，请重新输入!");
                }
                long redisDate = Long.parseLong(redisCode.split("_")[1]);
                if (System.currentTimeMillis() - redisDate > smsTimeOut * 60 * 1000) {
                    return ActionResult.fail("验证码已过期");
                }
            } else {
                return ActionResult.fail("验证码已过期");
            }
            return ActionResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("检验验证码错误:{}", e.getMessage());
            return ActionResult.fail("检验验证码错误");
        }
    }


}

