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);
        long costime = System.currentTimeMillis() - start;

        Map<String, Object> map = ThreadLocalConfig.get();
        map.put("costime", costime);
        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;
        }
    }


}
