package com.benyun.project.third.kingdee.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class K3cloudUitl {

    public static String POST_K3CloudURL;

    // Cookie 值
    public static String CookieVal = null; //可以存到redis里面,设置有效时长，过期删除，获取不到重新登录，重新存到redis

    private static Map map = new HashMap();
    static {
        map.put("Save","Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
        map.put("View","Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
        map.put("Submit","Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        map.put("Audit","Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        map.put("UnAudit","Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
        map.put("StatusConvert","Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        map.put("Login","Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc");
    }

    // HttpURLConnection
    private static HttpURLConnection initUrlConn(String url, JSONArray paras)
            throws Exception {
        URL postUrl = new URL(POST_K3CloudURL.concat(url));
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        if (CookieVal != null) {
            connection.setRequestProperty("Cookie", CookieVal);
        }
        if (!connection.getDoOutput()) {
            connection.setDoOutput(true);
        }
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());

        UUID uuid = UUID.randomUUID();
        int hashCode = uuid.toString().hashCode();

        JSONObject jObj = new JSONObject();

        jObj.put("format", 1);
        jObj.put("useragent", "ApiClient");
        jObj.put("rid", hashCode);
        jObj.put("parameters", chinaToUnicode(paras.toString()));
        jObj.put("timestamp", new Date().toString());
        jObj.put("v", "1.0");

        out.writeBytes(jObj.toString());
        out.flush();
        out.close();

        return connection;
    }

    // Login
    public static boolean Login(String dbId, String user, String pwd, int lang)
            throws Exception {
        boolean bResult = false;
        JSONArray jParas = new JSONArray();
        jParas.add(dbId);// 帐套Id
        jParas.add(user);// 用户名
        jParas.add(pwd);// 密码
        jParas.add(lang);// 语言
        HttpURLConnection connection = initUrlConn(map.get("Login").toString(), jParas);
        // 获取Cookie
        String key = null;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("Set-Cookie")) {
                String tempCookieVal = connection.getHeaderField(i);
                if (tempCookieVal.startsWith("kdservice-sessionid")) {
                    CookieVal = tempCookieVal;
                    break;
                }
            }
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream(),"utf-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            String sResult = new String(line.getBytes("utf-8"), "utf-8");
            bResult = line.contains("LoginResultType");
        }
        reader.close();
        connection.disconnect();
        return bResult;
    }
    // Save
    public static JSONObject Save(String formId, String content) throws Exception {
        return  k3cloudReq("Save", formId, content);
    }

    // View
    public static JSONObject View(String formId, String content) throws Exception {
        return k3cloudReq("View", formId, content);
    }

    // Submit
    public static JSONObject Submit(String formId, String content) throws Exception {
        return  k3cloudReq("Submit", formId, content);
    }

    // Audit
    public static JSONObject Audit(String formId, String content) throws Exception {
        return k3cloudReq("Audit", formId, content);
    }

    // UnAudit
    public static JSONObject UnAudit(String formId, String content) throws Exception {
        return  k3cloudReq("UnAudit", formId, content);
    }

    // StatusConvert
    public static JSONObject StatusConvert(String formId, String content)
            throws Exception {
        return k3cloudReq("StatusConvert", formId, content);
    }

    private static JSONObject k3cloudReq(String deal, String formId, String content)
            throws Exception {
        String sResult="";
        String sUrl = map.get(deal).toString();
        JSONArray jParas = new JSONArray();
        jParas.add(formId);
        jParas.add(content);
        HttpURLConnection connectionInvoke = initUrlConn(sUrl, jParas);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream(),"utf-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes("utf-8"), "utf-8");
        }
        reader.close();
        connectionInvoke.disconnect();
        return JSONObject.parseObject(sResult);
    }

    /**
     * 把中文转成Unicode码
     * @param str
     * @return
     */
    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }
}
