package com.ruoyi.bst.sms.service.impl;

import java.math.BigDecimal;
import java.util.concurrent.ScheduledExecutorService;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.ruoyi.bst.area.domain.AreaVO;
import com.ruoyi.bst.area.service.AreaService;
import com.ruoyi.bst.balanceLog.domain.enums.BalanceLogBstType;
import com.ruoyi.bst.order.domain.OrderVO;
import com.ruoyi.bst.sms.constants.SmsTemplateCode;
import com.ruoyi.bst.sms.service.SmsService;
import com.ruoyi.common.sms.SmsAliService;
import com.ruoyi.common.sms.SmsSendDTO;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.system.user.service.UserService;

import lombok.extern.slf4j.Slf4j;



@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsAliService smsAliService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private UserService userService;

    @Override
    public void sendOrderWaitVerifyMsg(OrderVO order) {
        AreaVO area = areaService.selectAreaById(order.getAreaId());
        if (area == null || area.getMsgSwitch() == null || !area.getMsgSwitch()) {
            return;
        }
        String mobile = area.getUserPhone();
        if (StringUtils.isBlank(mobile)) {
            return;
        }

        String reason = "订单" + order.getNo() + "还车待审核短信通知，接收手机：" + mobile;

        SmsSendDTO dto = new SmsSendDTO();
        dto.setMobile(mobile);
        dto.setTemplateCode(SmsTemplateCode.ORDER_WAIT_VERIFY);
        JSONObject param = new JSONObject();
        param.put("name", order.getTotalFee());
        dto.setParam(param);
        this.sendAsync(area.getUserId(), reason, dto);
    }

    // 异步发送短信
    private void sendAsync(Long userId, String reason, SmsSendDTO dto) {
        scheduledExecutorService.execute(() -> {
            transactionTemplate.execute(status -> {
                // 扣费
                int rows = userService.subtractBalance(userId, BigDecimal.valueOf(0.1), BalanceLogBstType.SMS, userId, reason, true);
                ServiceUtil.assertion(rows != 1, "短信扣费失败，用户%s余额不足", userId);

                // 发送短信
                SendSmsResponse res = smsAliService.send(dto);
                ServiceUtil.assertion(res == null, "给用户%s发送短信失败，未知原因", userId);
                ServiceUtil.assertion(!"OK".equals(res.getCode()), "给用户%s短信发送失败：%s", userId, res.getMessage());

                return rows;
            });
        });
    }

}
