package org.dromara.resource.dubbo;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.dromara.common.core.enums.SmsType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.sms.config.SmsProperties;
import org.dromara.resource.api.RemoteSmsService;
import org.dromara.resource.api.domain.RemoteSms;
import org.dromara.resource.danmi_sms.DMSmsUtils;
import org.dromara.resource.danmi_sms.common.DMSmsResult;
import org.dromara.resource.service.ISysSmsService;
import org.dromara.resource.domain.SysSms;
import org.dromara.resource.mapper.SysSmsMapper;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.sms4j.provider.enumerate.SupplierType;
import org.dromara.system.api.RemoteConfigService;
import org.dromara.system.api.domain.RemoteSysUnitDomainVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 短信服务
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@Service
@DubboService
public class RemoteSmsServiceImpl implements RemoteSmsService {


    @Resource
    public ISysSmsService  sysSmsService;

    private final SysSmsMapper baseMapper;

    @Resource
    private SmsProperties  smsProperties;

    @DubboReference
    private RemoteConfigService remoteConfigService;

    @Autowired
    private DMSmsUtils dmSmsUtils;

    /**
     * 发送短信
     *
     * @param phones     电话号(多个逗号分割)
     * @param templateId 模板id
     * @param param      模板对应参数
     */
    public RemoteSms send(String phones, String templateId, LinkedHashMap<String, String> param) throws ServiceException {
        SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
        SmsResponse smsResponse = smsBlend.sendMessage(phones, templateId, param);
        RemoteSms sysSms = new RemoteSms();
        sysSms.setIsSuccess(smsResponse.isSuccess());
        sysSms.setMessage(smsResponse.getMessage());
        sysSms.setResponse(JsonUtils.toJsonString(smsResponse));
        return sysSms;
    }



    @Override
    public Boolean sendSmsCode(SmsType smsType, String phonenumber, LinkedHashMap<String, String> param, Map smsConfig) {
       return this.sysSmsService.sendSmsCode(smsType,phonenumber,param,smsConfig);

    }

    public RemoteSms send(String domain, String phone, SmsType smsType, LinkedHashMap<String, String> param) throws ServiceException {
        RemoteSysUnitDomainVo site = remoteConfigService.queryByDomainName(domain);
        if(site == null){
            throw new ServiceException("不支持短信");
        }
        if(site.getOpenSms() != 1 || StringUtils.isBlank(site.getSmsConfig())){
            throw new ServiceException("未开通短信");
        }
       JSONObject smsConfig = JSONObject.parseObject(site.getSmsConfig());


        DMSmsResult result = this.dmSmsUtils.verificationCode(site.getSmsConfig(), phone, param.get("code"));
        if(!result.isSuccess()){
            log.error("{}-{}验证码短信发送异常 => {}",smsType.getDesc(),phone, result.getErrorMsg());
        }


        java.util.Date  currentDate = DateUtil.date().toJdkDate();
//        SmsBlend smsBlend = null;
//        SmsResponse smsResponse = null;
//        String smsFacType = "tencent";
//        if(StringUtils.isNotEmpty(smsProperties.getType())){
//            smsFacType = smsProperties.getType();
//        }
//        switch (smsFacType){
//            case "aliyun":
//                smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA, AlibabaConfig.builder().accessKeyId(smsConfig.getString("accid_aliyun"))
//                        .accessKeySecret(smsConfig.getString("acckey_aliyun")).signature(smsConfig.getString("sign_aliyun")).build());
//                smsResponse = smsBlend.sendMessage(phone, smsConfig.getString(smsType.getTempId()+"_aliyun"), param);
//                break;
//            case  "tencent":
//                smsBlend = SmsFactory.createSmsBlend(SupplierType.TENCENT,TencentConfig.builder().sdkAppId(smsConfig.getString("appid")).accessKeyId(smsConfig.getString("accid"))
//                        .accessKeySecret(smsConfig.getString("acckey")).signature(smsConfig.getString("sign")).build());
//                smsResponse = smsBlend.sendMessage(phone, smsConfig.getString(smsType.getTempId()), param);
//                break;
//        }
//        SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.TENCENT,TencentConfig.builder().sdkAppId(smsConfig.getString("appid")).accessKeyId(smsConfig.getString("accid"))
//            .accessKeySecret(smsConfig.getString("acckey")).signature(smsConfig.getString("sign")).build());
//        SmsResponse smsResponse = smsBlend.sendMessage(phone, smsConfig.getString(smsType.getTempId()), param);
//        if (!"OK".equals(smsResponse.getCode())) {
//            log.error("{}-{}验证码短信发送异常 => {}",smsType.getDesc(),phone, smsResponse);
//        }
        SysSms smsEntity = new SysSms();
        smsEntity.setIUserId(LoginHelper.getUserId());
        smsEntity.setVTempId(smsType.getTempId());
        smsEntity.setDtmSendTime(currentDate);
        smsEntity.setVType(smsType.getDesc());
        String msg = smsConfig.getString("templateContent");
        if(StringUtils.isNotBlank(msg)){
            Iterator paramIter = param.entrySet().iterator();
            int paramIndex = 1;
            while(paramIter.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)paramIter.next();
                msg = msg.replace("{"+paramIndex+"}",entry.getValue());
                paramIndex++;
            }
            smsEntity.setVSendContent(msg);
        }

        smsEntity.setCreateTime(currentDate);
        smsEntity.setVPhone(phone);
        smsEntity.setDtmExpirTime(DateUtil.offsetMinute(currentDate,smsType.getExpireTime()));
        this.baseMapper.insert(smsEntity);
        return MapstructUtils.convert(smsEntity,RemoteSms.class);
    }
}
