package com.zfire.mall.manager.helper;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zfire.mall.manager.config.k3.K3Config;
import com.zfire.mall.manager.config.k3.KingDeeUser;
import com.zfire.mall.manager.logic.k3.K3RequestLogLogic;
import com.zfire.mall.manager.utils.ApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
public class KingDeeInvokeHelper {



	private static String POST_K3CloudURL;

	// Cookie 值
	private static String CookieVal = null;

	private static long ExpTime = 0;

	private static Map map = new HashMap();
	static {
		map.put("Draft",
				"Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Draft.common.kdsvc");
		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("ExecuteBillQuery",
				"Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
		map.put("Delete",
				"Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc");
		map.put("Push",
				"Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push.common.kdsvc");
		map.put("CancelAssign",
				"Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.CancelAssign.common.kdsvc");
		map.put("SaveXSaleOrder",
				"Kingdee.K3.SCM.WebApi.ServicesStub.SaveXSaleOrderWebApi.SaveXSaleOrder.common.kdsvc");
		map.put("ExcuteOperation",
				"Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation.common.kdsvc");
		map.put("BatchSave",
				"Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc");

	}

	public static void setConfigInfo(K3Config k3Config) {
		KingDeeInvokeHelper.POST_K3CloudURL = k3Config.getK3CloudURL();
	}

	// 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 (Objects.nonNull(CookieVal)) {
			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();

		if (paras.size() > 1) {
			String content = paras.getString(1);
			if (content.contains("TakeEffect")) {
				out.writeBytes(paras.getString(1));
				out.flush();
				out.close();

				return connection;
			}
		}

		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;

		String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";

		JSONArray jParas = new JSONArray();
		jParas.add(dbId);// 帐套Id
		jParas.add(user);// 用户名
		jParas.add(pwd);// 密码
		jParas.add(lang);// 语言

		HttpURLConnection connection = initUrlConn(sUrl, 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;
					ExpTime = DateUtil.date().getTime() + 60000;
					break;
				}
			}
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		String line;
		log.info(" ============================= ");
		log.info(" Contents of post request ");
		log.info(" ============================= ");
		while ((line = reader.readLine()) != null) {
			String sResult = new String(line.getBytes(), StandardCharsets.UTF_8);
			log.info(sResult);
			bResult = line.contains("\"LoginResultType\":1");
			if (!bResult) {throw new RuntimeException("登录失败: " + line);}
		}
		log.info(" ============================= ");
		log.info(" Contents of post request ends ");
		log.info(" ============================= ");
		reader.close();

		connection.disconnect();

		return bResult;
	}

	// Save 保存
	public static String Draft(String formId, String content) throws Exception {
		return Invoke("Draft", formId, content, null);
	}

	// Save 保存
	public static String Save(String formId, String content) throws Exception {
		return Invoke("Save", formId, content, null);
	}

	// BatchSave 批量保存
	public static String BatchSave(String formId, String content) throws Exception {
		return Invoke("BatchSave", formId, content, null);
	}

	// View 查看
	public static void View(String formId, String content) throws Exception {
		Invoke("View", formId, content, null);
	}

	// Submit 提交
	public static void Submit(String formId, String content) throws Exception {
		Invoke("Submit", formId, content, null);
	}

	// Audit 审核
	public static void Audit(String formId, String content) throws Exception {
		Invoke("Audit", formId, content, null);
	}

	// CancelAssign 撤消
	public static String Cancel(String formId, String content) throws Exception {
		return Invoke("CancelAssign", formId, content, null);
	}

	// UnAudit 反审核
	public static String UnAudit(String formId, String content) throws Exception {
		return Invoke("UnAudit", formId, content, null);
	}

	// StatusConvert
	public static void StatusConvert(String formId, String content)
			throws Exception {
		Invoke("StatusConvert", formId, content, null);
	}

	// ExecuteBillQuery 表单数据查询
	public static String ExecuteBillQuery(String formId, String content)
			throws Exception {
		return Invoke("ExecuteBillQuery", formId, content, null);
	}

	// Delete 删除
	public static String Delete(String formId, String content)
			throws Exception {
		return Invoke("Delete", formId, content, null);
	}

	// Push 下推
	public static String Push(String formId, String content)
			throws Exception {
		return Invoke("Push", formId, content, null);
	}

	// 销售订单新变更单
	public static String SaveXSaleOrder(String formId, String content)
			throws Exception {
		return Invoke("SaveXSaleOrder", formId, content, null);
	}

	public static String ExcuteOperation(String formId, String content, String type)
			throws Exception {
		return Invoke("ExcuteOperation", formId, content, type);
	}


	private static String Invoke(String deal, String formId, String content, String type)
			throws Exception {
		// 登录超过有效时间时重新登录
		if (DateUtil.date().getTime() > ExpTime) {
			CookieVal = null;
			KingDeeInvokeHelper.Login(KingDeeUser.getDB(), KingDeeUser.getACCOUNT(), KingDeeUser.getPASSWORD(), KingDeeUser.getLANG());
		}
		log.info(Thread.currentThread().getName() + ">>" + deal + " Invoke content: " + content);
		String sUrl = map.get(deal).toString();
		JSONArray jParas = new JSONArray();
		if (StringUtils.isNotBlank(formId)) {
			jParas.add(formId);
		}
		if (StringUtils.isNotBlank(type)) {
			jParas.add(type);
		}
		jParas.add(content);

		HttpURLConnection connectionInvoke = initUrlConn(sUrl, jParas);

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connectionInvoke.getInputStream()));

		String line;
		log.info(" ============================= ");
		log.info(" Contents of post request ");
		log.info(" ============================= ");
		String sResult = "";
		while ((line = reader.readLine()) != null) {
			sResult = new String(line.getBytes(), StandardCharsets.UTF_8);
			log.info(Thread.currentThread().getName() + ">>" +sResult);
		}
		log.info(" ============================= ");
		log.info(" Contents of post request ends ");
		log.info(" ============================= ");
		reader.close();

	/*	ApplicationContextUtils.getBean(K3RequestLogLogic.class).createLog(deal, formId, content, sResult);*/

		connectionInvoke.disconnect();
		return 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;
	}


}
