package com.gree.mall.manager.logic.common;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ClientException;
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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.plus.entity.SmsRecord;
import com.gree.mall.manager.plus.service.SmsRecordService;
import com.gree.mall.manager.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
@Slf4j
public class SMSLogic {

    @Value("${spring.profiles.active}")
    private String profiles;
    @Value("${ali.access.key.id}")
    private String ACCESS_KEY_ID;
    @Value("${ali.access.key.secert}")
    private String ACCESS_KEY_SECERT;
    @Value("${ali.sms.msg.code}")
    private String TEMPLATE_SMS_CODE;

    private static final String smsSignName = "格力客服中心";

    @Resource
    RedisUtil redisUtil;
    @Resource
    SmsRecordService smsRecordService;


    public void sendSms(String constantStr, String mobile, String type, int expireSec) throws Exception {
        //限制不能频繁发送
        this.checkSendTime(constantStr, mobile);

        //6位随机数
        if(!profiles.equals("prd")){
            //记录发送的code
            redisUtil.set(constantStr + mobile, "000000", expireSec);
        } else {
            Random random = new Random();
            int num = (int) (random.nextDouble() * (1000000 - 100000) + 100000);
            String code = String.format("%06d", num);
            HashMap<String, String> map = new HashMap<>();
            map.put("code", code);
            String content = this.send(mobile, TEMPLATE_SMS_CODE, map);

            String beforeDate = DateUtil.formatDate(new Date());
            long count = smsRecordService.count(new LambdaQueryWrapper<SmsRecord>()
                    .eq(SmsRecord::getPhone, mobile)
                    .eq(SmsRecord::getType, type)
                    .ge(SmsRecord::getCreateTime, beforeDate + " 00:00:00")
                    .le(SmsRecord::getCreateTime, beforeDate + " 23:59:59"));
            // 一天内超过10次单一手机号同类型，不再发短信
            if (count > 10) {
                throw new RemoteServiceException("今天发送短信次数超过10次，停止发送！");
            }
            //记录短信内容
            SmsRecord smsRecord = new SmsRecord();
            smsRecord.setPhone(mobile);
            smsRecord.setContent(content);
            smsRecord.setCreateTime(new Date());
            smsRecord.insert();

            //记录发送的code
            redisUtil.set(constantStr + mobile, code, expireSec);
        }
    }

    /**
     * 验证手机号码两次发送的间隔，不能太短
     *
     * @param mobile 手机号码
     * @throws
     */
    private void checkSendTime(String constantStr, String mobile) throws RemoteServiceException {
        String key = constantStr + mobile;
        long expire = redisUtil.getExpire(key);
        if(Constant.SMS_EXPIRE - 60 < expire){
            throw new RemoteServiceException("发送短信间隔时间太短,请耐心等候");
        }

    }

    public String send(String mobile, String templateCode, HashMap<String, String> param) throws ClientException, com.aliyuncs.exceptions.ClientException {
        if(!profiles.equals("prd")){
            log.info("test send msg success mobile :{} ,param:{}",mobile,param);
            return "";
        }

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECERT);
        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("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", smsSignName);  // 需要在平台上添加
        request.putQueryParameter("TemplateCode", templateCode);  // 模版id 需要在拼台上添加

        String content = JSON.toJSONString(param);
        log.info("短信发送的内容" + content + mobile);
        request.putQueryParameter("TemplateParam", content);
        CommonResponse response = client.getCommonResponse(request);
        //打印返回数据
        log.info("短信验证返回数据 ：" + response.getData());

        String dateRes = response.getData();
        Map<String,Object> smsRsp = JSON.parseObject(dateRes);
        //获取数据
        String codeRes = smsRsp.get("Code").toString();
        if(!codeRes.equals("OK")) {
            log.error("短信发送失败,mobile:{}",mobile);
        }
        return content;
    }


}
