package com.dd.admin.business.api.service.impl;

import com.dd.admin.business.api.domain.PhoneLoginDto;
import com.dd.admin.business.api.service.LoginService;
import com.dd.admin.business.author.entity.Author;
import com.dd.admin.common.exception.ApiException;
import com.dd.admin.common.utils.RedisUtil;
import com.dd.admin.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public String sendSmsCode(String phoneNumber) {
        String redisKey = "SMS_CODE" + phoneNumber;
        String smsCode = String.valueOf(redisUtil.get(redisKey));
        if (StringUtil.isNotEmpty(smsCode)) {
            throw new ApiException("验证码已发送，请稍后再试" + smsCode);
        }
        String code = StringUtil.createCode(4);
        //设置有效时间
//        String json = JavaSmsApi.tplSingleSend(phoneNumber,CODE_TPL_ID, BeanUtil.beanToMap(new SmsCode(code)));

//        Map dataMap = (Map) JSON.parse(json);
//        if(dataMap.get("msg").equals("发送成功")){
        if (true) {
            System.out.println(code);
            redisUtil.set(redisKey, code, 120);
            return code;
        } else {
            throw new ApiException("发送失败");
//            throw new ApiException("发送失败,"+dataMap.get("msg"));
        }
    }

    @Override
    public void checkCode(PhoneLoginDto phoneLogin) {
        String code = phoneLogin.getCode();
        String phoneNumber = phoneLogin.getPhoneNumber();
        String smsCode = String.valueOf(redisUtil.get("SMS_CODE" + phoneNumber));
        //验证验证码是否正确
        if(!code.matches(smsCode)){
            throw new ApiException("验证码有误");
        }
    }

}
