package com.artfess.base.manager.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.artfess.base.exception.BaseException;
import com.artfess.base.manager.MobileSmsManager;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.vo.MobileSmsResultVo;
import com.artfess.base.vo.MobileSmsVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class MobileSmsManagerImpl implements MobileSmsManager {

    @Value("${mobileSMS.SendUrl}")
    private String SendUrl;
    @Value("${mobileSMS.SpCode}")
    private String SpCode;
    @Value("${mobileSMS.LoginName}")
    private String LoginName;
    @Value("${mobileSMS.Password}")
    private String Password;
    @Value("${mobileSMS.Signature}")
    private String Signature;

    @Override
    public MobileSmsResultVo SendSms(MobileSmsVo param) {
        param.setSpCode(BeanUtils.isNotEmpty(param.getSpCode())?param.getSpCode():SpCode);
        param.setLoginName(BeanUtils.isNotEmpty(param.getLoginName())?param.getLoginName():LoginName);
        param.setPassword(BeanUtils.isNotEmpty(param.getPassword())?param.getPassword():Password);
        param.setMessageContent(Signature+param.getMessageContent());
        String resultStr = null;
        System.out.println(LocalDateTime.now()+"短信发送参数:"+param);
        try {
            resultStr = HttpUtil.post(SendUrl, JSONUtil.toJsonStr(param));
        } catch (Exception e) {
            throw new BaseException("短信发送失败:"+e.getMessage());
        }
        System.out.println("短信发送返回:"+resultStr);

        if(BeanUtils.isEmpty(resultStr)){
            throw new BaseException("短信发送失败");
        }

        MobileSmsResultVo result = JSONUtil.toBean(resultStr, MobileSmsResultVo.class);

        if(BeanUtils.isEmpty(result.getResult()) || result.getResult()!=0){
            throw new BaseException("短信发送失败:"+result.getDescription());
        }

        return result;
    }

}

