package com.cm.common.plugin.oauth.service.menu.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cm.common.base.AbstractService;
import com.cm.common.component.OAuthRestTemplateComponent;
import com.cm.common.component.SecurityComponent;
import com.cm.common.config.properties.ApiPathProperties;
import com.cm.common.exception.AccessTokenException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.IApiConsts;
import com.cm.common.plugin.oauth.service.menu.IMenuService;
import com.cm.common.plugin.oauth.token.ClientTokenManager;
import com.cm.common.plugin.utils.RestTemplateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: MenuServiceImpl
 * @Description: 菜单
 * @Author: WangGeng
 * @Date: 2019/4/22 2:07 PM
 * @Version: 1.0
 **/
@Service
public class MenuServiceImpl extends AbstractService implements IMenuService {

    @Autowired
    private OAuth2ClientProperties oAuth2ClientProperties;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    private OAuthRestTemplateComponent oAuthRestTemplateComponent;
    @Autowired
    private ApiPathProperties apiPathProperties;
    @Autowired
    private SecurityComponent securityComponent;

    @Override
    public JSONArray listMenu(Map<String, Object> params) throws AccessTokenException, SearchException {
        String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_MENU, apiPathProperties.getUserCenter(), oAuth2ClientProperties.getClientId()), params);
        if (result == null) {
            throw new AccessTokenException("认证失败");
        }
        if (result.isEmpty()) {
            throw new SearchException("获取列表失败");
        }
        JSONObject resultObj = JSONObject.parseObject(result);
        return resultObj.getJSONArray("data");
    }

    @Override
    public JSONArray listMenuOfMine() throws AccessTokenException, SearchException {
        Map<String, Object> params = new HashMap<>(1);
        params.put(IApiConsts.ACCESS_TOKEN, ClientTokenManager.getInstance().getClientToken().getAccessToken());
        String result = restTemplateUtil.doGetFormNormal(String.format(IApiConsts.LIST_MENU_BY_USER, apiPathProperties.getUserCenter(), oAuth2ClientProperties.getClientId(), securityComponent.getCurrentUser().getUserId()), params);
        if (result == null) {
            throw new AccessTokenException("认证失败");
        }
        if (result.isEmpty()) {
            throw new SearchException("获取列表失败");
        }
        JSONObject resultObj = JSONObject.parseObject(result);
        return resultObj.getJSONArray("data");
    }


}
