package com.bweb.controller;

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.hai.common.security.VerifyCode;
import com.hai.common.security.VerifyCodeStorage;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.model.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

@RestController
@RequestMapping(value="/sms")
@Api(value="阿里云短信")
public class AliyuncsSmsController {

	Logger log = LoggerFactory.getLogger(AliyuncsSmsController.class);

	@RequestMapping(value="/sendVerificationCode",method= RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "发送验证码")
	public ResponseData sendVerificationCode(@RequestParam(value = "phone", required = true) String phone) {
		try {

			VerifyCode verifyCode = VerifyCodeStorage.getDate(phone);
			String code;
			if (verifyCode != null){
				code = verifyCode.getObject();
			}else{
				// 生成随机6位验证码
				code = String.valueOf(new Random().nextInt(899999) + 100000);
			}
			DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI4FzFiDCZsspxJfQYoHxC", "tkS64fUpgK0Lr2R8ps0AVYRWZloFLl");
			IAcsClient client = new DefaultAcsClient(profile);

			CommonRequest request = new CommonRequest();
			//request.setProtocol(ProtocolType.HTTPS);
			request.setMethod(MethodType.POST);
			request.setDomain("dysmsapi.aliyuncs.com");
			request.setVersion("2017-05-25");
			request.setAction("SendSms");
			request.putQueryParameter("PhoneNumbers", phone);
			request.putQueryParameter("SignName", "银企服");
			request.putQueryParameter("TemplateCode", "SMS_210765573");
			request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");

			//发送短信
			CommonResponse response = client.getCommonResponse(request);
			// 存入VerifyCodeStorage
			verifyCode = new VerifyCode(phone,code);
			VerifyCodeStorage.save(verifyCode);
			return ResponseMsgUtil.success(response.getData());

		} catch (Exception e) {
			return ResponseMsgUtil.exception(e);
		}
	}
}
