package shop.alien.store.util.ali;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import shop.alien.entity.store.StoreVerificationCode;
import shop.alien.mapper.StoreVerificationCodeMapper;
import shop.alien.store.config.BaseRedisService;
import shop.alien.store.config.NacosConfig;
import shop.alien.util.common.RandomCreateUtil;

import java.util.Date;

/**
 * 阿里云验证码配置
 *
 * @author ssk
 * @version 1.0
 * @date 2024/12/12 10:17
 */
@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class AliSms {
    private final BaseRedisService baseRedisService;

    private final NacosConfig nacosConfig;

    private final StoreVerificationCodeMapper storeVerificationCodeMapper;

    private final UserForgetPasswordSmsDailyLimiter userForgetPasswordSmsDailyLimiter;

    @Value("${ali.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${ali.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${ali.sms.endPoint}")
    private String endPoint;

    @Value("${ali.sms.signName}")
    private String signName;

    @Value("${ali.sms.templateCode}")
    private String templateCode;

    @Value("${ali.sms.codeTimeOut}")
    private Long codeTimeOut;

    @Value("${ali.sms.templateAccount}")
    private String templateAccount;

    @Value("${ali.sms.templateAccountCode:}")
    private String templateAccountCode;

    @Value("${ali.sms.templatereFundCode:}")
    private String templatereFundCode;

    @Value("${ali.sms.templatereRefundCode:}")
    private String templatereRefundCode;

    /** 到店提醒短信模板（内容：您在${time}预订了${storeName}${tableNumber}的桌位,请您及时到店） */
    @Value("${ali.sms.templateArrivalReminderCode:}")
    private String templateArrivalReminderCode;




    /**
     * 发送验证码
     *
     * @param phone        手机号
     * @param appType      端区分(0:用户, 1:商家, 2:商家web端)
     * @param businessType 业务类型 (0:登录, 1:修改密码, 2:注册, 3:修改手机号, 4:注销店铺, 5:注销账号, 6:忘记密码)
     * @return 验证码
     */
    public Integer sendSms(String phone, Integer appType, Integer businessType) {
        log.info("AliSmsConfig.sendSms?phone={}&appType={}&businessType={}", phone, appType, businessType);
        if (userForgetPasswordSmsDailyLimiter.isUserForgetPassword(appType, businessType)) {
            userForgetPasswordSmsDailyLimiter.checkLimit(phone);
        }
        try {
            String appTypeStr = resolveAppTypeStr(appType);
            String businessTypeStr;
            switch (businessType) {
                case 0:
                    //登录
                    businessTypeStr = "login";
                    break;
                case 1:
                    //修改密码
                    businessTypeStr = "modify_password";
                    break;
                case 2:
                    //注册
                    businessTypeStr = "register";
                    break;
                case 3:
                    //修改手机号
                    businessTypeStr = "modify_phone";
                    break;
                case 4:
                    //注销店铺
                    businessTypeStr = "cancel_store";
                    break;
                case 5:
                    //注销账号
                    businessTypeStr = "cancel_account";
                    break;
                case 6:
                    //忘记密码
                    businessTypeStr = "forget_password";
                    break;
                case 7:
                    //忘记支付密码
                    businessTypeStr = "forget_pay_password";
                    break;
                default:
                    businessTypeStr = "login";
            }
            // -----------------测试用手机号--------------------------------------------------------------------------------------------
            if (nacosConfig.getTestPhone().contains(phone)) {
                // 验证码发送成功，将验证码保存到redis中 设置60秒过期
                baseRedisService.setString("verification_" + appTypeStr + "_" + businessTypeStr + "_" + phone, "123456", codeTimeOut);
                saveVerificationCode(appType, businessType, phone, "123456");
                return 123456;
            }
            // -----------------测试用手机号--------------------------------------------------------------------------------------------

            Config config = new Config()
                    .setEndpoint(endPoint)
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret);
            Integer code = RandomCreateUtil.getRandomNum(100000, 999999);

            // 构建发送请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    // 设置签名
                    .setSignName(signName)
                    // 设置模板
                    .setTemplateCode(templateCode)
                    // 设置手机号为参数传入的值
                    .setPhoneNumbers(phone)
                    // 设置模板参数为传入的验证码
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            // 运行时选择，可以设置不同的属性来配置运行时环境的参数。
            RuntimeOptions runtime = new RuntimeOptions();
            Client client = new Client(config);
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            if (!"OK".equals(sendSmsResponse.getBody().getCode())) {
                return null;
            }
            // 验证码发送成功，将验证码保存到redis中 设置60秒过期
            baseRedisService.setString("verification_" + appTypeStr + "_" + businessTypeStr + "_" + phone, code.toString(), codeTimeOut);
            saveVerificationCode(appType, businessType, phone, code.toString());
            recordUserForgetPasswordSend(appType, businessType, phone);

            return code;
        } catch (SmsSendLimitException e) {
            throw e;
        } catch (Exception e) {
            log.error("AliSmsConfig.sendSms ERROR Msg={}", e.getMessage());
            return null;
        }
    }

    /**
     * 校验短信验证码
     *
     * @param phone        手机号
     * @param appType      端区分(0:用户, 1:商家, 2:商家web端)
     * @param businessType 业务类型 (0:登录, 1:修改密码, 2:注册, 3:修改手机号, 4:注销店铺, 5:注销账号, 6:忘记密码)
     * @param code         用户输入的验证码
     * @return 校验结果 true-校验成功 false-校验失败
     */
    public boolean checkSmsCode(String phone, Integer appType, Integer businessType, Integer code) {
        log.info("AliSms.checkSmsCode?phone={}&appType={}&businessType={}&code={}", phone, appType, businessType, code);
        try {
            // 构建Redis key，与sendSms方法中的key格式保持一致
            String appTypeStr = resolveAppTypeStr(appType);
            String businessTypeStr;
            switch (businessType) {
                case 0:
                    businessTypeStr = "login";
                    break;
                case 1:
                    businessTypeStr = "modify_password";
                    break;
                case 2:
                    businessTypeStr = "register";
                    break;
                case 3:
                    businessTypeStr = "modify_phone";
                    break;
                case 4:
                    businessTypeStr = "cancel_store";
                    break;
                case 5:
                    businessTypeStr = "cancel_account";
                    break;
                case 6:
                    businessTypeStr = "forget_password";
                    break;
                case 7:
                    businessTypeStr = "forget_pay_password";
                    break;
                default:
                    businessTypeStr = "login";
            }
            
            String verifyKey = "verification_" + appTypeStr + "_" + businessTypeStr + "_" + phone;
            
            // 从Redis中获取验证码
            String cacheCode = baseRedisService.getString(verifyKey);
            
            // 验证码不存在或已过期
            if (cacheCode == null || cacheCode.trim().isEmpty()) {
                log.warn("验证码不存在或已过期，phone={}, appType={}, businessType={}", phone, appType, businessType);
                return false;
            }
            
            // 比较验证码（去除空格）
            boolean isValid = cacheCode.trim().equals(String.valueOf(code).trim());
            
            if (isValid) {
                // 验证成功，删除验证码（防止重复使用）
                baseRedisService.delete(verifyKey);
                log.info("验证码校验成功，phone={}, appType={}, businessType={}", phone, appType, businessType);
            } else {
                log.warn("验证码校验失败，phone={}, appType={}, businessType={}, 期望值={}, 实际值={}", 
                        phone, appType, businessType, cacheCode, code);
            }
            
            return isValid;
        } catch (Exception e) {
            log.error("AliSms.checkSmsCode ERROR Msg={}", e.getMessage(), e);
            return false;
        }
    }

    private void saveVerificationCode(Integer appType, Integer businessType, String phone, String code) {
        try {
            StoreVerificationCode entity = new StoreVerificationCode();
            entity.setAppType(appType);
            entity.setBusinessType(businessType);
            entity.setPhone(phone);
            entity.setCode(code);
            Date now = new Date();
            entity.setCreatedTime(now);
            entity.setUpdatedTime(now);
            entity.setDeleteFlag(0);
            storeVerificationCodeMapper.insert(entity);
        } catch (Exception ex) {
            log.error("AliSms.saveVerificationCode ERROR Msg={}", ex.getMessage(), ex);
        }
    }

    private void recordUserForgetPasswordSend(Integer appType, Integer businessType, String phone) {
        if (userForgetPasswordSmsDailyLimiter.isUserForgetPassword(appType, businessType)) {
            userForgetPasswordSmsDailyLimiter.recordSend(phone);
        }
    }

    /**
     * JSON字符串转义，防止特殊字符破坏JSON格式
     */
    private String escapeJsonString(String str) {
        if (str == null) {
            return "";
        }
        return str.replace("\\", "\\\\")
                  .replace("\"", "\\\"")
                  .replace("\n", "\\n")
                  .replace("\r", "\\r")
                  .replace("\t", "\\t");
    }

    /**
     * 发送律师短信信息（账号密码通知）
     * @param phone        手机号
     * @param userName     用户名
     * @param password     密码
     * @return 1-发送成功, null-发送失败
     */
    public Integer sendLawyerSms(String phone, String userName, String password) {
        log.info("AliSmsConfig.sendLawyerSms?phone={}&userName={}", phone, userName);
        try {
            Config config = new Config()
                    .setEndpoint(endPoint)
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret);

            // 构建模板参数JSON，必须符合阿里云短信模板参数格式
            // 模板内容：您在律所管理平台的账号已创建成功,账号名称为${userName},登录密码为${password}.
            // 模板CODE：SMS_499205254
            // 变量：userName（用户昵称）、password（其他号码）
            // 参数名必须与模板中的变量名一致（去掉${}），格式必须是有效的JSON
            String templateParam = String.format("{\"userName\":\"%s\",\"password\":\"%s\"}", 
                    escapeJsonString(userName), 
                    escapeJsonString(password));

            // 使用账号密码短信模板代码
            // 优先级：templateAccountCode > templateAccount（如果以SMS_开头）> templateCode
            String accountTemplateCode;
            if (templateAccountCode != null && !templateAccountCode.trim().isEmpty()) {
                accountTemplateCode = templateAccountCode;
            } else if (templateAccount != null && templateAccount.startsWith("SMS_")) {
                // 如果templateAccount配置的是模板代码（以SMS_开头），则使用它
                accountTemplateCode = templateAccount;
            } else {
                accountTemplateCode = templateCode;
            }

            log.info("AliSmsConfig.sendLawyerSms 准备发送短信，phone={}, userName={}, templateCode={}, templateParam={}", 
                    phone, userName, accountTemplateCode, templateParam);

            // 构建发送请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    // 设置签名
                    .setSignName(signName)
                    // 设置模板代码（账号密码短信模板）
                    .setTemplateCode(accountTemplateCode)
                    // 设置手机号
                    .setPhoneNumbers(phone)
                    // 设置模板参数（必须是有效的JSON格式）
                    .setTemplateParam(templateParam);
            
            // 运行时选择，可以设置不同的属性来配置运行时环境的参数。
            RuntimeOptions runtime = new RuntimeOptions();
            Client client = new Client(config);
            // 调用阿里云短信API
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            
            String responseCode = sendSmsResponse.getBody().getCode();
            String responseMessage = sendSmsResponse.getBody().getMessage();
            String bizId = sendSmsResponse.getBody().getBizId(); // 业务ID，用于查询发送状态
            
            // 记录完整的响应信息
            log.info("AliSmsConfig.sendLawyerSms API响应详情，phone={}, responseCode={}, responseMessage={}, bizId={}", 
                    phone, responseCode, responseMessage, bizId);
            
            if (!"OK".equals(responseCode)) {
                log.error("AliSmsConfig.sendLawyerSms 短信发送失败，phone={}, userName={}, templateCode={}, templateParam={}, responseCode={}, responseMessage={}, bizId={}", 
                        phone, userName, accountTemplateCode, templateParam, responseCode, responseMessage, bizId);
                return null;
            }
            
            // 即使返回OK，也可能存在其他问题，记录详细信息便于排查
            log.info("AliSmsConfig.sendLawyerSms 短信发送成功（API返回OK），phone={}, userName={}, bizId={}, templateCode={}, templateParam={}", 
                    phone, userName, bizId, accountTemplateCode, templateParam);
            
            // 如果bizId为空，可能是异常情况
            if (bizId == null || bizId.trim().isEmpty()) {
                log.warn("AliSmsConfig.sendLawyerSms 警告：API返回OK但bizId为空，可能存在问题，phone={}, responseMessage={}", 
                        phone, responseMessage);
            }
            
            return 1;
        } catch (Exception e) {
            log.error("AliSmsConfig.sendLawyerSms ERROR phone={}, userName={}, Msg={}", phone, userName, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送商家预约取消短信
     * 模板内容：您在${dateTime},预订了${storeName},的${number}桌位,已被商家取消,取消原因:${info},请您重新预订
     * 模板CODE：SMS_501820954
     * 
     * @param phone        用户手机号
     * @param dateTime     预约时间（格式：2026-01-01 14:00）
     * @param storeName    店铺名称
     * @param tableNumber  桌号名称（如：A01）
     * @param cancelReason 取消原因
     * @return 1-发送成功, null-发送失败
     */
    public Integer sendCancelReservationSms(String phone, String dateTime, String storeName, String tableNumber, String cancelReason) {
        log.info("AliSms.sendCancelReservationSms?phone={}&dateTime={}&storeName={}&tableNumber={}&cancelReason={}", 
                phone, dateTime, storeName, tableNumber, cancelReason);
        try {
            // 参数校验
            if (phone == null || phone.trim().isEmpty()) {
                log.warn("发送商家预约取消短信失败：手机号不能为空");
                return null;
            }
            if (dateTime == null || dateTime.trim().isEmpty()) {
                log.warn("发送商家预约取消短信失败：预约时间不能为空");
                return null;
            }
            if (storeName == null || storeName.trim().isEmpty()) {
                log.warn("发送商家预约取消短信失败：店铺名称不能为空");
                return null;
            }
            if (tableNumber == null || tableNumber.trim().isEmpty()) {
                log.warn("发送商家预约取消短信失败：桌号名称不能为空");
                return null;
            }
            if (cancelReason == null || cancelReason.trim().isEmpty()) {
                log.warn("发送商家预约取消短信失败：取消原因不能为空");
                return null;
            }

            Config config = new Config()
                    .setEndpoint(endPoint)
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret);

            // 构建模板参数JSON，必须符合阿里云短信模板参数格式
            // 模板内容：您在${dateTime},预订了${storeName},的${number}桌位,已被商家取消,取消原因:${info},请您重新预订
            // 变量：dateTime（时间）、storeName（店铺名称）、number（桌号名称）、info（取消原因）
            String templateParam = String.format("{\"dateTime\":\"%s\",\"storeName\":\"%s\",\"number\":\"%s\",\"content\":\"%s\"}",
                    escapeJsonString(dateTime), 
                    escapeJsonString(storeName),
                    escapeJsonString(tableNumber),
                    escapeJsonString(cancelReason));

            // 使用商家预约取消短信模板代码
            String cancelTemplateCode = templatereFundCode;
            if (cancelTemplateCode == null || cancelTemplateCode.trim().isEmpty()) {
                cancelTemplateCode = "SMS_501820954"; // 默认模板代码
            }

            log.info("AliSms.sendCancelReservationSms 准备发送短信，phone={}, dateTime={}, storeName={}, tableNumber={}, cancelReason={}, templateCode={}, templateParam={}", 
                    phone, dateTime, storeName, tableNumber, cancelReason, cancelTemplateCode, templateParam);

            // 构建发送请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    // 设置签名
                    .setSignName(signName)
                    // 设置模板代码（商家预约取消短信模板）
                    .setTemplateCode(cancelTemplateCode)
                    // 设置手机号
                    .setPhoneNumbers(phone)
                    // 设置模板参数（必须是有效的JSON格式）
                    .setTemplateParam(templateParam);
            
            // 运行时选择，可以设置不同的属性来配置运行时环境的参数。
            RuntimeOptions runtime = new RuntimeOptions();
            Client client = new Client(config);
            // 调用阿里云短信API
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            
            String responseCode = sendSmsResponse.getBody().getCode();
            String responseMessage = sendSmsResponse.getBody().getMessage();
            String bizId = sendSmsResponse.getBody().getBizId(); // 业务ID，用于查询发送状态
            
            // 记录完整的响应信息
            log.info("AliSms.sendCancelReservationSms API响应详情，phone={}, responseCode={}, responseMessage={}, bizId={}", 
                    phone, responseCode, responseMessage, bizId);
            
            if (!"OK".equals(responseCode)) {
                log.error("AliSms.sendCancelReservationSms 短信发送失败，phone={}, dateTime={}, storeName={}, tableNumber={}, cancelReason={}, templateCode={}, templateParam={}, responseCode={}, responseMessage={}, bizId={}", 
                        phone, dateTime, storeName, tableNumber, cancelReason, cancelTemplateCode, templateParam, responseCode, responseMessage, bizId);
                return null;
            }
            
            // 即使返回OK，也可能存在其他问题，记录详细信息便于排查
            log.info("AliSms.sendCancelReservationSms 短信发送成功（API返回OK），phone={}, dateTime={}, storeName={}, tableNumber={}, cancelReason={}, bizId={}, templateCode={}, templateParam={}", 
                    phone, dateTime, storeName, tableNumber, cancelReason, bizId, cancelTemplateCode, templateParam);
            
            // 如果bizId为空，可能是异常情况
            if (bizId == null || bizId.trim().isEmpty()) {
                log.warn("AliSms.sendCancelReservationSms 警告：API返回OK但bizId为空，可能存在问题，phone={}, responseMessage={}", 
                        phone, responseMessage);
            }
            
            return 1;
        } catch (Exception e) {
            log.error("AliSms.sendCancelReservationSms ERROR phone={}, dateTime={}, storeName={}, tableNumber={}, cancelReason={}, Msg={}", 
                    phone, dateTime, storeName, tableNumber, cancelReason, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送订金退款短信
     * 短信内容：您预付的订金已返还至您的支付账号,请注意查收
     * 模板CODE：使用 templatereRefundCode 配置
     * 
     * @param phone 用户手机号
     * @return 1-发送成功, null-发送失败
     */
    public Integer sendDepositRefundSms(String phone) {
        log.info("AliSms.sendDepositRefundSms?phone={}", phone);
        try {
            // 参数校验
            if (phone == null || phone.trim().isEmpty()) {
                log.warn("发送订金退款短信失败：手机号不能为空");
                return null;
            }

            Config config = new Config()
                    .setEndpoint(endPoint)
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret);

            // 使用订金退款短信模板代码
            String refundTemplateCode = templatereRefundCode;
            if (refundTemplateCode == null || refundTemplateCode.trim().isEmpty()) {
                log.warn("发送订金退款短信失败：模板代码未配置");
                return null;
            }

            log.info("AliSms.sendDepositRefundSms 准备发送短信，phone={}, templateCode={}", 
                    phone, refundTemplateCode);

            // 构建发送请求
            // 如果模板不需要参数，可以传空JSON对象 {} 或者不传参数
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    // 设置签名
                    .setSignName(signName)
                    // 设置模板代码（订金退款短信模板）
                    .setTemplateCode(refundTemplateCode)
                    // 设置手机号
                    .setPhoneNumbers(phone)
                    // 设置模板参数（如果模板不需要参数，传空JSON对象）
                    .setTemplateParam("{}");
            
            // 运行时选择，可以设置不同的属性来配置运行时环境的参数。
            RuntimeOptions runtime = new RuntimeOptions();
            Client client = new Client(config);
            // 调用阿里云短信API
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            
            String responseCode = sendSmsResponse.getBody().getCode();
            String responseMessage = sendSmsResponse.getBody().getMessage();
            String bizId = sendSmsResponse.getBody().getBizId(); // 业务ID，用于查询发送状态
            
            // 记录完整的响应信息
            log.info("AliSms.sendDepositRefundSms API响应详情，phone={}, responseCode={}, responseMessage={}, bizId={}", 
                    phone, responseCode, responseMessage, bizId);
            
            if (!"OK".equals(responseCode)) {
                log.error("AliSms.sendDepositRefundSms 短信发送失败，phone={}, templateCode={}, responseCode={}, responseMessage={}, bizId={}", 
                        phone, refundTemplateCode, responseCode, responseMessage, bizId);
                return null;
            }
            
            // 即使返回OK，也可能存在其他问题，记录详细信息便于排查
            log.info("AliSms.sendDepositRefundSms 短信发送成功（API返回OK），phone={}, bizId={}, templateCode={}", 
                    phone, bizId, refundTemplateCode);
            
            // 如果bizId为空，可能是异常情况
            if (bizId == null || bizId.trim().isEmpty()) {
                log.warn("AliSms.sendDepositRefundSms 警告：API返回OK但bizId为空，可能存在问题，phone={}, responseMessage={}", 
                        phone, responseMessage);
            }
            
            return 1;
        } catch (Exception e) {
            log.error("AliSms.sendDepositRefundSms ERROR phone={}, Msg={}", phone, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送到店提醒短信
     * 名称：到店提醒。内容：您在${time}预订了${storeName}${tableNumber}的桌位,请您及时到店
     *
     * @param phone       用户手机号
     * @param timeStr     预订开始时间（如 14:00）
     * @param storeName   店铺名称
     * @param tableNumber 桌号或名称（如 A01）
     * @return 1-发送成功, null-发送失败
     */
    public Integer sendArrivalReminderSms(String phone, String timeStr, String storeName, String tableNumber) {
        log.info("AliSms.sendArrivalReminderSms?phone={}, timeStr={}, storeName={}, tableNumber={}",
                phone, timeStr, storeName, tableNumber);
        try {
            if (phone == null || phone.trim().isEmpty()) {
                log.warn("发送到店提醒短信失败：手机号不能为空");
                return null;
            }
            if (timeStr == null || timeStr.trim().isEmpty()) {
                log.warn("发送到店提醒短信失败：预订时间不能为空");
                return null;
            }
            if (storeName == null) {
                storeName = "";
            }
            if (tableNumber == null) {
                tableNumber = "";
            }

            String templateCodeArrival = templateArrivalReminderCode;
            if (templateCodeArrival == null || templateCodeArrival.trim().isEmpty()) {
                log.warn("发送到店提醒短信失败：模板代码未配置 ali.sms.templateArrivalReminderCode");
                return null;
            }

            String templateParam = String.format("{\"time\":\"%s\",\"storeName\":\"%s\",\"tableNumber\":\"%s\"}",
                    escapeJsonString(timeStr),
                    escapeJsonString(storeName),
                    escapeJsonString(tableNumber));

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(signName)
                    .setTemplateCode(templateCodeArrival)
                    .setPhoneNumbers(phone)
                    .setTemplateParam(templateParam);

            Config config = new Config()
                    .setEndpoint(endPoint)
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret);
            RuntimeOptions runtime = new RuntimeOptions();
            Client client = new Client(config);
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);

            String responseCode = sendSmsResponse.getBody().getCode();
            String responseMessage = sendSmsResponse.getBody().getMessage();
            String bizId = sendSmsResponse.getBody().getBizId();

            log.info("AliSms.sendArrivalReminderSms API响应，phone={}, responseCode={}, responseMessage={}, bizId={}",
                    phone, responseCode, responseMessage, bizId);

            if (!"OK".equals(responseCode)) {
                log.error("AliSms.sendArrivalReminderSms 短信发送失败，phone={}, templateParam={}, responseCode={}, responseMessage={}",
                        phone, templateParam, responseCode, responseMessage);
                return null;
            }
            log.info("AliSms.sendArrivalReminderSms 短信发送成功，phone={}, bizId={}", phone, bizId);
            return 1;
        } catch (Exception e) {
            log.error("AliSms.sendArrivalReminderSms ERROR phone={}, timeStr={}, storeName={}, tableNumber={}, Msg={}",
                    phone, timeStr, storeName, tableNumber, e.getMessage(), e);
            return null;
        }
    }

    private String resolveAppTypeStr(Integer appType) {
        if (appType == null) {
            return "store_platform";
        }
        switch (appType) {
            case 0:
                return "user";
            case 1:
                return "store";
            case 2:
                return "store_platform";
            case 3:
                return "lawyer";
            default:
                return "store_platform";
        }
    }

}
