package com.bohuikeji.delivery.backstage.controller.open;

import com.bohuikeji.delivery.backstage.entity.TOpen;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.service.ITOpenService;
import com.bohuikeji.delivery.backstage.util.PageUtil;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.utils.JwtTokenUtil;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

/**
 * 权限的认证接口
 * @author 10552
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/open/auth")
public class AuthOpenApi {
    public static final String APP_KEY="open";
    public static final String APP_SECRET="open";

    final ITOpenService openService;

    /**
     * token有效时间(秒)  4小时
     */
    public static final long FAIL_TIME=14400;
    final RedisUtil redisUtil;

    /**
     * TOKEN 内部类分装
     */
    @Data
    private static class Token implements Serializable {
        String token;
        long second;
        Token(String token,long second){
            this.token=token;
            this.second=second;
        }
    }

    /**
     * 获取token
     * @param appKey
     * @param appSecret
     * @return
     */
    @GetMapping("/get/token")
    APIEntity getToken(String appKey,String appSecret){
        TOpen open=openService.getOpenBySecret(appKey,appSecret);
        if(open==null){
            return APIEntity.fail("【参数错误】[appKey]或[appSecret]错误");
        }
        Object token=redisUtil.get("token:auth:open:id:"+open.getId());
        if(token==null){
            token=JwtTokenUtil.createToken("开放平台",open.getId(),FAIL_TIME);
            //redis提前失效，以保证甲方系统在token继续失效时可以生产新的token
            redisUtil.set("token:auth:open:id:"+open.getId(),token,FAIL_TIME-10);
            return APIEntity.success(new Token(token.toString(),FAIL_TIME-10));
        }
        //返回之前的token及过期时间
        return APIEntity.success(new Token(token.toString(),redisUtil.getExpire("token:auth:open:id:"+open.getId())));
    }


}
