package cn.myapps.runtime.dynaform.form.controller;

import static com.jayway.jsonpath.JsonPath.parse;

import java.util.ArrayList;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONArray;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.Option;

import cn.myapps.common.auth.IUser;
import cn.myapps.common.controller.Resource;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.util.StringUtil;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.form.service.FormDesignTimeService;
import cn.myapps.runtime.common.controller.AbstractRuntimeController;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.form.ejb.Form;
import cn.myapps.runtime.dynaform.form.ejb.Options;
import cn.myapps.runtime.dynaform.form.ejb.SuggestField;
import cn.myapps.runtime.dynaform.form.ejb.ValidateMessage;
import cn.myapps.runtime.macro.runner.IRunner;
import cn.myapps.runtime.macro.runner.JavaScriptFactory;
import cn.myapps.common.util.cache.MemoryCacheUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = "智能搜索提示框执行模块")
@RequestMapping(value = "/api")
@Component
public class SuggestFieldController extends AbstractRuntimeController {

	/**
	 * 服务器返回搜索提示相关的信息
	 * @param applicationId 软件id
	 * @param formid 表单id
	 * @param docid 文档id
	 * @param content 请求包体
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/runtime/{applicationId}/forms/{formid}/documents/{docid}/querySuggest")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "服务器返回搜索提示相关的信息", notes = "服务器返回搜索提示相关的信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
			@ApiImplicitParam(name = "formid",value = "表单id",required = true,paramType = "path",dataType = "string"),
			@ApiImplicitParam(name = "docid",value = "文档id",required = true,paramType = "path",dataType = "string"),
			@ApiImplicitParam(name = "content",value = "请求包体",required = true,paramType = "body",dataType = "string")
	})
	public Resource querySuggest(@PathVariable String applicationId, @PathVariable String formid,
								 @PathVariable String docid, @RequestBody String content) throws Exception {
		Configuration configuration = Configuration.defaultConfiguration();
		configuration = configuration.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
		DocumentContext parse = parse(content, configuration);

		String parentId = parse.read("$.parentId");
		String formFieldId = parse.read("$.formFieldId");
		String keyword = parse.read("$.keyword");
		if(!StringUtil.isBlank(keyword)){
			keyword = keyword.replace("'", "");
		}

		JSONArray json = null;
		Options options = null;
		ParamsTable params = getParams();
		IUser user = getUser();
		if (docid != null && docid.equals(parentId)) {
			parentId = null;
			params.removeParameter(parentId);
		}

		FormDesignTimeService formService = DesignTimeServiceManager.formDesignTimeService();
		Form form = (Form) formService.doView(formid);
		SuggestField field = (SuggestField) form.findField(formFieldId);
		Document doc = null;

		if (field.getOptionsScript() != null && field.getOptionsScript().trim().length() > 0) {
			if (!StringUtil.isBlank(docid)) {
				doc = (Document) MemoryCacheUtil.getFromPrivateSpace(docid, user);
				if (doc != null) {
					doc.setId(docid);
				}
			} else if (!StringUtil.isBlank(parentId)) {
				doc = (Document) MemoryCacheUtil.getFromPrivateSpace(parentId, user);
			}
			doc = form.createDocument(doc, params, user);

			params.setParameter("_keyword", keyword);

			IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), applicationId);
			runner.initBSFManager(doc, params, user, new ArrayList<ValidateMessage>());
			options = field.getOptions(runner);
			json = options.toJsonSuggest();
		}

		return success("ok", json);
	}
}
