package com.system.api;

import com.system.config.ThreadLocalConfig;
import com.system.constants.Constants;
import com.system.constants.KingDeeConstants;
import com.system.serializer.SerializerProxy;
import com.system.utils.HttpUtil;
import com.system.utils.JsonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;

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

/**
 * @author Inori
 */
public class KingDeeApiClient {

    /**
     * 金蝶地址
     */
    private String serverUrl;

    /**
     * Cookie
     */
    private String cookieStore;

    /**
     * 金蝶后缀
     */
    private static final String HTTP_SUFFIX = ".common.kdsvc";


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

    @SuppressWarnings("unchecked")
    public <T> T execute(String serviceName, Object[] parameters, Class<T> returnType) throws Exception {
        Map<String, Object> header = new HashMap<>(1);
        header.put("cookie", this.cookieStore);

        Map<String, Object> request = new HashMap<>(1);
        request.put("parameters", parameters);

        String url = serverUrl + serviceName + HTTP_SUFFIX;
        System.out.println("------------>" + url);

        long start = System.currentTimeMillis();
        ResponseEntity<String> responseEntity = HttpUtil.httpPost(url, header, JsonUtil.toString(request));
        long costTime = System.currentTimeMillis() - start;

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

        return (T) (new SerializerProxy()).deserialize(responseEntity.getBody(), returnType);
    }

    public Boolean login(String dbId, String userName, String password, int lcid) {
        try {
            Map<String, Object> request = new HashMap<>(1);
            request.put("parameters", new Object[]{dbId, userName, password, lcid});

            String url = serverUrl + "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser" + HTTP_SUFFIX;
            ResponseEntity<String> responseEntity = HttpUtil.httpPost(url, JsonUtil.toString(request));
            System.out.println(responseEntity.getBody());

            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                Map<String, Object> map = JsonUtil.toMap(responseEntity.getBody(), String.class, Object.class);
                if (!CollectionUtils.isEmpty(map) && Constants.ONE.equals(String.valueOf(map.get(KingDeeConstants.LOGIN_RESULT_TYPE)))) {
                    this.cookieStore = this.getCookieStore(responseEntity);
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private String getCookieStore(ResponseEntity<String> responseEntity) {
        String cookieStore = "";
        Set<String> keys = responseEntity.getHeaders().keySet();
        for (String key : keys) {
            if (key.equalsIgnoreCase(KingDeeConstants.KING_DEE_COOKIE_NAME)) {
                List<String> cookieList = responseEntity.getHeaders().get(key);
                if (!CollectionUtils.isEmpty(cookieList)) {
                    for (String cookie : cookieList) {
                        if (cookie.startsWith(KingDeeConstants.KING_DEE_SESSION_NAME)) {
                            cookieStore = cookie;
                            break;
                        }
                    }
                }
            }
        }
        return cookieStore;
    }


}
