package com.lutao.cloud.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lutao.cloud.admin.api.dto.PhoneDTO;
import com.lutao.cloud.admin.api.entity.SysUser;
import com.lutao.cloud.admin.mapper.SysUserMapper;
import com.lutao.cloud.admin.service.MobileService;
import com.lutao.cloud.common.core.constant.CacheConstants;
import com.lutao.cloud.common.core.constant.SecurityConstants;
import com.lutao.cloud.common.core.constant.enums.LoginTypeEnum;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.common.core.util.StringUtil;
import com.lutao.cloud.common.security.service.CloudUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

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

/**

 * @date 2018/11/14
 * <p>
 * 手机登录相关业务实现
 */
@Slf4j
@Service
@AllArgsConstructor
public class MobileServiceImpl implements MobileService{

	private final RedisTemplate redisTemplate;

	private final SysUserMapper userMapper;

	/**
	 * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
	 * @param mobile mobile
	 * @return code
	 */
	@Override
	public MessageInfo<Boolean> sendSmsCode(String mobile){
		List<SysUser> userList = userMapper
				.selectList(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, mobile));

		if (CollUtil.isEmpty(userList)){
			log.info("手机号未注册:{}", mobile);
			return MessageInfo.ok(Boolean.FALSE, "手机号未注册");
		}

		Object codeObj = redisTemplate.opsForValue()
				.get(CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile);

		if (codeObj != null){
			log.info("手机号验证码未过期:{}，{}", mobile, codeObj);
			return MessageInfo.ok(Boolean.FALSE, "验证码发送过频繁");
		}

		String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
		log.debug("手机号生成验证码成功:{},{}", mobile, code);
		redisTemplate.opsForValue().set(
				CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile, code,
				SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
		return MessageInfo.ok(Boolean.TRUE, code);
	}


	/**
	 * 发送验证码
	 * @param phoneDTO
	 * @param cloudUser
	 * @return
	 */
	@Override
	public MessageInfo verificode(PhoneDTO phoneDTO,CloudUser cloudUser){
		LocalDateTime localDateTime = LocalDateTime.now();
		log.info("verificode cloudUser:{}",cloudUser);
		String phone = "";
		if (phoneDTO == null){
			phone = cloudUser.getPhone();
		} else{
			phone = phoneDTO.getPhoneNumber();
		}
		String key = getVerificodeKey(phone, cloudUser);
		String code = String.format("%02d%02d",localDateTime.getMonthValue(),localDateTime.getDayOfMonth());
		BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(key);
        /*Object rdCode = boundValueOperations.get();
        if (rdCode != null){
            code = rdCode.toString();
        }*/
		boundValueOperations.set(code,300, TimeUnit.SECONDS);

		return MessageInfo.ok("验证码已发送,5分钟内有效");
	}

	/**
	 * 获取验证码key
	 * @param phone
	 * @param cloudUser
	 * @return
	 */
	public String getVerificodeKey(String phone, CloudUser cloudUser){
		String key = String.format("auth:verificode:%s", phone);
//		if (cloudUser == null) {
//			key =
//		} else {
//			 = String.format("auth:verificode:%s:%s", cloudUser.getId(), phone);
//		}
		return key;
	}


	/**
	 * 注册手机发验证码
	 * @param cloudUser
	 * @return
	 */
	@Override
	public MessageInfo userVerificode(CloudUser cloudUser){
		log.info("userVerificode cloudUser:{}",cloudUser);

		SysUser sysUser = userMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserId,cloudUser.getId()));
		if (sysUser == null || StringUtil.isBlank(sysUser.getPhone())){
			return MessageInfo.failed("请绑定手机");
		}
		return verificode(null,cloudUser);
	}
}
