package com.nzwz.api;

import com.nzwz.config.ThreadLocalConfig;
import kingdee.bos.json.JSONObject;
import kingdee.bos.webapi.client.ApiHttpClient;
import kingdee.bos.webapi.client.ApiRequest;
import kingdee.bos.webapi.client.ApiServiceRequest;
import org.apache.http.client.CookieStore;

import java.util.Map;

/**
 * @author Lnori
 */
public class KingDeeApiClient {
    private String serverUrl;
    private CookieStore cookieStore;

    public KingDeeApiClient(String serverUrl) {
        this.serverUrl = serverUrl;
    }

    public <T> ApiRequest<T> createRequest(String serviceName, Object[] parameters, Class<T> returnType) {
        return new ApiServiceRequest<>(this.serverUrl, this.cookieStore, serviceName, parameters, returnType);
    }

    public <T> T execute(String serviceName, Object[] parameters, Class<T> returnType) throws Exception {
        ApiRequest<T> request = this.createRequest(serviceName, parameters, returnType);
        ApiHttpClient<T> httpClient = new ApiHttpClient<>();
        request.setListener(httpClient);

        long start = System.currentTimeMillis();
        T send = httpClient.Send(request, returnType);
        System.out.println();
        System.out.println("---------->" + send);
        System.out.println();
        long costTime = System.currentTimeMillis() - start;

        Map<String, Object> map = ThreadLocalConfig.get();
        map.put("costTime", costTime);
        ThreadLocalConfig.set(map);

        return send;
    }

    public Boolean login(String dbId, String userName, String password, int lcid) {
        try {
            Object[] loginInfo = new Object[]{dbId, userName, password, lcid};
            ApiRequest<String> request = this.createRequest("Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser", loginInfo, String.class);
            ApiHttpClient<String> httpClient = new ApiHttpClient<>();
            request.setListener(httpClient);
            String ret = httpClient.Send(request, String.class);
            System.out.println(ret);
            int result = (new JSONObject(ret)).getInt("LoginResultType");
            if (result == 1) {
                this.cookieStore = request.getCookieStore();
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}
