package com.platform.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.platform.dao.SysSmsLogDao;
import com.platform.entity.SysSmsLogEntity;
import com.platform.service.SysConfigService;
import com.platform.service.SysSmsLogService;
import com.platform.utils.IdUtil;
import com.platform.utils.RRException;
import com.platform.utils.ShiroUtils;
import com.platform.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service("smsLogService")
public class SysSmsLogServiceImpl implements SysSmsLogService {
    @Autowired
    private SysSmsLogDao smsLogDao;
    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public SysSmsLogEntity queryObject(String id) {
        return smsLogDao.queryObject(id);
    }

    @Override
    public List<SysSmsLogEntity> queryList(Map<String, Object> map) {
        return smsLogDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return smsLogDao.queryTotal(map);
    }


    @Override
    public SysSmsLogEntity querySmsCodeByPhoneNum(String phoneNum) {

        return smsLogDao.querySmsCodeByPhoneNum(phoneNum);
    }

    @Override
    public int save(SysSmsLogEntity smsLog) {
        smsLog.setId(IdUtil.createIdbyUUID());
        return smsLogDao.save(smsLog);
    }

    @Override
    public int update(SysSmsLogEntity smsLog) {
        return smsLogDao.update(smsLog);
    }

    @Override
    public int delete(String id) {
        return smsLogDao.delete(id);
    }

    @Override
    public int deleteBatch(String[] ids) {
        return smsLogDao.deleteBatch(ids);
    }

    @Override
    public SysSmsLogEntity sendSms(SysSmsLogEntity smsLog) {
        SmsSingleSenderResult result;
        boolean falg = false;
        try {
            /**
             * 状态,发送编号,无效号码数,成功提交数,黑名单数和消息，无论发送的号码是多少，一个发送请求只返回一个sendid，如果响应的状态不是“0”，则只有状态和消息
             */
//            result = SmsUtil.crSendSms(config.getAppid(), config.getAppkey(), smsLog.getMobile(), smsLog.getTemplateId(), new String[]{smsLog.getCode()}, smsLog.getSign());
            falg = SmsUtil.sendAliSms(smsLog.getMobile(), "{\"code\":\"" + smsLog.getCode() + "\"}", "SMS_184816840");
            //发送成功
//            if (result.result == 0) {
            if (falg) {
//                smsLog.setSendId(result.sid);
                smsLog.setSuccessNum(1);
                smsLog.setReturnMsg("短信发送成功");
            } else {
                //发送失败
                smsLog.setReturnMsg("短信发送失败");
            }
        } catch (Exception e) {
            throw new RRException("短信发送失败");
        }
        smsLog.setSendStatus(0);
        try {
            smsLog.setUserId(ShiroUtils.getUserId());
        } catch (Exception e) {
            //外部发送短信
            smsLog.setUserId(1L);
        }
//        smsLog.setSign(config.getSign());
        //保存发送记录
        save(smsLog);
        return smsLog;
    }


    //阿里云发送短信

    @Override
    public SysSmsLogEntity sendAliSms(String templateCode, SysSmsLogEntity smsLog) {
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        boolean result = false;
        try {
            // 初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", SmsUtil.accessKeyId, SmsUtil.accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", SmsUtil.product, SmsUtil.domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            // 组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();

            // 必填:待发送手机号
            request.setPhoneNumbers(smsLog.getMobile());
            // 必填:短信签名-可在短信控制台中找到
            request.setSignName(SmsUtil.signName);
            // 必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);

            // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            request.setTemplateParam("{\"code\":\"" + smsLog.getCode() + "\"}");

            // 选填-上行短信扩展码(无特殊需求用户请忽略此字段)
            // request.setSmsUpExtendCode("90997");

            // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            // request.setOutId("yourOutId");

            // hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse != null
                    && !org.springframework.util.StringUtils.isEmpty(sendSmsResponse.getCode())
                    && "OK".equals(sendSmsResponse.getCode())) {
                log.debug("阿里云短信发送成功");

                smsLog.setSendId(sendSmsResponse.getBizId());
                smsLog.setSuccessNum(1);
                smsLog.setReturnMsg(sendSmsResponse.getMessage());
                smsLog.setSendStatus(1);
                result = true;
            } else {
                //发送失败
                smsLog.setReturnMsg(sendSmsResponse.getMessage());
                smsLog.setSendStatus(0);
            }
        } catch (ClientException e) {
            throw new RRException("短信发送失败");
        }

        try {
            smsLog.setUserId(ShiroUtils.getUserId());
        } catch (Exception e) {
            //外部发送短信
            smsLog.setUserId(1L);
        }
        //保存发送记录
        save(smsLog);
        return smsLog;
    }
}
