package com.ruoyi.web.controller.sms;

import javax.servlet.http.HttpServletResponse;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SendSmsUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SendSms;
import com.ruoyi.system.service.ISendSmsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 短信日志Controller
 * 
 * @author ruoyi
 * @date 2023-02-08
 */
@RestController
@RequestMapping("/sms")
public class SendSmsController extends BaseController
{
    @Autowired
    private ISendSmsService sendSmsService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询短信日志列表
     */
    @PreAuthorize("@ss.hasPermi('system:sms:list')")
    @GetMapping("/list")
    public TableDataInfo list(SendSms sendSms)
    {
        startPage();
        List<SendSms> list = sendSmsService.selectSendSmsList(sendSms);
        return getDataTable(list);
    }

    /**
     * 导出短信日志列表
     */
    @PreAuthorize("@ss.hasPermi('system:sms:export')")
    @Log(title = "短信日志", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SendSms sendSms)
    {
        List<SendSms> list = sendSmsService.selectSendSmsList(sendSms);
        ExcelUtil<SendSms> util = new ExcelUtil<SendSms>(SendSms.class);
        util.exportExcel(response, list, "短信日志数据");
    }

    /**
     * 获取短信日志详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sms:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sendSmsService.selectSendSmsById(id));
    }

    /**
     * 新增短信日志
     */
    @PreAuthorize("@ss.hasPermi('system:sms:add')")
    @Log(title = "短信日志", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SendSms sendSms)
    {
        return toAjax(sendSmsService.insertSendSms(sendSms));
    }

    /**
     * 修改短信日志
     */
    @PreAuthorize("@ss.hasPermi('system:sms:edit')")
    @Log(title = "短信日志", businessType = BusinessType.UPDATE)
    @PostMapping("/put")
    public AjaxResult edit(@RequestBody SendSms sendSms)
    {
        return toAjax(sendSmsService.updateSendSms(sendSms));
    }

    /**
     * 删除短信日志
     */
    @PreAuthorize("@ss.hasPermi('system:sms:remove')")
    @Log(title = "短信日志", businessType = BusinessType.DELETE)
	@GetMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sendSmsService.deleteSendSmsByIds(ids));
    }


    /**
     * 单独发送短信的接口
     */
    @PostMapping("/sendSmsOnly")
    public AjaxResult sendSms(@RequestBody SendSms sendSms) {
        String phone = sendSms.getPhone();
        if (StringUtils.isBlank(phone)) {
            return AjaxResult.error("未获取到手机号");
        }
        try {
            // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
            com.aliyun.dysmsapi20170525.Client client = SendSmsUtils.createClient();
            //获取用户验证码
            String verifyKey = CacheConstants.SMS_CODE_KEY + sendSms.getPhone();
            String smsCode = "{\"code\":"+redisCache.getCacheObject(verifyKey)+"}";
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    //手机号码
                    .setPhoneNumbers(phone)
                    //短信签名名称。
                    .setSignName("your_value")
                    //短信模板CODE
                    .setTemplateCode("your_value")
                    //短信模板变量对应的实际值{"name": code}
                    .setTemplateParam(smsCode);
            try {
                // 复制代码运行请自行打印 API 的返回值
                SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
                String code = sendSmsResponse.getBody().code;
                if ("OK".equals(code)) {
                    sendSms.setStatus("发送成功");
                    sendSmsService.insertSendSms(sendSms);
                    return AjaxResult.success("发送成功");
                } else {
                    sendSms.setStatus("发送失败");
                    sendSmsService.insertSendSms(sendSms);
                    return AjaxResult.error(sendSmsResponse.getBody().message);
                }
            } catch (TeaException error) {
                // 如有需要，请打印 error
                com.aliyun.teautil.Common.assertAsString(error.message);
            }
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return AjaxResult.error("发送失败");
    }

    /**
     * 获取四位数短信验证码
     * @param sendSms
     * @return
     */
    @PostMapping("/getCode")
    public AjaxResult getCode(@RequestBody SendSms sendSms) {
        String code = SendSmsUtils.getCode(4);
        String verifyKey = CacheConstants.SMS_CODE_KEY + sendSms.getPhone();
        redisCache.setCacheObject(verifyKey, code, Constants.SMS_EXPIRATION, TimeUnit.MINUTES);
        return AjaxResult.success("获取成功",code);
    }
}
