/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.api.dao.TokenDao;
import com.api.entity.TokenEntity;
import com.api.service.TokenService;
import com.doudian.open.core.DoudianOpSpi;
import com.doudian.open.core.DoudianOpSpiBizHandler;
import com.doudian.open.core.DoudianOpSpiContext;
import com.doudian.open.core.GlobalConfig;
import com.doudian.open.spi.demo_spi.DemoSpiRequest;
import com.doudian.open.spi.demo_spi.data.DemoSpiData;
import com.doudian.open.spi.demo_spi.param.DemoSpiParam;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;


@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {
	/**
	 * 12小时后过期
	 */
	private final static int EXPIRE = 3600 * 12;

	@Override
	public TokenEntity queryByToken(String token) {
		return this.getOne(new QueryWrapper<TokenEntity>().eq("token", token));
	}

	@Override
	public TokenEntity createToken(long userId) {
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//生成token
		String token = generateToken();

		//保存或更新用户token
		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(expireTime);
		this.saveOrUpdate(tokenEntity);

		return tokenEntity;
	}

	@Override
	public void expireToken(long userId){
		Date now = new Date();

		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(now);
		this.saveOrUpdate(tokenEntity);
	}

	@Override
	public void testCreateToken(HttpServletRequest httpServletRequest) {
		GlobalConfig.initAppKey("7090080248619877901");
		GlobalConfig.initAppSecret("a4d9d3e6-aa69-4f0c-bffa-be4039e74262");
		String s = DoudianOpSpi.config(DemoSpiRequest.class, this.bizHandler, httpServletRequest).responseJson();

	}
	private final DoudianOpSpiBizHandler bizHandler = new DoudianOpSpiBizHandler() {
		public void handle(DoudianOpSpiContext context) {
			DemoSpiParam param = (DemoSpiParam)context.getParam();
			DemoSpiData data = (DemoSpiData)context.getData();
			context.wrapSuccess();
			context.wrapError(100002L, "系统错误");
		}
	};


	private String generateToken(){
		return UUID.randomUUID().toString().replace("-", "");
	}
}
