package com.api.mobilemode.web.mobile.service;

import com.api.doc.detail.service.DocViewPermission;
import com.api.doc.detail.util.DocDownloadCheckUtil;
import com.api.doc.mobile.systemDoc.service.impl.ImageFileServiceImpl;
import com.api.doc.mobile.systemDoc.util.DocDetailUtil;
import com.api.mobilemode.util.BasicHandler;
import com.api.mobilemode.util.FieldHandler;
import com.api.mobilemode.web.mobile.ActionMapping;
import com.api.mobilemode.web.mobile.BaseMobileAction;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.cube.biz.CodeBuilder;
import com.engine.mobilemode.biz.json.MJSONObject;
import com.weaver.formmodel.constant.Constants;
import com.weaver.formmodel.data.manager.CustomSearchManager;
import com.weaver.formmodel.data.manager.FormInfoManager;
import com.weaver.formmodel.data.model.CustomSearch;
import com.weaver.formmodel.data.model.Formfield;
import com.weaver.formmodel.exception.MobileModeException;
import com.weaver.formmodel.mobile.MobileFileUpload;
import com.weaver.formmodel.mobile.mec.model.MobileExtendComponent;
import com.weaver.formmodel.mobile.mec.service.MECService;
import com.weaver.formmodel.mobile.security.SecurityUtil;
import com.weaver.formmodel.mobile.ui.manager.MobileAppUIManager;
import com.weaver.formmodel.mobile.ui.model.AppFormUI;
import com.weaver.formmodel.mobile.utils.AttachUtil;
import com.weaver.formmodel.mobile.utils.BrowserUtil;
import com.weaver.formmodel.mobile.utils.MobileCommonUtil;
import com.weaver.formmodel.mobile.utils.TextUtil;
import com.weaver.formmodel.util.NumberHelper;
import com.weaver.formmodel.util.SQLParseHelper;
import com.weaver.formmodel.util.StringHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.formmode.dao.ModelInfoDao;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.servicefiles.DataSourceXML;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class MobileCommonAction extends BaseMobileAction{
	private static final long serialVersionUID = -268583277882617838L;
	
	public MobileCommonAction(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
	}

	/**
	 * 解析字段联动值
	 * 
	 * @return
	 */
	@ActionMapping(name="getFieldTriggerValue")
	public List<Map<String, Object>> getFieldTriggerValue(){
		RecordSet recordSet = new RecordSet();
		String datasource = Util.null2String(getParameter("datasourcename"));
		String fromTable = ""; 
		String whereClause = "";
		int entryId = Util.getIntValue(getParameter("entryId"), -1);
		String fromTableids = Util.null2String(getParameter("fromTable"));
		List<String> fromTableidsList = StringHelper.string2ArrayList(fromTableids, ",");
		
		String sql = "select a.entryid,a.whereclause,b.id,b.DataInputID,b.TableName,b.alias from modeDataInputmain a,modeDataInputtable b where a.id=b.datainputid and a.entryID=? order by b.id asc";
		recordSet.executeQuery(sql, entryId);
		List<String> textTypeFields = new ArrayList<>();
		RecordSet fieldRcord = new RecordSet();
		String DBtype = fieldRcord.getDBType();
		while(recordSet.next()){
			String dataInputtableid = recordSet.getString("id");
			if(!fromTableidsList.contains(dataInputtableid)) continue;
			
			String itemFromTable = recordSet.getString("tablename");
			String alias = Util.null2String(recordSet.getString("alias"));
			fieldRcord.executeQuery("select a.fieldname from workflow_billfield a, workflow_bill b where a.billid = b.id and a.fielddbtype = 'text' and b.tablename = ?", itemFromTable);
			while(fieldRcord.next()) {
				String textFieldname = fieldRcord.getString("fieldname");
				if (!"".equals(alias)) {
					textFieldname = (alias+"."+textFieldname);
				}
				textTypeFields.add(textFieldname);
			}
			if(!"".equals(alias)) itemFromTable += " " + alias;
			fromTable += itemFromTable + ",";
			whereClause = Util.null2String(recordSet.getString("whereclause"));
		}
		if(!"".equals(fromTable)) fromTable = fromTable.substring(0, fromTable.length()-1);
		if("".equals(whereClause)) whereClause = " 1=1 ";
		
		//取值字段为查询条件
		JSONArray asArr;
		String triggerConditionjsonArr = Util.null2String(getParameter("triggerConditionjsonArr"));
		if(triggerConditionjsonArr.trim().equals("")){
			asArr = new JSONArray();
		}else{
			asArr = JSONArray.fromObject(triggerConditionjsonArr);
		}
		//赋值字为查询字段
		String regex = "^[\u4e00-\u9fa5 a-z0-9A-Z_]*$";
		String triggerJsonArr = Util.null2String(getParameter("triggerJsonArr"));
		String searchField = "";
		if(triggerJsonArr.trim().equals("")){
			searchField = " * ";
		}else{
			try{
			    StringBuilder sb = new StringBuilder();
				JSONArray searchFieldArr = JSONArray.fromObject(triggerJsonArr);
				for(int i = 0; i < searchFieldArr.size(); i++){
					JSONObject fieldObj = searchFieldArr.getJSONObject(i);
					String fieldname = Util.null2String(fieldObj.get("name"));
					String fieldid = Util.null2String(fieldObj.get("id"));
					if(!Pattern.matches(regex, fieldid)) throw new MobileModeException(MobileCommonUtil.getHtmlLabelName(383777, user.getLanguage(), "fieldid参数不合法："+fieldid)); 
					if(!Pattern.matches(regex, fieldname)) throw new MobileModeException(MobileCommonUtil.getHtmlLabelName(383777, user.getLanguage(), "fieldname参数不合法："+fieldname)); 
					
					String alias = Util.null2String(fieldObj.get("alias"));
					sb.append("".equals(alias) ? fieldname : alias + "." + fieldname).append(" ").append(fieldid).append(",");
				}
				searchField = sb.substring(0, sb.length() - 1);
			}catch(Exception e){
				searchField = " * ";
				new BaseBean().writeLog(e.getMessage());
			}
		}
		
		StringBuilder sqlBuilder = new StringBuilder();
		sqlBuilder.append("select ").append(searchField).append(" from ").append(fromTable).append(" where ").append(whereClause);
		for(int i = 0;i < asArr.size();i++){
			JSONObject jsonObject = asArr.getJSONObject(i);
			String alias = StringHelper.null2String(jsonObject.get("alias"));
			String nameN = StringHelper.null2String(jsonObject.get("name"));
			String conditions = StringHelper.null2String(jsonObject.get("conditions"));//联动条件设置
			if(StringHelper.isNotEmpty(alias)){
				nameN = alias + "." + nameN;
			}
			String valueN = StringHelper.null2String(jsonObject.get("value"));
			if (textTypeFields.contains(nameN)) {
				nameN = " cast(" + nameN + " as varchar)";
			}
			if("".equals(valueN)){
				sqlBuilder.append(" and (").append(nameN).append("='' or ").append(nameN).append(" is null)");
			}else{
				if("1".equals(conditions)){//属于
					sqlBuilder.append(" and ").append(nameN).append(" in (").append(valueN).append(")");
				} else {
					if(DBtype.equals("postgresql")){//当数据库类型为postgreSQL时单独处理
						sqlBuilder.append(" and ").append(nameN).append(" = '").append(valueN).append("'");
					}else{
						sqlBuilder.append(" and ").append(nameN).append(" like '").append(valueN).append("'");
					}

				}
			}
		}
		sql = sqlBuilder.toString();
		Map<String,String> fieldAliasMap = new HashMap<>();
		boolean flag = MobileCommonUtil.analysisPwd( sql, datasource, fieldAliasMap );
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		if(!"".equals(datasource) && !DataSourceXML.SYS_LOCAL_POOLNAME.equals(datasource)){
			recordSet.executeSqlWithDataSource(sql, datasource);
		}else{
			recordSet.execute(sql);
		}
		BaseBean zxlog = new BaseBean();
		zxlog.writeLog("----2022120701ZXCS----:"+sql+"|| DBtype:"+DBtype);
		String[] columnNames = recordSet.getColumnName();
		while(recordSet.next()){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			for(String columnName : columnNames){
				String columnValue = MobileCommonUtil.formatMultiLang(recordSet.getString(columnName), user);
				if(flag && ("password".equals(columnName.toLowerCase() ) || Util.null2String(fieldAliasMap.get(columnName.toLowerCase())).toLowerCase().contains("password"))){
					columnValue = "";
				}
				resultMap.put(columnName, columnValue);
			}
			resultList.add(resultMap);
		}
		return resultList;
	}

	@ActionMapping(name="getCalendarCondition")
	public String getCalendarCondition() {
		String condition = "";
		String columns = Util.null2String(this.getRequest().getParameter("columns"));
		if(!columns.equals("")){
			try {
				columns = URLDecoder.decode(columns, "utf-8");
				JSONArray columnArr = JSONArray.fromObject(columns);
				if(columnArr.size() > 0){
					//日期条件
					condition += "(";
					for(int i = 0; i < columnArr.size(); i++){
						JSONObject columnObj = (JSONObject)columnArr.get(i);
						String name = Util.null2String(columnObj.get("name"));
						String value = Util.null2String(columnObj.get("value"));
						String opt = Util.null2String(columnObj.get("opt"));
						String fieldType = Util.null2String(columnObj.get("fieldType"));
						boolean valueIsField = fieldType.equals("valueIsField");
						String optStr = "";
						String dateTimeValue = value;
						if(opt.equals("equalTo")){
							//只有e8使用了
							optStr = "=";
						}else if(opt.equals("lessThanEqualTo")){
							optStr = "<=";
							//时间日期字段或者来源为sql时type为""
							if ((fieldType.equals("290") || fieldType.equals("")) && !valueIsField){
								dateTimeValue += " 23:59:59";
							}
						}else if(opt.equals("greaterThanEqualTo")){
							optStr = ">=";
							//数据库比较字符串大小是一个一个字符比较的，因此2019-12-12是小于2019-12-12 00:00:00的。此处只对时间日期类型处理即可。
							if (fieldType.equals("290")){
								dateTimeValue += " 00:00:00";
							}
						}
						String singleMark = valueIsField ? "" : "'";
						condition += name + optStr + singleMark + dateTimeValue + singleMark;
						if(i != (columnArr.size() - 1)){
							condition += " and ";
						}
					}
					condition += ")";
					condition = SecurityUtil.encrypt(condition);
				}
			} catch (Exception e) {
				writeLog(e);
			}
		}
		
		return condition;
	}
	

	
	@ActionMapping(name="getImgMeta", returnKey="datas")
	public JSONArray getImgMeta() throws Exception{
		JSONArray datas = new JSONArray();
		String items = Util.null2String(getParameter("items")).trim();
		JSONArray imgArr = new JSONArray();
		if(StringHelper.isNotEmpty(items)){
		    try{
	            imgArr = JSONArray.fromObject(items);
	        }catch(Exception e){
	            e.printStackTrace();
	        }
		}
		int size = imgArr.size();
		for(int i = 0; i < size; i++){
			JSONObject imgObj = imgArr.getJSONObject(i);
			int index = Util.getIntValue(Util.null2String(imgObj.get("index")));
			String imgPath = Util.null2String(imgObj.get("src"));
			if(imgPath.trim().equals("")){
				continue;
			}

			String fileid = "";
			boolean isID = false;
			if(imgPath.indexOf("/weaver/weaver.file.FileDownload?fileid=") != -1){
				fileid = MobileCommonUtil.getParamInUrl(imgPath, "fileid");
				isID = true;
			}else if(imgPath.indexOf("/mobile/plugin/Download.jsp?sessionkey=") != -1){
				fileid = MobileCommonUtil.getParamInUrl(imgPath, "url");
				isID = true;
			}else if(imgPath.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$")){
				fileid = imgPath;
				imgPath = "/weaver/weaver.file.FileDownload?fileid=" + fileid;
				isID = true;
			}
			boolean isUrl = !isID && !imgPath.equals("");
			
			InputStream inStream = null;
			if(isID){
			    fileid = DocDownloadCheckUtil.getDownloadfileidstr(fileid);
				ImageFileManager fileManager = new ImageFileManager();
				fileManager.getImageFileInfoById(Util.getIntValue(fileid));
				String fileType = fileManager.getImageFileType();
				if(!fileType.contains("image")){ //过滤掉不是图片的附件
					continue;
				}
				inStream = ImageFileManager.getInputStreamById(Util.getIntValue(fileid));
			}else if(isUrl){
				String realPath = getRequest().getSession().getServletContext().getRealPath(imgPath);
				File file = new File(realPath);
				if(file.exists() && file.isFile()){
					inStream = new BufferedInputStream(new FileInputStream(file));
				}
			}
			if (imgPath != null && imgPath.startsWith("/") && !imgPath.startsWith(weaver.general.GCONST.getContextPath())) {
				imgPath = weaver.general.GCONST.getContextPath() + imgPath;
			}
			
			JSONObject d = new JSONObject();
			d.put("src", imgPath);
			d.put("w", "200"); //如果是外网图片或者资源不存在，需设置默认高度和宽度，否则PhotoSwipejs会加载异常
			d.put("h", "200");
			if(inStream != null){
				try{
				
					/*使用ByteArrayOutputStream读取inStream,相当于缓存复制一份inStream。下面用的时候不能因为try中的代码干扰catch中的代码*/
					ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len;
					while ((len = inStream.read(buffer)) > -1 ) {
						byteArrayOutputStream.write(buffer, 0, len);
					}
					byteArrayOutputStream.flush();	  
		
					BufferedImage inputBufImage = null;
					try{
						inputBufImage = ImageIO.read(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
					}catch(Exception ex){
					    ex.printStackTrace();
					}
					
					int width = inputBufImage.getWidth();
					int height = inputBufImage.getHeight();
					
					d.put("w", width);
					d.put("h", height);
				}catch(Exception ex){
					//如果IO流对应的文件不是图片，文件流获取图片信息会失败，需要捕获该异常
				    ex.printStackTrace();
				}
			}
			d.put("index", index);
			datas.add(d);
			
		}
		return datas;
	}
	
	@ActionMapping(name="runSQL")
	public JSONObject runSQL() {
		JSONObject result = new JSONObject();
		FileUpload fileUpload = new MobileFileUpload(this.getRequest(), "UTF-8", false);
		
		String datasource = Util.null2String(fileUpload.getParameter("datasource"));
		datasource = ("".equals(datasource)) ? null : datasource;
		
		String sql = Util.null2String(fileUpload.getParameter("content"));
		sql = SecurityUtil.decrypt(sql);
		if(!MobileCommonUtil.isSafeSql(sql, datasource)){//sql不安全
			result.put("status", "0");
			result.put("result", "false");
			return result;
		}
		
		sql = BasicHandler.replaceVariables(sql, user, pageParam);
		sql = BasicHandler.replaceServerVariables(sql);
		
		String tmpSQL = sql.toLowerCase().trim();
		boolean isNotQuery = tmpSQL.startsWith("insert") || tmpSQL.startsWith("update") || tmpSQL.startsWith("delete");
		
		String sqlParams = MobileCommonUtil.decompressByLZ(Util.null2String(fileUpload.getParameter("sqlParams")));
		JSONArray sqlParamArray = StringHelper.isEmpty(sqlParams) ? new JSONArray() : JSONArray.fromObject(sqlParams);
		
		Object[] paramArr = new Object[sqlParamArray.size()];
		for(int i = 0; i < sqlParamArray.size(); i++){
			Object p = sqlParamArray.get(i);
			if(p instanceof String){
				p = TextUtil.escapeHtml((String)p);
			}
			paramArr[i] = p;
		}
		
		/*处理in的情况，方便前台调用*/
		String inStr = " in (?)";
		int inIndex = -1;
		while((inIndex = sql.indexOf(inStr)) != -1){
			String beforeStr = sql.substring(0, inIndex);
			String currStr = sql.substring(inIndex, inIndex + inStr.length());
			String afterStr = sql.substring(inIndex + inStr.length(), sql.length());
			
			int countOfBefore = (beforeStr.length() - beforeStr.replace("?", "").length());
			Object currValue = paramArr[countOfBefore];
			currStr = currStr.replace("?", Util.null2String(currValue));
			paramArr = MobileCommonUtil.deleteArrayElement(paramArr, countOfBefore);
			
			sql = beforeStr + currStr + afterStr;
		}

		Map<String,String> fieldAliasMap = new HashMap<>();
		RecordSet rs = new RecordSet();
		boolean flag = MobileCommonUtil.analysisPwd(sql, datasource, fieldAliasMap);

		/*针对查询增加分页限制*/
		if(!isNotQuery){
			String dbType = rs.getDBType(datasource);
			if("oracle".equalsIgnoreCase(dbType)){
				sql = "select T.* from ("+sql+") T where rownum <= 100";
			}else if(dbType.startsWith("mysql")){
				if(!sql.toLowerCase().contains(" limit ")){
					sql = sql + " limit 100";
				}
			}
			else if("postgresql".equalsIgnoreCase(dbType)){
				if(!sql.toLowerCase().contains(" limit ")){
					sql = sql + " limit 100";
				}
			}
			else if("db2".equalsIgnoreCase(dbType)){
				if(!sql.toLowerCase().contains(" fetch first ")){
					sql = "select T.* from ("+sql+") T fetch first 100 rows only";
				}
			}
			else if ("sqlserver".equalsIgnoreCase(dbType)) {
				//解析sql
				int selectIndex = sql.toLowerCase().indexOf("select ");
				int fromIndex = sql.toLowerCase().indexOf(" from");
				if(fromIndex > 0){
					List<String> sqlParts = SQLParseHelper.formatAndSplit(sql, datasource);
					Optional<String> orderByOpt = sqlParts.stream().filter(s -> s.toLowerCase().indexOf("order by") == 0).findFirst();
					String orderBy = orderByOpt.isPresent() ? orderByOpt.get() : "";
					int topIndex = sql.substring(selectIndex, fromIndex).toLowerCase().indexOf(" top ");
					if (StringHelper.isNotEmpty(orderBy) && topIndex == -1) {
						//如果最外层sql有 order by且无top关键字，此处对sql进行处理加上 Top 100
						sql = "select top 100 "+sql.substring(6);
					} else {
						sql = "select top 100 T.* from ("+sql+") T";
					}
				}
			} else {
				sql = "select top 100 T.* from ("+sql+") T";
			}
		}
		
		boolean isSuccess = rs.executeSql(sql, !isNotQuery, datasource, paramArr);
		
		result.put("status", isSuccess ? "1" : "0");
		if(isNotQuery){
			result.put("result", isSuccess);
		}else{
			List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
			String[] columnNames = rs.getColumnName();
			while(rs.next()){
				Map<String, Object> resultMap = new HashMap<String, Object>();
				for(String columnName : columnNames){
					String columnValue = MobileCommonUtil.formatMultiLang(rs.getString(columnName), user);
					String columnNameLower = columnName.toLowerCase();
					String colrmnNameUpper = columnName.toUpperCase();
					if(flag && ("password".equals(columnName. toLowerCase() ) || Util.null2String(fieldAliasMap.get(columnName.toLowerCase())).toLowerCase().contains("password"))){
						columnValue = "";
					}
					resultMap.put(columnName, columnValue);
					if(columnName.equals(columnNameLower)){
						resultMap.put(colrmnNameUpper, columnValue);
					}else if(columnName.equals(colrmnNameUpper)){
						resultMap.put(columnNameLower, columnValue);
					}else{
						resultMap.put(colrmnNameUpper, columnValue);
						resultMap.put(columnNameLower, columnValue);
					}
				}
				resultList.add(resultMap);
			}
			result.put("result", JSONArray.fromObject(resultList));
		}
		return result;
	}
	
	@ActionMapping(name="getCustomSearchFieldMeta")
    public MJSONObject getCustomSearchFieldMeta() throws Exception{
	    MJSONObject resultObj = new MJSONObject();
	    MobileExtendComponent mecObj = getMecObjFromRequest();
	    JSONArray asFields = (JSONArray) mecObj.getMecparam("advancedSearchColumns");
	    JSONObject sourceData = (JSONObject) mecObj.getMecparam("sourceData");
        int sourceType = Util.getIntValue(Util.null2String(sourceData.get("sourceType")), 1);
	    if(sourceType != 1 && asFields != null && asFields.size() > 0){
	        for(int i = 0; i < asFields.size(); i++){
                JSONObject searchFieldObj = asFields.getJSONObject(i);
                String id = Util.null2String(searchFieldObj.get("id"));
                JSONObject customFieldJson = (JSONObject) searchFieldObj.get("fieldJson");
                int fieldtype = Util.getIntValue(Util.null2String(customFieldJson.get("fieldtype")));
                int dataType = Util.getIntValue(Util.null2String(customFieldJson.get("sourcetype")));
                if(fieldtype == 5 && dataType == 2){
                    String datasource = Util.null2String(customFieldJson.get("datasource"));
                    String sql = Util.null2String(customFieldJson.get("sql"));
                    sql = BasicHandler.replaceVariables(sql, user, pageParam);
                    RecordSet rs = new RecordSet();
                    boolean isSuccess = false;
                    if (!"".equals(datasource) && !DataSourceXML.SYS_LOCAL_POOLNAME.equals(datasource)) {
                        isSuccess = rs.executeQueryWithDatasource(sql, datasource);
                    } else {
                        isSuccess = rs.executeQuery(sql);
                    }
                    if(isSuccess){
                        JSONArray fieldDatas = new JSONArray();
                        List<String> columnNames = Arrays.asList(rs.getColumnName());
                        while(rs.next()){
                            JSONObject jsonObj = new JSONObject();
                            String name;
                            String value;
                            if(columnNames.contains("name")){
                                name = rs.getString("name");
                            }else{
                                name = rs.getString(1);
                            }   
                            if(columnNames.contains("value")){
                                value = rs.getString("value");
                            }else{
                                value = rs.getString(2);
                            }
                            
                            jsonObj.put("selectname", MobileCommonUtil.formatMultiLang(name, user));
                            jsonObj.put("selectvalue", value);
                            fieldDatas.add(jsonObj);
                        }
                        resultObj.put(id, fieldDatas);
                    }
                }
            }
	    }
	    return resultObj;
	}
	
	@ActionMapping(name="getSearchFieldMeta", returnKey="datas")
	public JSONArray getSearchFieldMeta() throws Exception{
		JSONArray fieldMetaArr = new JSONArray();

		String browser = Util.null2String(getParameter("browser"));
		if(StringHelper.isNotEmpty(browser)){// 浏览框高级搜索
			List<Formfield> formFields = BrowserUtil.getCubeBrowserSearchField(browser, user.getLanguage());
			formFields.forEach(f -> {
				fieldMetaArr.add(FieldHandler.parseFormfieldForSearch("", f, user));
			});
			return fieldMetaArr;
		}

		String id = Util.null2String(getParameter("id"));
		int searchid = Util.getIntValue(getParameter("searchid"));
		JSONArray asConfigArr = new JSONArray();
		int formid = 0;
		if(searchid != -1){
			try{
				String advancedSearchContent = Util.null2String(getParameter("conditions")).trim();
				asConfigArr = JSONArray.fromObject(advancedSearchContent);
				CustomSearchManager searchManager = CustomSearchManager.getInstance();
				CustomSearch customSearch = searchManager.getCustomSearch(searchid);
				formid = customSearch.getFormid();
			}catch(Exception e){
				e.printStackTrace();
			}
		}else{
			MECService mecService = new MECService();
			MobileExtendComponent mecObj = mecService.getMecById(id);
			int source = Util.getIntValue(Util.null2String(mecObj.getMecparam("source")));
			MobileAppUIManager mobileAppUIManager = MobileAppUIManager.getInstance();
			AppFormUI appFormUI = mobileAppUIManager.getById(source);
			String advancedSearchContent = Util.null2String(mecObj.getMecparam("advancedSearchContent")).trim();
			asConfigArr = JSONArray.fromObject(advancedSearchContent);
			if(appFormUI != null && !advancedSearchContent.equals("")){
				formid = appFormUI.getFormId();
			}
		}
		if(formid != 0){
			Map<Integer,Formfield> fieldMap = FormInfoManager.getInstance().getFieldMap(formid);
			Map<Integer, Integer> childFieldMap = new HashMap<>();
			for (int i = 0; i < asConfigArr.size(); i++) {
				JSONObject asConfigObj = (JSONObject)asConfigArr.get(i);
				int fid = Util.getIntValue(Util.null2String(asConfigObj.get("fieldid")));
				Formfield fd = fieldMap.get(fid);
				String htmltype = fd.getFieldhtmltype();
				if ("5".equals(htmltype)) {
					int fieldid = fd.getId();
					Integer childfieldid = fd.getChildfieldid();
					if (childfieldid != null && childfieldid > 0) {
						childFieldMap.put(childfieldid, fieldid);
					}
				}
			}
			for(int i = 0; i < asConfigArr.size(); i++){
				JSONObject asConfigObj = (JSONObject)asConfigArr.get(i);
				String fieldname = Util.null2String(asConfigObj.get("field"));
				int fid = Util.getIntValue(Util.null2String(asConfigObj.get("fieldid")));
				Formfield formfield = fieldMap.get(fid);
				if(formfield == null){//兼容老数据
					for(Entry<Integer, Formfield> entry : fieldMap.entrySet()){
						Formfield fd = entry.getValue();
						String currfield = fd.getFieldname();
						if(StringHelper.isNotEmpty(fd.getDetailtable())){
							currfield = Constants.DETAILTABLE_ALIAS + "." + currfield;
						}
						if(fieldname.equalsIgnoreCase(currfield)){
							formfield = fd;
							break;
						}
					}
				}
				if(formfield == null){	//字段匹配不到
					continue;
				}

				formfield.setLabelName(Util.null2String(asConfigObj.get("showname")));
				fieldMetaArr.add(FieldHandler.parseFormfieldForSearch(String.valueOf(searchid), formfield, childFieldMap, user));
			}
		}
		return fieldMetaArr;
	}
	
	@ActionMapping(name="selectChange", returnKey="datas")
	protected JSONArray getChildSelectValue(){
		JSONArray result = new JSONArray();
		
		int fieldid = Util.getIntValue(getParameter("fieldid"));
		int childfieldid = Util.getIntValue(getParameter("childfieldid"));
		String selectvalue = Util.null2String(getParameter("selectvalue"));
		if(fieldid != -1 && childfieldid != -1 && StringHelper.isNotEmpty(selectvalue)){
			RecordSet rs = new RecordSet();
			String sql = "";
			sql = "select childitemid from workflow_selectitem where fieldid="+fieldid+" and isbill=1 and selectvalue="+selectvalue;
			rs.execute(sql);
			if(rs.next()){
				String childitemid = Util.null2String(rs.getString("childitemid"));
				if(!"".equals(childitemid.trim())){
					if(!"".equals(childitemid)){
						if(childitemid.indexOf(",")==0){
							childitemid = childitemid.substring(1);
						}
						if(childitemid.endsWith(",")){
							childitemid = childitemid.substring(0, childitemid.length()-1);
						}
						sql = "select id, selectvalue, selectname, listorder from workflow_selectitem where fieldid="+childfieldid+" and isbill=1 and selectvalue in ("+childitemid+") and ( cancel!=1 or cancel is null) order by listorder, id asc";
						rs.execute(sql);
						while(rs.next()){
							String selectvalue_tmp = Util.null2String(rs.getString("selectvalue"));
							String selectname_tmp = Util.toScreen(rs.getString("selectname"), 7);
							JSONObject selectOption=new JSONObject();
							selectOption.put("value",selectvalue_tmp);
							selectOption.put("text", MobileCommonUtil.formatMultiLang(selectname_tmp, user));
							result.add(selectOption);
						}
					}
				}
			}
		}
		
		return result;
	}

	
	@ActionMapping(name="getUserMecConfig")
	public JSONObject getUserMecConfig(){
		JSONObject result = new JSONObject();
		result.put("status", "0");

		String mecid = Util.null2String(getParameter("mecid"));
		if(StringHelper.isNotEmpty(mecid)){
			RecordSet rs = new RecordSet();
			String sql = "";
			sql = "select config from MobilemodeUserMecConfig where userid = ? and  mecid = ? ";
			rs.executeQuery(sql, user.getUID(), mecid);
			if(rs.next()){
				result.put("status", "1");
				result.put("result", Util.null2String(rs.getString("config")));
			}
		}
		
		return result;
	}
	
	@ActionMapping(name="setUserMecConfig")
	public JSONObject setUserMecConfig(){
		JSONObject result = new JSONObject();
		FileUpload fu = new MobileFileUpload(this.getRequest(), "UTF-8", false);

		String mecid = Util.null2String(fu.getParameter("mecid"));
		String config = Util.null2String(fu.getParameter("config"));
		boolean isSuccess = false;
		if(StringHelper.isNotEmpty(mecid)){
			RecordSet rs = new RecordSet();
			String sql = "";
			sql = "select id from MobilemodeUserMecConfig where userid = ? and  mecid = ? ";
			rs.executeQuery(sql, user.getUID(), mecid);
			if(rs.next()){
				isSuccess = rs.executeUpdate("update MobilemodeUserMecConfig set config = ? where id = ? ", config, Util.null2String(rs.getString("id")));
			}else{
				isSuccess = rs.executeUpdate("insert into MobilemodeUserMecConfig(mecid, userid, config) values(?,?,?)", mecid, user.getUID(), config);
			}
		}
		
		result.put("success", isSuccess);
		return result;
	}
	
	@ActionMapping(name="encrypt")
	protected String encrypt() {
		String content = Util.null2String(getParameter("content"));
		boolean unEncodeWhenFirewallDisabled = Util.null2String(getParameter("unEncodeWhenFirewallDisabled")).equals("true");
		return MobileCommonUtil.xssEncode(content, !unEncodeWhenFirewallDisabled);
	}
	
	@ActionMapping(name="addFormmodeDataShare")
	protected void addFormmodeDataShare() {
		int modelid = NumberHelper.getIntegerValue(getParameter("modelid"), -1);
		int billid = NumberHelper.getIntegerValue(getParameter("billid"), -1);
		if(modelid > 0 && billid > 0){
			
			int userid = user.getUID();
			
			ModelInfoDao modelInfoDao = new ModelInfoDao();
			int formid = modelInfoDao.getFormInfoIdByModelId(modelid);
			
			ModeRightInfo modeRightInfo = new ModeRightInfo();
			CodeBuilder cbuild = new CodeBuilder(modelid);
			cbuild.getModeCodeStr(formid, billid);//生成编号
			modeRightInfo.setNewRight(true);
			modeRightInfo.editModeDataShare(userid, modelid, billid);//新建的时候添加共享
		}
	}

	@ActionMapping(name="parseVar")
	protected JSONObject parseVar() {
		FileUpload fileUpload = new MobileFileUpload(this.getRequest(), "UTF-8", false);
		String requestParam = Util.null2String(fileUpload.getParameter("requestmap"));
		JSONObject requestmap = JSONObject.fromObject(requestParam);
		for(Object key : requestmap.keySet()){
			String source = Util.null2String(requestmap.get(key));
			String target = BasicHandler.replaceWithVarParser(source, user);
			requestmap.put(key, target);
		}
		return requestmap;
	}
	
	@ActionMapping(name="getImagesByDocids")
	protected  Map<String, List<String>> getImagesByDocids() {
		String docids = Util.null2String(getParameter("docids"));
		return AttachUtil.getAllImagesByDocids(docids);
	}
	
	/**
	 * 获取请求URL的域名或IP与端口
	 * @return
	 */
	@ActionMapping(name="getRequestURL", returnKey="ipaddr")
	protected  String getRequestURL() {
        URI uri = URI.create(getRequest().getRequestURL().toString());
    	try {
			uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
		} catch (URISyntaxException e) {
        	return "";
		}
        return uri.toString();
	}
	
	@ActionMapping(name="checkCubeReply", returnKey="enable")
    protected  boolean isENFormmodeReply() {
	    RecordSet rs = new RecordSet();
        rs.execute("select isEnFormmodeReply from formEngineSet");
        if(rs.next()){
            return "1".equals(rs.getString("isEnFormmodeReply"));
        }
        return false;
    }
	
	/**
     * 附件下载的在钉钉环境会单开浏览器导致拿不到用户无法下载
     * 
     * @param fileid 附件id
     * @return
     */
    @ActionMapping(name="getFileDownloadParams")
    protected Map<String, Object> getFileDownloadDDCode(){
        String fileidStr = Util.null2String(getRequest().getParameter("fileid"), "");
        int fileid = -1;
        if(fileidStr.length()<11){
            fileid = Util.getIntValue(fileidStr);
        }else{
            fileid = DocDownloadCheckUtil.getDownloadfileid(fileidStr);
        }

		int docid = AttachUtil.convertFileIdToDocid(fileid);

		DocViewPermission docViewPermission = new DocViewPermission();
		Map<String,Boolean> rightMap= docViewPermission.getShareLevel(docid,user,false);
		boolean canReader = rightMap.get(DocViewPermission.READ);

		if(canReader || docid == -1){
			Map<String, Object> resultMap = ParamUtil.request2Map(getRequest());
			ImageFileServiceImpl imageFileService = ServiceUtil.getService(ImageFileServiceImpl.class, user);
			Map<String, Object> result = imageFileService.getMobileDownloadParams(fileid, "", resultMap, user);
			return result;
		}else{
			throw new MobileModeException(MobileCommonUtil.getHtmlLabelName(539277, user.getLanguage(), "无下载权限"));
		}

    }
    
    @ActionMapping(name="getAttachViewFileType")
    protected List<String> getAttachViewFileType(){
    	DocDetailUtil docDetailUtil = new DocDetailUtil();
    	return docDetailUtil.getAttachViewFileType(false, false);
    }
}
