package com.huiju.estateagents.third.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.common.MD5Utils;
import com.huiju.estateagents.third.entity.TaThirdPartyMiniappConfig;
import com.huiju.estateagents.third.mapper.TaThirdPartyMiniappConfigMapper;
import com.huiju.estateagents.third.service.ITaThirdPartyMiniappConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *   服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-10-17
 */
@Service
public class TaThirdPartyMiniappConfigServiceImpl extends ServiceImpl<TaThirdPartyMiniappConfigMapper, TaThirdPartyMiniappConfig> implements ITaThirdPartyMiniappConfigService {
	
	@Autowired
	private TaThirdPartyMiniappConfigMapper taThirdPartyMiniappConfigMapper;
	
	/**
	 * 校验是否合法第三方接口调用
	 *
	 * @param tokenHeader
	 * @param appidHeader
	 * @param nowHeader
	 * @return
	 */
	@Override
	public String checkToken(String tokenHeader, String appidHeader, String nowHeader) {
		//秘钥是否过期
		QueryWrapper<TaThirdPartyMiniappConfig> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("appid",appidHeader);
		TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = taThirdPartyMiniappConfigMapper.selectOne(queryWrapper);
//		if (LocalDateTime.now().isAfter(taThirdPartyMiniappConfig.getExpirationDate())){
//			return "秘钥已过期，请重新申请";
//		}
		
		//判断nowHeader是十五分钟之内(15 * 60 * 1000)
		if (System.currentTimeMillis() - Long.valueOf(nowHeader) > (15 * 60 * 1000)){
			return "密钥超时，请在十五分钟内请求";
		}
		
		//重新加密对比
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(taThirdPartyMiniappConfig.getAppid()).append(taThirdPartyMiniappConfig.getAppSecret()).append(nowHeader);
		String token = MD5Utils.md5(MD5Utils.md5(stringBuilder.toString()));
		if (!tokenHeader.equals(token)){
			return "秘钥出错请重新生成";
		}
		
		return "success";
	}
}
