package com.dora.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.dora.config.MsmConfig;
import com.dora.service.MsmService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 短信服务实现类
 */
@Slf4j
@Service
public class MsmServiceImpl implements MsmService {
   
    @Resource
    private MsmConfig msmConfig;

    /**
     * 发送验证码
     * @param param 验证码参数
     * @param phone 手机号
     * @return 是否发送成功
     */
    @Override
    public boolean send(Map<String, Object> param, String phone) {
        if(StringUtils.isEmpty(phone)) {
            log.warn("手机号为空，无法发送短信");
            return false;
        }

        try {
            // 创建阿里云客户端
            DefaultProfile profile = DefaultProfile.getProfile("default", 
                msmConfig.getAccessKeyId(), msmConfig.getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);

            // 创建请求
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain("dysmsapi.aliyuncs.com");
            request.setVersion("2017-05-25");
            request.setAction("SendSms");

            // 设置请求参数
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", msmConfig.getSignName());
            request.putQueryParameter("TemplateCode", msmConfig.getVerifyTemplateCode());
            request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

            // 发送请求
            CommonResponse response = client.getCommonResponse(request);
            String responseData = response.getData();
            log.info("短信发送响应: {}", responseData);
            
            // 解析响应JSON
            JSONObject responseJson = JSONObject.parseObject(responseData);
            String code = responseJson.getString("Code");
            
            // 检查业务状态码
            if ("OK".equals(code)) {
                log.info("短信发送成功 - phone: {}", phone);
                return true;
            } else {
                String message = responseJson.getString("Message");
                log.error("短信发送失败 - phone: {}, code: {}, message: {}", phone, code, message);
                return false;
            }
        } catch (Exception e) {
            log.error("短信发送异常 - phone: {}", phone, e);
            return false;
        }
    }
} 