package com.dcsoft.system.face.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.CacheConstants;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.redis.service.RedisService;
import com.dcsoft.system.face.service.IIDaasService;
import com.dcsoft.system.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户管理 服务层处理
 *
 * @author xueyi
 */
@Service
public class IDaasServiceImpl implements IIDaasService {

    @Autowired
    private RedisService redisService;

    //@Value("${IDaas.url}")
    public String IDaas;
    //** 资源映射路径 前缀 *//*
    //@Value("${IDaas.apiKey}")
    public String apiKey;
    //@Value("${IDaas.apiSecret}")
    public String apiSecret;

    //获取token值
    @Override
    public String getToken() {
        //通过缓存获取，如果没有就重新获取
        //所有请求 token 及其他参数都写在 header 中
        String verifyKey = CacheConstants.AUTH_KEY + apiKey;
        String token = redisService.getCacheObject(verifyKey);
        if(StringUtils.isEmpty(token)){//重新获取token
            String url=IDaas+"/oauth/token";
            Map<String, Object> headMap=new HashMap<String, Object>();
            headMap.put("client_id",apiKey);
            headMap.put("client_secret",apiSecret);
            headMap.put("scope","read");
            headMap.put("grant_type","client_credentials");
            String response= HttpUtil.sendxwwwform(url,headMap);
            JSONObject json= JSONObject.parseObject(response);
            token=json.get("access_token").toString();
            Long expires=Long.parseLong(json.get("expires_in")+"");
            redisService.setCacheObject(verifyKey,token);
            redisService.expire(verifyKey,expires);
        }
        return token;
    }
    //获取组织机构列表
    @Override
    public String organizationList(Integer start) {
        String token=getToken();
        //start分页开始位置，默认0 limit分页限制条数，默认20
        String url=IDaas+"/api/bff/v1.2/developer/scim/organization/list?start="+start;
        String response= HttpUtil.getDataToken(url,token);
        return response;
    }

    //获取账户列表
    @Override
    public String accountList(Integer start) {
        String token=getToken();
        //start分页开始位置，默认0 limit分页限制条数，默认20
        String url=IDaas+"/api/bff/v1.2/developer/scim/account/list?start="+start;
        String response= HttpUtil.getDataToken(url,token);
        return response;
    }
}
