package com.cm.common.plugin.service.tree.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.service.tree.ITreeService;
import com.cm.common.utils.http.RestRequestUtil;
import org.apache.commons.collections4.KeyValue;
import org.apache.commons.collections4.keyvalue.DefaultKeyValue;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: TreeServiceImpl
 * @Description: 树结构
 * @Author: WangGeng
 * @Date: 2019-07-02 17:09
 * @Version: 1.0
 **/
@Service
public class TreeServiceImpl implements ITreeService {

    @Override
    public JSONArray listTreeJustList(Map<String, Object> params) throws SearchException {
        String result = getResultResult(params);
        return JSON.parseArray(result);
    }

    @Override
    public JSONArray listTreeCodeSuccessResultData(Map<String, Object> params) throws SearchException {
        String result = getResultResult(params);
        JSONObject resultObject = JSON.parseObject(result);
        if (resultObject.getString(RestRequestUtil.CODE) == null
                || !RestRequestUtil.SUCCESS.equals(resultObject.getString(RestRequestUtil.CODE))) {
            throw new SearchException("请求失败，状态无效");
        }
        return arrayResult(resultObject);
    }

    @Override
    public JSONArray listTreeStateSuccessResultData(Map<String, Object> params) throws SearchException {
        String result = getResultResult(params);
        JSONObject resultObject = JSON.parseObject(result);
        if (resultObject.getString(RestRequestUtil.STATE) == null
                || !RestRequestUtil.SUCCESS.equals(resultObject.getString(RestRequestUtil.STATE))) {
            throw new SearchException("请求失败，状态无效");
        }
        return arrayResult(resultObject);
    }

    /**
     * 获取{result:{data:[]}}结构的结果
     *
     * @param resultObject
     * @return
     * @throws SearchException
     */
    private JSONArray arrayResult(JSONObject resultObject) throws SearchException {
        JSONObject result = resultObject.getJSONObject(RestRequestUtil.RESULT);
        if (result == null) {
            throw new SearchException("请求失败，结果为空");
        }
        JSONArray data = result.getJSONArray(RestRequestUtil.DATA);
        if (data == null) {
            throw new SearchException("请求失败，结果为空");
        }
        return data;
    }

    /**
     * 执行请求，获得请求结果
     *
     * @param params
     * @return
     */
    private String getResultResult(Map<String, Object> params) throws SearchException {
        String apiUri = params.get("apiUri").toString();
        params.remove("apiUri");
        Map<String, Object> requestParams = getRequestParams(params);
        String result = null;
        if (RestRequestUtil.METHOD_GET.equals(requestParams.get("method"))) {
            result = RestRequestUtil.getRestRequest(apiUri, requestParams);
        }
        if (RestRequestUtil.METHOD_POST.equals(requestParams.get("method"))) {
            result = RestRequestUtil.postRestRequestJson(apiUri, requestParams, null);
        }
        if (result == null) {
            throw new SearchException("请求失败，结果为空");
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param defaultParams
     * @return
     */
    private Map<String, Object> getRequestParams(Map<String, Object> defaultParams) {
        List<KeyValue<String, Object>> defaultKeyValues = new ArrayList<>();
        // 取出默认参数
        Map<String, Object> requestParams = new HashMap<>();
        for (Map.Entry<String, Object> keyValue : defaultParams.entrySet()) {
            String key = keyValue.getKey();
            Object value = keyValue.getValue();
            if (key.startsWith(DEFAULT_PARAMS_AND_VALUE)) {
                KeyValue<String, Object> defaultKeyValue = new DefaultKeyValue<>(key.replace(DEFAULT_PARAMS_AND_VALUE, ""), value);
                defaultKeyValues.add(defaultKeyValue);
            } else {
                requestParams.put(key, value);
            }
        }
        // 判断参数中是否有默认参数
        for (KeyValue<String, Object> defaultKeyValue : defaultKeyValues) {
            String defaultKey = defaultKeyValue.getKey();
            boolean noDefaultParams = false;
            for (Map.Entry<String, Object> keyValue : requestParams.entrySet()) {
                String key = keyValue.getKey();
                if (key.equals(defaultKey)) {
                    noDefaultParams = true;
                    break;
                }
            }
            if (!noDefaultParams) {
                requestParams.put(defaultKey, defaultKeyValue.getValue());
            }
        }
        return requestParams;
    }

}
