/*
 *
S * Copyright (c) 2001-2017 泛微软件.
 * 泛微协同商务系统,版权所有.
 * 
 */
package com.cloudstore.dev.api.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.browser.util.BoolAttr;
import com.api.cube.util.CubeCipherUitl;
import com.cloudstore.dev.api.bean.OrgType;
import com.cloudstore.dev.api.bean.TimeMarker;
import com.cloudstore.dev.api.bean.UserDefCol;
import com.cloudstore.dev.api.util.TextUtil;
import com.cloudstore.dev.api.util.Util_public;
import com.cloudstore.eccom.core.WeaCommon;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.LogUtil;
import com.google.common.collect.Lists;
import com.weaver.formmodel.util.StringHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.util.WorkflowToModeUtil;
import weaver.general.BaseBean;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.CompanyComInfo;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.datasource.DataSource;
import weaver.servicefiles.DataSourceXML;

import java.util.*;


/**
 * @version 1.0
 * @author wangkai
 * TODO 
 */
public class Dao_TableSqlServer implements Dao_Table {

	private static final Log logger = LogFactory.getLog(Dao_TableSqlServer.class);
	private String    sql = null;

	/**
	 * 无参构造方法
	 */
	public Dao_TableSqlServer(){
		
	}
	
	/**
	 * TODO 旧的分页查询
	 * 
	 * @param sqlObj
	 * @param columns
	 * @param min
	 * @param max
	 * @return
	 */
	@Override
	public List<Map<String, String>> getTableDatas(JSONObject sqlObj,
			JSONArray columns, String min, String max) {
		RecordSet rs=new RecordSet();
		String tFields = Util.null2String(sqlObj.getString("tFields"));
		String tFrom = Util.null2String(sqlObj.getString("tFrom"));
		String tWhere = Util.null2String(sqlObj.getString("tWhere"));
		String tOrder = Util.null2String(sqlObj.getString("tOrder"));
		StringBuilder sb = new StringBuilder();
		sb.append("select * from (");
		sb.append("select "+tFields+",ROW_NUMBER() OVER( order by "+tOrder+") as rn");
		sb.append(" ");
		if(!tFrom.startsWith("from"))
			sb.append("from");
		sb.append(" ").append(tFrom);
		sb.append(" ");
		if (!"".equals(tWhere)) {
			if (!tWhere.startsWith("where") && !tWhere.startsWith("WHERE")) {
				sb.append(" where ");
			}
			sb.append(" ").append(tWhere);
		}
		sb.append(") as tmp");
		sb.append(" where tmp.rn>=").append(min);
		sb.append(" and tmp.rn<=").append(max);
		sql = sb.toString();
		//logger.error(sql);
		rs.writeLog("zqb::::::sql====="+sql);
		if(!rs.execute(sql)) logger.error(sql);
		List<Map<String, String>> mssl = new ArrayList<Map<String,String>>();
		while(rs.next()) {
			Map<String, String> mss = new HashMap<String, String>();
			for(Object column : (List)columns) {
				JSONObject obj = (JSONObject) column;
				String dataIndex = obj.getString("dataIndex");
				mss.put(dataIndex,rs.getString(dataIndex));
			}
			mss.put("id",rs.getString("id"));
			mssl.add(mss);
		}
		return mssl;
	}
	
	/**
	 * TODO 旧的分页数量查询
	 * 
	 * @param sqlObj
	 * @return
	 */
	@Override
	public int getTableCount(JSONObject sqlObj) {
		RecordSet rs=new RecordSet();
		String tFrom = sqlObj.getString("tFrom");
		String tWhere = sqlObj.getString("tWhere");
		StringBuilder sb = new StringBuilder();
		sb.append("select count(*)");
		sb.append(" ");
		if(!tFrom.startsWith("from"))
			sb.append("from");
		sb.append(" ").append(tFrom);
		sb.append(" ");
		if (!"".equals(tWhere)) {
			if (!tWhere.startsWith("where") && !tWhere.startsWith("WHERE")) {
				sb.append(" where ");
			}
			sb.append(" ").append(tWhere);
		}
		sql = sb.toString();
		Long start=System.currentTimeMillis();

		if(!rs.execute(sql)) logger.error(sql);
		printSQLAndTimeLog(sql,start);
		return rs.next()?rs.getInt(1):0;
	}

	/**
	 * 打印时间和SQL的日志
	 * @param sql
	 * @return
	 */
	public void printSQLAndTimeLog(String sql,Long start){
		if (System.currentTimeMillis()-start>2000)
			logger.error("通用列表查询:耗时："+(System.currentTimeMillis()-start)+"ms SQL:"+sql);
	}
	
	/**
	 * TODO 
	 * @param str
	 * @return 
	 */
	public static String convertChar(String str,String wrapClose){
        if ("1".equals(wrapClose)) return str;//关闭换行
        else {
            str = str.replace("\t", "");
            str = str.replace("\r", "");
            str = str.replace("\n", "");
            str = str.replace("\f", "");
            return str;
        }
	}

	/**
	 * TODO 
	 * @param sqlObj 
	 * @param sql 
	 * @param columns 
	 * @return
	 */
	@Override
	public List<Map<String, String>> setDevTableDatas(JSONObject sqlObj, String sql, JSONArray columns, List getBroList, TimeMarker timeMarker) {
		RecordSet rs=new RecordSet();
		// 如果在 <sql> 标签中配置了 unchecksql 属性，不检查SQL。
		// 默认：检查SQL
		if (sqlObj.getBooleanValue("unchecksql")){
			rs.setChecksql(false);
		}
		if(Util.null2String(sqlObj.getString("fromExport")).equals("1")){
			//导出数据明文显示
			rs.isReturnDecryptData(true);
		}else{
			rs.isReturnDecryptData(Util.null2String(sqlObj.getString("isReturnDecryptData")).equals("true"));
			rs.isAutoDecrypt(!Util.null2String(sqlObj.getString("isAutoDecrypt")).equals("false"));
		}

		String topColumn = Util.null2String(sqlObj.getString("topColumn"),"");//获取置顶列
		int topColumnValue = 0;//置顶列的value
		//logger.error("setDevTableDatas sql :" + sql);
		String tPrimaryKey = Util.null2String(sqlObj.getString("sqlprimarykey"));
        String wrapClose = Util.null2String(sqlObj.getString("wrapclose"));
		String [] primarys = primarys = tPrimaryKey.split(",");
		String tophtmlWithMarginString =   "<span style='background-color:#ff9000;margin-left:12px;border-radius:2px;color:white;font-weight:500;font-size:9px;transform:scale(0.8);display:inline-block;padding:1px 5px;height:16px;line-height:14px;'>TOP</span>";
		String tophtmlWithOutMarginString = "<span style='background-color:#ff9000;border-radius:2px;color:white;font-weight:500;font-size:9px;transform:scale(0.8);display:inline-block;padding:1px 5px;height:16px;line-height:14px;'>TOP</span>";
		for(int i=0; i<primarys.length; i++) {
			if(primarys[i].indexOf(".")>0) {
				primarys[i] = primarys[i].substring(primarys[i].indexOf(".")+1);
			}
		}
		String poolname = sqlObj.getString("poolname");

		//logger.error(sql);
		//AndyZhang 修改建模的跨数据库异常问题
		if (StringUtils.isBlank(poolname)){
			if(!rs.executeSql(sql)) logger.error(sql);
		}
		else{
			if(!rs.executeSql(sql, poolname)) logger.error(sql);
		}

		/*if(!rs.executeSql(sql, poolname)) logger.error(sql);*/
		printSQLAndTimeLog(sql,timeMarker.getStart());


        timeMarker.mark("read data in dao");
		List<Map<String, String>> mssl = new ArrayList<Map<String,String>>();
		//Long times1 = System.currentTimeMillis();
		while(rs.next()) {
			Map<String, String> mss = new HashMap<String, String>();
			if(!"".equals(topColumn)){
				 topColumnValue =  Util.getIntValue(Util.null2String(rs.getString(topColumn)), 0);
			}

			for(Object column : (List)columns) {
				JSONObject obj = (JSONObject) column;

				obj.put("fromExport",Util.null2String(sqlObj.getString("fromExport")));
				String name = obj.getString("dbField");
				String tablename = obj.getString("tablename");
				String columnname = Util.null2String(obj.getString("columnname"));//字段名，用于别名情况
				String jsonName = obj.getString("dataIndex");
				/*String align = obj.getString("align");
				
				if (StringUtils.isNotBlank(align)) mss.put("align",align);
				if (StringUtils.isNotBlank(obj.getString("dataalign"))) 
					mss.put("dataalign",obj.getString("dataalign"));*/

				String value = "";
				if(columnname.length()>0){
					value = rs.getStringFromAlias(tablename,name, columnname);
				}else{
					value = rs.getString(tablename,name);
				}
				value=CubeCipherUitl.decrypt(value);
				String valueSpan = value;
				// logger.error("obj is :" + obj.toString());

				//加入对base64的支持功能 andyzhang
				if (obj.containsKey("isBase64")&& obj.getString("isBase64").equals("1")){
					if (Util.isEnableMultiLang()) {//weainput多语言需要在前面加上base_标识
                    	value=TextUtil.toBase64ForMultilang(value);
					}else {
						value=Util_public.base64Encode(value);
					}
				}

				if (obj.containsKey("transMethod") && StringUtils.isNotBlank(obj.getString("transMethod"))
						&& obj.containsKey("display")) {
					// logger.error("obj is containsKey transMethod:"
					// + obj.getString("transMethod"));
					// logger.error("obj is containsKey display:"
					// + obj.getString("display"));
					if ("true".equals(obj.getString("display"))|| "true".equals(obj.getString("transMethodForce"))) {
						//linkvaluecolumn
						try {
							valueSpan = Util.null2String(Util_public.doTransMethod(obj, rs)).replaceAll("&nbsp;"," ").replaceAll("<br>","\n");
							//添加对移动交互字段的解析逻辑
							if (value.indexOf(WorkflowToModeUtil.SPLIT_LOCATION) != -1 || value.indexOf(WorkflowToModeUtil.SPLIT_FIELD) != -1) {//判断是否存在地址分割符，如果存在就进行转换
								valueSpan = WorkflowToModeUtil.toList(value);
							}

//							if(topColumnValue==1){
//								if(valueSpan.startsWith("<a") && valueSpan.indexOf("</a>") != -1 ){//链接字段 且属于置顶数据则需要添加top标志
//									if(!"".equals(value) && valueSpan.indexOf("javaScript:openhrm")==-1){
//										valueSpan+= tophtmlWithMarginString;
//									}else {
//										if(valueSpan.indexOf("javaScript:openhrm")==-1){
//											valueSpan+=tophtmlWithOutMarginString;
//										}
//
//									}
//								}
//							}
						}catch(Exception e) {
						}
					}
					if ("".equals(valueSpan)) {
						mss.put(jsonName + "span", "");
					} else {
						if (valueSpan.contains("</p>\n\n<p>")) { //处理富文本多次换行
							valueSpan = valueSpan.replaceAll("</p>\n\n<p>", "</p>\n<p>");
						}
						mss.put(jsonName + "span",convertChar(valueSpan,wrapClose));
					}

					mss.put(jsonName, convertChar(value,wrapClose));

					//logger.error("end jsonName :" + jsonName);
				}
				else {
					mss.put(jsonName, convertChar(value,wrapClose));
					mss.put(jsonName + "span", convertChar(valueSpan,wrapClose));
				}
				if(obj.containsKey("linkvaluecolumn")) {
					String id = obj.getString("linkvaluecolumn");
					mss.put(id,rs.getString(id));
				}
				
				//移动端处理
				if (sqlObj.containsKey("ismobile"))
				{
					if (obj.containsKey("mobiletransmethod") && StringUtils.isNotBlank(obj.getString("mobiletransmethod"))) {

						try {
							valueSpan = Util.null2String(Util_public.doMobileTransMethod(obj, rs));

						}catch(Exception e) {
							e.printStackTrace();
							//logger.error(e.getMessage());
						}

						if ("".equals(valueSpan)) {
							mss.put(jsonName + "span", "");
						} else {
							mss.put(jsonName + "span", convertChar(valueSpan,wrapClose));
						}
						mss.put(jsonName, convertChar(value,wrapClose));
					
					}
					
					//过滤移动端的 Link标签
					if (StringUtil.isNotNullAndEmpty(valueSpan))
					{
						valueSpan=Util_public.deletcLink(valueSpan);
						mss.put(jsonName + "span", convertChar(valueSpan,wrapClose));
					}
				}
				//移动端处理
			}
			if (null != getBroList && getBroList.size() > 0) {
				for (int i = 0; i < getBroList.size(); i++) {
					if (!mss.containsKey(getBroList.get(i))) {
						mss.put((String) getBroList.get(i),
								rs.getString(getBroList.get(i) + ""));
					}
				}
			}
			for(int i=0; i<primarys.length; i++) {
				if(i==0) {
					mss.put("randomFieldId",rs.getString(primarys[i]));
				} else {
					mss.put("randomFieldSubKey"+primarys[i],rs.getString(primarys[i]));
				}
			}

			mssl.add(mss);
		}
		timeMarker.mark("do transMethod in dao");
		return mssl;
	}
	
	/**
	 * TODO 新table
	 * 
	 * @param sqlObj
	 * @param columns
	 * @param min
	 * @param max
	 * @param sortParams
	 * @return
	 */
	@Override
	public List<Map<String, String>> getDevTableDatas(JSONObject sqlObj,
			JSONArray columns, String min, String max, String sortParams,
			List getBroList, TimeMarker timeMarker) {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		String usedpri = Util.null2String(sqlObj.getString("usingPriSql"));
		String pripagesql = Util.null2String(sqlObj.getString("priPageSql"));
		String tWhere = Util_public.toSqlForSplitPage(Util.null2String(sqlObj.getString("sqlwhere")));
		String privatePageSql = "";
		// logger.error("sqlwhere is :" + tWhere);
		if ("true".equals(usedpri) && !"".equals(pripagesql)) {
			pripagesql = pripagesql.replace("tmp.maxNum", max);
			pripagesql = pripagesql.replace("tmp.minNum", min);
			sb.append(pripagesql);
			privatePageSql = sb.toString();
			// logger.error("getDevTableDatas private sql :" + sb.toString());
		} else {

			String tFields = Util.null2String(sqlObj.getString("backfields"));
			if(!"".equals(tFields)){
				tFields+=Util.null2String(sqlObj.getString("topColumn"))==""?"":",t1."+Util.null2String(sqlObj.getString("topColumn"));

			}
			String tFrom = Util_public.toSqlForSplitPage(Util.null2String(sqlObj.getString("sqlform")));
			// String tWhere = Util.null2String(sqlObj.getString("sqlwhere"));
			String tOrder = Util.null2String(sqlObj.getString("sqlorderby"));
			String tOrderWay = Util.null2String(sqlObj.getString("sqlsortway"));
			String tDistinct = Util.null2String(sqlObj.getString("sqlisdistinct"));
            String tGroupBy = Util.null2String(sqlObj.getString("sqlgroupby")).trim();
            String sqlPrimaryKey = sqlObj.getString("sqlprimarykey");
            
            String openPrimaryKeyOrder = sqlObj.getString("openprimarykeyorder");

			String mergeOrder = sqlObj.getString("mergeorder");

            //分页方式不带top
            String fastpage = sqlObj.getString("fastpage");

            tOrder = Util_public.createSqlOrder(sortParams, tOrder, tOrderWay, sqlPrimaryKey,
					BoolAttr.TRUE.getStringVal().equals(openPrimaryKeyOrder),BoolAttr.TRUE.getStringVal().equals(mergeOrder));
            
            //分页方式fastpage 不使用top分页较快
            if ("true".equals(fastpage))
            {
            	//sb.append("select * from (");
                
                sb.append("select * ");
                
    			//支持outfields
    			if (sqlObj.containsKey("outfields")
    					&& !"".equals(sqlObj.getString("outfields"))) {
    				sb.append(" , " + sqlObj.getString("outfields"));
    			}
    			//支持outfields
    			
    			//sb.append(" from ( ");
    			
    			sb.append(" from (select * ,ROW_NUMBER() OVER( order by " + tOrder
    					+ ") as rn from ( ");
    			
    			//(select * ,ROW_NUMBER () OVER (ORDER BY sort ASC, id ASC) AS rn from 
    			
    			sb.append("select " + ("true".equals(tDistinct) ? "distinct " : "")
    					+ tFields );
    			sb.append(" ");
    			if (!tFrom.startsWith("from"))
    				sb.append("from");
    			sb.append(" ").append(tFrom);
    			sb.append(" ");
    			if(!"".equals(tWhere)){
    				if (!tWhere.startsWith("where") && !tWhere.startsWith("WHERE")) {
    					sb.append("where");
    				}
    				sb.append(" ").append(tWhere);
    			}
    			// if ((!tWhere.startsWith("where") && !"".equals(tWhere))
    			// || (!tWhere.startsWith("WHERE") && !"".equals(tWhere)))
    			// sb.append("where");
    			// sb.append(" ").append(tWhere);
    			sb.append(Util_public.getSqlPartWithToken(tGroupBy, "group by"));
    			//sb.append(Util_public.getSqlPartWithToken(tOrder, "order by"));
    			sb.append(" ) as p");
    			sb.append(" ) as r");
    			sb.append(" where 1=1");
    				sb.append(" and r.rn>=").append(min);
    			sb.append(" and r.rn<=").append(max);
    			// logger.error("getDevTableDatas public sql :" + sb.toString());
    			privatePageSql = sb.toString();
            }
            else
            {
    			//top方式分页效率较低  但是为了兼容以前的暂时留着 andyzhang 2018-10-11
 
    			privatePageSql += " SELECT r.* ";
    			if (sqlObj.containsKey("outfields")
    					&& !"".equals(sqlObj.getString("outfields"))) {
    				privatePageSql += " , " + sqlObj.getString("outfields");
    			}
    			privatePageSql += " FROM ( SELECT outtemp.* FROM (SELECT row_number () over ( ORDER BY tempcolumn) temprownumber ,* FROM (";
    			privatePageSql += " SELECT ";
    			if ("true".equals(tDistinct)) {
    				privatePageSql += " distinct ";
    			}

    			privatePageSql += " top " + max + " tempcolumn = 0,";

    			privatePageSql += tFields;
                privatePageSql += Util_public.getSqlPartWithToken(tFrom, "from");
                privatePageSql += Util_public.getSqlPartWithToken(tWhere, "where");
                privatePageSql += Util_public.getSqlPartWithToken(tGroupBy, "group by");
    			if (StringUtils.isNotBlank(tOrder))
    				privatePageSql += " order by " + tOrder;
    			privatePageSql += " ) innertemp ) outtemp ";

    				privatePageSql += " where temprownumber>=" + min;
    			privatePageSql += " ) r";
            }


		}
		timeMarker.mark("create sql");
		return this.setDevTableDatas(sqlObj, privatePageSql, columns,
				getBroList, timeMarker);
	}

	
	public String getDbType(String poolname)
	{
		String dbtype;
		if(!StringHelper.isEmpty(poolname)&&!DataSourceXML.SYS_LOCAL_POOLNAME.equals(poolname)){
			DataSource datasource = (DataSource) StaticObj.getServiceByFullname("datasource."+poolname, DataSource.class);
			dbtype = datasource.getType();
		}else{
			RecordSet recordSet = new RecordSet();
			dbtype = recordSet.getDBType();
		}
		
		return dbtype;
	}
	// private static String toSqlForSplitPage(String s) {
	//
	// // s = Util.StringReplace(s, "\\'", "'");
	// s = Util.StringReplace(s, "&lt;", "<");
	// s = Util.StringReplace(s, "&gt;", ">");
	// s = Util.StringReplace(s, "&amp;", "&");
	// s = Util.StringReplace(s, "&quot;", "\"");
	// return s;
	// }

	/**
	 * TODO  
	 * @param sqlObj 
	 * @return
	 */
	@Override
    public int getDevTableCount(JSONObject sqlObj) {
        RecordSet rs=new RecordSet();
        String usedpri = Util.null2String(sqlObj.getString("usingPriSql"));
        String poolname = sqlObj.getString("poolname");
        new BaseBean().writeLog("getDevTableCount--poolname:"+poolname);
        if ("true".equals(usedpri)) {

            String countsql = Util.null2String(sqlObj.getString("priCountSql"));
            if ("".equals(countsql))
                return 0;
            sql = countsql;
            // logger.error("in used private countsql " + sql);
            /*if (!rs.executeSql(sql, poolname))
                logger.error(" private countsql wrong sql :" + sql);*/
            //AndyZhang 修改建模的跨数据库异常问题
            if (StringUtils.isBlank(poolname)){
    			if(!rs.executeSql(sql))logger.error(" private countsql wrong sql :" + sql);
            }
    		else{
    			if(!rs.executeSql(sql, poolname)) logger.error(" private countsql wrong sql :" + sql);
    		}
            
            return rs.next() ? rs.getInt(1) : 0;
        } else {
            String tFrom = Util_public.toSqlForSplitPage(Util.null2String(sqlObj.getString("sqlform")));
            String tWhere = Util_public.toSqlForSplitPage(Util.null2String(sqlObj.getString("sqlwhere")));
            String tDistinct = Util_public.toSqlForSplitPage(Util.null2String(sqlObj.getString("sqlisdistinct")));
            String tFields = Util_public.toSqlForSplitPage(Util.null2String(sqlObj.getString("backfields")));
            String tGroupBy = Util.null2String(sqlObj.getString("sqlgroupby"));
            StringBuilder sb = new StringBuilder();
            sb.append("select count(*)");
            sb.append(" from (");
            sb.append("select " + ("true".equals(tDistinct) ? "distinct " : " ") + tFields + " ");
            sb.append(Util_public.getSqlPartWithToken(tFrom, "from"));
            sb.append(Util_public.getSqlPartWithToken(tWhere, "where"));
            sb.append(Util_public.getSqlPartWithToken(tGroupBy, "group by"));

			DataSource dataSource = (DataSource) StaticObj.getServiceByFullname("datasource." + poolname, DataSource.class);
//			南大通用sql报错 别名list前加as；数据库厂商已经做了兼容，去掉 as
			sb.append("mysql".equalsIgnoreCase(dataSource != null ? dataSource.getType() : rs.getDBType()) ? " ) `list`" : "informix".equalsIgnoreCase(dataSource != null ? dataSource.getType() : rs.getDBType()) ?" ) as list " : " ) list");
//            sb.append(" ) list");
            sql = sb.toString();

			Long start=System.currentTimeMillis();

			//AndyZhang 修改建模的跨数据库异常问题
            if (StringUtils.isBlank(poolname)){
    			if(!rs.executeSql(sql))logger.error(" public countsql wrong sql:" + sql);
            }
    		else{
    			if(!rs.executeSql(sql, poolname)) logger.error(" public countsql wrong sql:" + sql);
    		}
            
            /*if (!rs.executeSql(sql, poolname))
                logger.error(" public countsql wrong sql :" + sql);*/

			printSQLAndTimeLog(sql,start);

            //logger.error("GET DEV TABLE COUNT sql:" + sql);
            return rs.next() ? rs.getInt(1) : 0;
        }
    }

	/**
	 * TODO  
	 * @param customid 
	 * @return
	 */
	@Override
	public boolean checkModeSkip(int customid) {
		RecordSet rs=new RecordSet();
		sql = "select 1 from Mode_CustomDspField where customid = " + customid
				+ " and isshow = 1";
		if (!rs.execute(sql)) {
			logger.error("checkModeSkip wrong sql :" + sql);
			return false;
		}
		if (!rs.next()) {
			return true;
		}
		return false;
	}

	/**
	 * TODO  
	 * @param user 
	 * @param pageUid 
	 * @param type 
	 * @return
	 */
	@Override
	public JSONObject getDestTable(User user, String pageUid, int type) {
		RecordSet rs=new RecordSet();
		JSONObject rObj = new JSONObject();
		rObj.put("status", false);

		if (null != pageUid && !"".equals(pageUid)) {

			JSONArray getRlist = new JSONArray();
			StringBuilder sbl = new StringBuilder();
			String dbname = " cloudstore_defcol ";
			// " user_default_col ";
			// if (!"".equals(pageUid) && 0 == type)
			// dbname = " cloudstore_defcol ";
			sbl.append("select distinct sdc.orders,udc.id,udc.sysid,sdc._text,sdc._key from ");
			sbl.append(dbname).append(" udc");
			sbl.append(" , cloudstore_sdfcol sdc where udc.sysid = sdc.uuid ");
			// sql.append(" left outer join table_col_base tcb on sdc.col_base_id = tcb.id");
			sbl.append(" and udc.userid  = '").append(user.getUID())
					.append("' and sdc.pageUid='").append(pageUid)
					.append("' and udc.display=0");
			sbl.append(" order by sdc.orders");
			// System.out.println("1-------"+sql);
			sql = sbl.toString();
			// json.put("currentPage", "1");
			// json.put("totalPage", "1");
			if (!rs.execute(sql)) {
				logger.error("getDestTable Awrong sql :" + sql);
				return rObj;
			}
			while (rs.next()) {
				JSONObject tmp = new JSONObject();
				tmp.put("id", rs.getString("sysid"));
				tmp.put("name", rs.getString("_text"));
				tmp.put("key", rs.getString("_key"));
				getRlist.add(tmp);
			}

            sbl = new StringBuilder();
            sbl.append("select sdc.id,sdc.uuid,sdc._text,sdc._key from cloudstore_sdfcol sdc where sdc.display=0 and sdc.pageuid='")
                    .append(pageUid).append("'");

            // 用户没有设置自定义列时，查出所有的需要显示的列。设置了自定义列时，查出不在自定义表中的需要显示的列
            // 针对自定义查询做的修改。
			if (getRlist.size() > 0) {
			    sbl.append(" and not exists (select id from cloudstore_defcol udc where udc.sysid = sdc.uuid and udc.userid = '"+user.getUID()+"') ");
			}
            sbl.append(" order by orders");
            sql = sbl.toString();
            if (!rs.execute(sql)) {
                logger.error("getDestTable Bwrong sql :" + sql);
                return rObj;
            }

            while (rs.next()) {
                JSONObject tmp = new JSONObject();
                tmp.put("id", rs.getString("uuid"));
                tmp.put("name", rs.getString("_text"));
                tmp.put("key", rs.getString("_key"));
                getRlist.add(tmp);
            }
            // }

            if (getRlist.size() == 0) {
                // 系统表不存在这个表单，需要保存一次记录
                logger.error("pageUid 为：" + pageUid + "  表单定制列进行了一次新增");
                rObj.put("msg", "needInit");
                return rObj;
            }
			rObj.put("status", true);
			rObj.put("datas", getRlist);
		}

		return rObj;

	}

	/**
	 * TODO  
	 * @param user 
	 * @param pageUid 
	 * @param type 
	 * @return
	 */
	@Override
	public JSONArray getSrcTable(User user, String pageUid, int type) {
		RecordSet rs=new RecordSet();
		JSONArray getRlist = new JSONArray();
		StringBuilder sql2 = new StringBuilder();
		String dbname = "  cloudstore_defcol ";

		StringBuilder sbl = new StringBuilder();
		sbl.append("select distinct sdc.orders,udc.id,udc.sysid,sdc._text,udc.display,sdc._key from ");
		sbl.append(dbname).append(" udc");
		sbl.append(", cloudstore_sdfcol sdc where udc.sysid = sdc.uuid ");
		// sql.append(" left outer join table_col_base tcb on sdc.col_base_id = tcb.id");
		sbl.append(" and udc.userid  = '").append(user.getUID())
				.append("' and sdc.pageUid='").append(pageUid)
				.append("' order by sdc.orders");

		sql = sbl.toString();
		// json.put("currentPage", "1");
		// json.put("totalPage", "1");
		// logger.error("getSrcTable A sql :" + sql);
		if (!rs.execute(sql)) {
			logger.error("getSrcTable Awrong sql :" + sql);
			return getRlist;
		}
		String usingIds = "";
		while (rs.next()) {
			String id = rs.getString("sysid");
			if ("1".equals(rs.getString("display"))) {
				JSONObject tmp = new JSONObject();
				tmp.put("id", id);
				tmp.put("key", rs.getString("_key"));
				tmp.put("name", rs.getString("_text"));
				getRlist.add(tmp);
			}
			usingIds += "'" + id + "',";

		}
		sql2.append("select sdc.id,sdc.uuid,sdc._text,sdc._key from cloudstore_sdfcol sdc");
		// sql2.append(" left outer join table_col_base tcb on tcb.id = sdc.col_base_id");
		sql2.append(" where sdc.pageuid='").append(pageUid).append("'");

		if (!"".equals(usingIds)) {
			usingIds = usingIds.substring(0, usingIds.length() - 1);
			sql2.append(" and sdc.uuid not in (").append(usingIds)
					.append(") and sdc.display=1");
		} else {
			sql2.append(" and sdc.display=1");
		}

		sql2.append(" order by sdc.orders");
		sql = sql2.toString();
		// logger.error("sql2 src sql :" + sql);
		if (!rs.executeSql(sql)) {
			logger.error("getSrcTable Bwrong sql :" + sql);
			return getRlist;
		}
		while (rs.next()) {
			JSONObject tmp = new JSONObject();
			String id = rs.getString("uuid");
			tmp.put("id", id);
			tmp.put("key", rs.getString("_key"));
			tmp.put("name", rs.getString("_text"));
			getRlist.add(tmp);
		}
		// if (getRlist.size() == 0 && 0 == type) {
		// //logger.error("run second");
		// getRlist.addAll(getSrcTable(user, excludeId, includeId, pageId,
		// pageUid, 1));
		// }
		return getRlist;
	}

	/**
	 * 更新用户列的配置
	 * @param systemIdArr
	 * @param systemOrderArr
	 * @param user
	 * @param pageUid
	 * @return
	 */
	@Override
	public boolean updateShowCol(String[] systemIdArr, String[] systemOrderArr,
			User user, String pageUid) {
		// TODO Auto-generated method stub
		RecordSetTrans rst = new RecordSetTrans();
		if ("".equals(pageUid) || null == pageUid) {
			return false;
		}
		try {
			rst.setAutoCommit(false);
			// 目前不能先删除后添加了。
            // 不知道为什么不能，但现在的逻辑是有问题的，第一次如果是从已读改为未读，被修改的数据会丢失，所以还是改成先删除后添加。by caoyun
			rst.executeSql("delete from cloudstore_defcol where sysid<>'def' and pageuid='"+pageUid+"'"+" and userId = "+user.getUID());
			String dbname = " cloudstore_defcol ";
			// " user_default_col ";

			// if (!"".equals(pageUid))
			// dbname = " cloudstore_defcol ";
            sql = "insert into " + dbname + " (sysid,pageUid,userid,orders,display) "
                    + " select sdc.uuid, '" + pageUid + "','"+user.getUID() + "', sdc.orders, 1 "
                    + " from cloudstore_sdfcol sdc where sdc.pageUid='" + pageUid + "'";
//			sql = "update " + dbname + " set display=1 where pageuid='"
//					+ pageUid + "'" + " and userId = " + user.getUID();

			// logger.error("frist update sql is :" + sql);
			if (!rst.executeSql(sql)) {
				logger.error("updateShowCol update sql first false :" + sql);
				return false;
			}
			for (int i = 0; i < systemIdArr.length; i++) {
				if (Util.null2String(systemIdArr[i]).equalsIgnoreCase(""))
					continue;
				int orders = i;
				if (systemOrderArr != null && systemOrderArr.length > 0) {
					orders = Util.getIntValue(systemOrderArr[i], 0);
				}
				sql = "select 1 from " + dbname + " where sysid = '"
						+ systemIdArr[i] + "' and pageuid='" + pageUid + "'"
						+ " and userId = " + user.getUID();
				// logger.error("frist select sql is :" + sql);
				if (!rst.executeSql(sql)) {
					logger.error("updateShowCol select sql false :" + sql);
					return false;
				}
				if (rst.next()) {// 更新
					sql = "update " + dbname + " set display=0,orders="
							+ orders + " where sysid='" + systemIdArr[i]
							+ "' and pageuid='" + pageUid + "'"
							+ " and userId = '" + user.getUID() + "'";

					// logger.error("second update sql is :" + sql);
					rst.executeSql(sql);
				} else {

						sql = "insert into "
								+ dbname
							+ "(sysid,pageUid,userid,orders,display"
							+ ") values('" + systemIdArr[i] + "','" + pageUid
							+ "','" + user.getUID() + "',"
								+ orders + ",0)";

					// logger.error("second insert sql is :" + sql);
					rst.executeSql(sql);
				}
			}
			rst.commit();
			// 添加成功

			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			rst.rollback();
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * TODO 新增
	 * 
	 * @param heads
	 * @param pageUid
	 * @return
	 */
	@Override
	public boolean insertShowCol(JSONArray heads, String pageUid) {
		// TODO Auto-generated method stub
		RecordSetTrans rst = new RecordSetTrans();
		try {
			rst.setAutoCommit(false);
			Map IndexMap = new HashMap();

			if ("".equals(pageUid)) {
				return false;
			}
			for (int i = 0; i < heads.size(); i++) {
				// 先判断当前列是否存在DataIndex
				JSONObject jo = heads.getJSONObject(i);
				if (jo.containsKey("dataIndex")
						&& !"".equals((jo.getString("dataIndex")))
						&& !IndexMap.containsKey(jo.getString("dataIndex"))) {
					IndexMap.put(jo.getString("dataIndex"), "used");

					sql = "insert into cloudstore_sdfcol (uuid,pageuid,_key,display,orders,orderkey,_text)values('"
							+ UUID.randomUUID()
							+ "','"
							+ pageUid
							+ "','"
							+ jo.getString("dataIndex")
							+ "','"
							+ ("true".equals(jo.getString("display")) ? "0"
									: "1")
							+ "','"
							+ i
							+ "','"
							+ jo.getString("orderkey")
							+ "','"
							+ jo.getString("title") + "')";
					if (!rst.execute(sql)) {
						logger.error("insertShowCol WrongSql :" + sql);
						return false;
					}

				} else {
					return false;
				}
			}
			rst.commit();
			return true;
		} catch (Exception e) {
			rst.rollback();
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * TODO 新增
	 * 
	 * @param heads
	 * @param pageUid
	 * @param i
	 * @return
	 */
	@Override
	public boolean insertShowCol4Obj(JSONObject heads, String pageUid, int i) {
		// TODO Auto-generated method stub
		RecordSetTrans rst = new RecordSetTrans();
		try {
			rst.setAutoCommit(false);

			if ("".equals(pageUid)) {
				return false;
			}
			// 先判断当前列是否存在DataIndex
			JSONObject jo = heads;
			if (jo.containsKey("dataIndex")
					&& !"".equals((jo.getString("dataIndex")))) {
				RecordSet rs = new RecordSet();
				String checksql = "select _text from cloudstore_sdfcol where pageUid = '"+pageUid+"' and _text='"+jo.getString("title").trim()+"'";
				rs.executeSql(checksql);
				if (!rs.next()) {
					sql = "insert into cloudstore_sdfcol (uuid,pageuid,_key,display,orders,orderkey,_text)values('"
							+ UUID.randomUUID()
							+ "','"
							+ pageUid
							+ "','"
							+ jo.getString("dataIndex")
							+ "','"
							+ ("true".equals(jo.getString("display")) ? "0"
									: "1")
							+ "','"
							+ i
							+ "','"
							+ jo.getString("orderkey")
							+ "','"
							+ jo.getString("title") + "')";

					if (!rst.execute(sql)) {
						logger.error("insertShowCol WrongSql :" + sql);
						return false;
					}
				} else {
				    return false;
                }
			} else {
				return false;
			}

			rst.commit();
			return true;
		} catch (Exception e) {
			rst.rollback();
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * TODO
	 * @param title 
	 * @param dataIndex
	 * @param pageUid  
	 * @param i 
	 * @return
	 */
	@Override
	public boolean updateShowCol4Obj(String title, String dataIndex,
			String pageUid, int i) {
		// TODO Auto-generated method stub
		RecordSetTrans rst = new RecordSetTrans();
		try {
			rst.setAutoCommit(false);
			if ("".equals(pageUid)) {
				return false;
			}
			// 先判断当前列是否存在DataIndex
			if (!"".equals(dataIndex)) {

				sql = "update cloudstore_sdfcol set _text='" + title
						+ "' where pageuid = '" + pageUid + "' and _key='"
						+ dataIndex + "'";

				if (!rst.execute(sql)) {
					logger.error("update WrongSql :" + sql);
					return false;
				}

			} else {
				return false;
			}

			rst.commit();
			return true;
		} catch (Exception e) {
			rst.rollback();
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * TODO 
	 * @param uid 
	 * @param isload
	 */
	@Override
	public void insertUserSetting(int uid, String isload) {
		RecordSet rs=new RecordSet();
		sql = "insert into HrmUserSetting(resourceid,rtxOnload,isCoworkHead,skin,cutoverWay,transitionTime,transitionWay) values("
				+ uid + "," + isload + ",1,'','','','')";
		if (!rs.executeSql(sql)) {
			logger.error("insertUserSetting Bwrong sql :" + sql);
		}
	}

	/**
	 * TODO 
	 * @param uid 
	 * @param pageId
	 * @return
	 */
	@Override
	public String getPageSize(int uid, String pageId) {
		RecordSet rs=new RecordSet();
		String sql = "select pagesize from ecology_pagesize where pageId = '" + pageId
				+ "' and userid=" + uid;
		if (!rs.executeSql(sql)) {
			logger.error("getPageSize wrong sql :" + sql);
			return "";
		}
		if (rs.next()) {
			return rs.getString(1);
		}
		return "";
	}
	/**
	 * TODO 
	 * @param uid 
	 * @param pageId
	 * @param usedPageSize
	 * @return
	 */
	@Override
	public boolean insertPageSize(int uid, String pageId, int usedPageSize) {
		RecordSet rs=new RecordSet();
		sql = "insert into ecology_pagesize(pageId,pageSize,userid) values('"
				+ pageId + "'," + usedPageSize + "," + uid + ")";
		if (!rs.executeSql(sql)) {
			logger.error("insertPageSize wrong sql :" + sql);
			return false;
		}

		return true;
	}
	/**
	 * TODO 
	 * @param uid 
	 * @param pageId
	 * @param usedPageSize
	 * @return
	 */
	@Override
	public boolean updatePageSize(int uid, String pageId, int usedPageSize) {
		RecordSet rs=new RecordSet();
		sql = "update ecology_pagesize set pageSize= " + usedPageSize
				+ " where pageId='" + pageId + "' and userid=" + uid;
		if (!rs.executeSql(sql)) {
			logger.error("updatePageSize wrong sql :" + sql);
			return false;
		}
		return true;
	}
	

	public String getDealWithThousandsField(String sumField,String tCountcolumns,String dbType)
	{
		if (StringUtils.isNotBlank(tCountcolumns)) {
        	String[] fields=tCountcolumns.split(",");
        	for(String field:fields) {
        		if (StringUtils.isNotBlank(field)&&field.equalsIgnoreCase(sumField)) {
        			
        			if (dbType.equals("oracle")) {
        				return "cast(REPLACE("+sumField+",',','') as float) ";
        			}
        			else
        			if (dbType.equals("sqlserver")) {
        				return "cast(REPLACE("+sumField+",',','') as float) ";
        			}
        			else
        			if (dbType.equals("mysql")) {
        				return "cast(REPLACE("+sumField+",',','') as  DECIMAL(30,8)) ";
        			}
        		}
        	}
        }
		return sumField;
	}

	@Override
	public Map<String, String> getSqlSum(JSONObject sp, String[] sumlist,
			Map<String, String> allSumMap) {
		RecordSet rs = new RecordSet();
		
		StringBuilder sb = new StringBuilder();
		String tWhere = Util_public.toSqlForSplitPage(Util.null2String(sp.getString("sqlwhere")));
		String tFields = Util.null2String(sp.getString("backfields"));
		String tFrom = Util_public.toSqlForSplitPage(Util.null2String(sp.getString("sqlform")));
		String tOrder = Util.null2String(sp.getString("sqlorderby"));
		String tOrderWay = Util.null2String(sp.getString("sqlsortway"));
		String tDistinct = Util.null2String(sp.getString("sqlisdistinct"));
        String tGroupBy = Util.null2String(sp.getString("sqlgroupby"));
        String tCountcolumns = Util.null2String(sp.getString("countcolumnsdbtype"));
        String poolname = Util.null2String(sp.getString("poolname"));

        String dbType="";
        if(StringUtils.isBlank(poolname)){
            dbType = getDbType("");
        }else{
            dbType = getDbType(poolname);
        }

        Map<String, Double> tempMap=new HashMap<String, Double>();
        
        String tOrderArr[] = tOrder.split(",");
        tOrder = "";
		for (int i = 0; i < tOrderArr.length; i++) {
            tOrder += tOrderArr[i] + " " + tOrderWay + ",";
		}
        if (StringUtils.isNotBlank(tOrder))
            tOrder = tOrder.substring(0, tOrder.length() - 1);
        sb.append("select ");
		String tsum = "";
		
		for (int i = 0; i < sumlist.length; i++) {
			String field=sumlist[i];
			
			//tCountcolumns 兼容E8千分位的字段 需要被处理andyZhang 2008-8-10
			field=getDealWithThousandsField(sumlist[i],tCountcolumns,dbType);
			
			//tCountcolumns 兼容E8千分位的字段 需要被处理andyZhang 2008-8-10
            /*
            *sqlserver如果sum的结果超过int范围(-2^31 (-2,147,483,648) 到 2^31 - 1(2,147,483,647))，会出现报错，这里进行sql处理
            *oracel中int相当于number(22),存储22位数据，足够大，暂不做处理
            */
			if(dbType.contains("sqlserver")){
                tsum += "sum(cast(" + field + " as decimal(38,6))) " + sumlist[i] + ",";
            }else{
                tsum += "sum(" + field + ") " + sumlist[i] + ",";
            }

			tempMap.put(sumlist[i].trim(), 0.00);
			allSumMap.put(sumlist[i].trim(), "0.00");
		}
		
		if (!"".equals(tsum)) {
			tsum = tsum.substring(0, tsum.length() - 1);
		}
		sb.append("  ").append(!"".equals(tsum) ? tsum : "*").append(" from(");

        sb.append("select " + ("true".equals(tDistinct) ? "distinct " : "") + tFields);
        sb.append(" ");
        sb.append(Util_public.getSqlPartWithToken(tFrom, "from"));
        sb.append(Util_public.getSqlPartWithToken(tWhere, "where"));
        sb.append(Util_public.getSqlPartWithToken(tGroupBy, "group by"));
		sb.append(") tmp");
			sb.append(" where 1=1");
		sql = sb.toString();

		//AndyZhang 修改建模的跨数据库异常问题
		if (StringUtils.isBlank(poolname)){
			if(!rs.executeSql(sql)) logger.error("getSqlSum wrong sql is :" + sql);
		}
		else{
			if(!rs.executeSql(sql, poolname)) logger.error("getSqlSum wrong sql is :" + sql);
			}
		
		/*if (!rs.executeSql(sql,poolname))
			logger.error("getSqlSum wrong sql is :" + sql);*/
		
		while (rs.next()) {
			for (int i = 0; i < sumlist.length; i++) {
				Double getsum = Util.getDoubleValue(rs.getString(sumlist[i].trim()) ,0);//直接getDouble默认值是-1,会有问题。
				//getsum = getsum + allSumMap.get(sumlist[i].trim());
				getsum = getsum + tempMap.get(sumlist[i].trim());
				allSumMap.put(sumlist[i].trim(), Util_public.parseString(getsum));
			}
		}
		return allSumMap;
	}

    /**
     * 根据pageUid清除待选列,null时清除所有待选列
     * @param pageUid
     * @return
     */
    @Override
    public boolean clearShowCol(String pageUid) {
        return false;
        /*SqlSession session = sqlSessionFactory.openSession();
        try {
            Dao_TableMapper mapper = session.getMapper(Dao_TableMapper.class);
            if (pageUid != null) {
                mapper.deleteDefColByPageUid(pageUid);
                mapper.deleteSdfColByPageUid(pageUid);
            } else {
                mapper.deleteAllDefCol();
                mapper.deleteAllSdfCol();
            }
            session.commit();
        } finally{
            session.close();
        }
        return true;*/
    }

    @Override
    public boolean clearShowCol(String pageUid, int uid) {
        String sql = "delete from cloudstore_defcol where pageUid = ? and userid = ?";
        RecordSet rs = new RecordSet();
        /*SqlSession session = sqlSessionFactory.openSession();
        try {
            Dao_TableMapper mapper = session.getMapper(Dao_TableMapper.class);
            mapper.deleteUserDefCol(pageUid, uid);
            session.commit();
        } finally{
            session.close();
        }*/
        return rs.executeUpdate(sql, pageUid, uid);
    }

    @Override
    public List<UserDefCol> getUserDefColumns(String pageUid, int uid) {
        String sql = "select dataIndex, orders, display ,width from cloudstore_defcol where pageUid = ? and userid = ? and sysid<>'def' order by orders";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, pageUid, uid);

		//读取默认账号
		if (rs.getCounts()==0)
			rs.executeQuery(sql, pageUid, 0);

        List<UserDefCol> userDefCols = Lists.newArrayList();
        while (rs.next()) {
            UserDefCol col = new UserDefCol();
            col.setDataIndex(rs.getString("dataIndex"));
            col.setOrders(rs.getInt("orders"));
            col.setDisplay(rs.getString("display"));
			col.setWidth(rs.getString("width"));
            userDefCols.add(col);
        }
        return userDefCols;
        /*SqlSession session = sqlSessionFactory.openSession();
        try {
            Dao_TableMapper mapper = session.getMapper(Dao_TableMapper.class);
            return mapper.getUserDefColumns(pageUid, uid);
        } finally{
            session.close();
        }*/
    }

    @Override
    public void insertShowCol(List<UserDefCol> choosedDefCols, List<UserDefCol> unchoosedDefCols) {
        if (choosedDefCols != null && choosedDefCols.size() > 0) {
            batchInsert(choosedDefCols);
        }
        if (unchoosedDefCols != null && unchoosedDefCols.size() > 0) {
            batchInsert(unchoosedDefCols);
        }
        /*SqlSession session = sqlSessionFactory.openSession();
        try {
            Dao_TableMapper mapper = session.getMapper(Dao_TableMapper.class);
            if (choosedDefCols != null && choosedDefCols.size() > 0) {
                mapper.insertUserDefCol(choosedDefCols);
            }
            if (unchoosedDefCols != null && unchoosedDefCols.size() > 0) {
                mapper.insertUserDefCol(unchoosedDefCols);
            }
            session.commit();
        } finally{
            session.close();
        }*/
    }

    private void batchInsert(List<UserDefCol> cols) {
        RecordSet rs = new RecordSet();
        //宽度调整 andyzhang
        /*StringBuilder builder = new StringBuilder("insert into cloudstore_defcol (dataIndex,sysid, orders, display, pageUid,userid,width) values ");
        List<Object> params = Lists.newArrayList();
        for (UserDefCol col : cols) {
            builder.append("(?,?,?,?,?,?,?),");
            params.add(col.getDataIndex());
            params.add("");
            params.add(col.getOrders());
            params.add(col.getDisplay());
            params.add(col.getPageUid());
            params.add(col.getUserId());
			params.add(col.getWidth());
        }
        builder.deleteCharAt(builder.length() - 1);
        boolean result = rs.executeUpdate(builder.toString(), params.toArray());
        if (!result) {
            logger.error("插入失败");
        }*/

		//为兼容sql2005而调整 andyzhang
        for (UserDefCol col : cols) {
			StringBuilder builder = new StringBuilder("insert into cloudstore_defcol (dataIndex,sysid, orders, display, pageUid,userid,width) values ");
			List<Object> params = Lists.newArrayList();
            builder.append("(?,?,?,?,?,?,?)");
            params.add(col.getDataIndex());
            params.add("");
            params.add(col.getOrders());
            params.add(col.getDisplay());
            params.add(col.getPageUid());
            params.add(col.getUserId());
			params.add(col.getWidth());
			boolean result = rs.executeUpdate(builder.toString(), params.toArray());
			if (!result) {
				logger.error("插入失败");
			}
        }
    }

	public List<String> getDepList(String departmentIds) throws Exception {
		ArrayList depList=new ArrayList<>();
		if (StringUtils.isNotEmpty(departmentIds) )
			return depList;
		DepartmentComInfo comInfo=new DepartmentComInfo();
		String[] list=departmentIds.split(",");

		for(String id :list) {
			depList.add(id);
			comInfo.getAllChildDeptByDepId(depList,id);
		}
		return depList;
	}

	public List<String> getCompanyList(String companyIds) throws Exception {
		ArrayList companyList=new ArrayList<>();
		if (StringUtils.isNotEmpty(companyIds) )
			return companyList;
		CompanyComInfo comInfo=new CompanyComInfo();
		String[] list=companyIds.split(",");

		for(String id :list) {
			companyList.add(id);
		}
		return companyList;
	}

	@Override
	public boolean synCols(BizLogContext bizLogContext,List<UserDefCol> choosedDefCols, List<UserDefCol> unchoosedDefCols, OrgType orgType, String orgId,int def) {
		try {
			String pageuid="";
			String sysid="nullSysId";
			//def==1 是默认 def==2 是清除非默认
			if (def==1) sysid="def";
			RecordSet rs=new RecordSet();

			String sqlWhere="";
			String sqlWhereAll="";
			List params=new ArrayList();
			if (OrgType.COMPANY==orgType){
				List<String> companyList=getCompanyList(orgId);
				sqlWhere="  sysid in  "+WeaCommon.createWhereInSQL(companyList,true);
				sqlWhereAll=" where "+sqlWhere ;
				if (def==2)
					rs.executeQuery("delete from cloudstore_defcol where orgtype='COMPANY' and pageuid=?  and "+sqlWhere,pageuid);
				else
					rs.executeQuery("delete from cloudstore_defcol where orgtype='COMPANY' and sysid<>? and pageuid=?  and "+sqlWhere,def,pageuid);
				updateCols(orgType.name(),companyList,choosedDefCols,unchoosedDefCols,pageuid,def);
				//logger.info("清除设置："+pageuid);
			}

			if (OrgType.DEPARTMENT==orgType){

				List<String> depList=getDepList(orgId);
				sqlWhere="   sysid in "+WeaCommon.createWhereInSQL(depList,true);
				sqlWhereAll=" where "+sqlWhere ;
				if (def==2)
					rs.executeQuery("delete from cloudstore_defcol where orgtype='DEPARTMENT' and pageuid=?  "+sqlWhere,pageuid,params);
				else
					rs.executeQuery("delete from cloudstore_defcol where orgtype='DEPARTMENT' and sysid<>'def' and pageuid=?  "+sqlWhere,pageuid,params);
				updateCols(orgType.name(),depList,choosedDefCols,unchoosedDefCols,pageuid,def);
			}

			if (OrgType.PERSON==orgType){
				List<String> orgList=  Lists.newArrayList (orgId.split(",")) ;
				sqlWhere="  sysid in "+WeaCommon.createWhereInSQL(orgId);
				sqlWhereAll=" where "+sqlWhere ;
				if (def==2)
					rs.executeQuery("delete from cloudstore_defcol where orgtype='PERSON' and pageuid=? and "+sqlWhere,pageuid);
				else
					rs.executeQuery("delete from cloudstore_defcol where orgtype='PERSON' and sysid<>'def' and pageuid=? and "+sqlWhere,pageuid);

				updateCols(orgType.name(),orgList,choosedDefCols,unchoosedDefCols,pageuid,def);
			}


			logger.info("SQL执行成功："+pageuid);

			LogUtil.writeBizLog(bizLogContext);
		}
		catch (Exception ex	) {
			logger.error(ex.getMessage());
			return  false;
		}

		return true;
	}

	public boolean updateCols(String orgtype,List<String> orgList,List<UserDefCol> choosedDefCols,List<UserDefCol> unchoosedDefCols,String pageuid,int def){
		int i=0;
		RecordSet rs=new RecordSet();
		for(String orgid:orgList){

			for(UserDefCol col : choosedDefCols) {
				String dataIndex=col.getDataIndex();
				ArrayList<Object> paramsReal=new ArrayList<>();
				i++;
				paramsReal.add(orgid);
				paramsReal.add("");
				paramsReal.add(pageuid);
				paramsReal.add(i);
				paramsReal.add(dataIndex);
				paramsReal.add(orgtype);
				String sql;

				sql=" Insert into cloudstore_defcol(userid,sysid,pageuid,orders,display,dataindex,width,orgtype) ";
				sql+=" values(?,?,?,?,1,?,0,?) ";

				rs.executeUpdate(sql,paramsReal);
				logger.info("SQL执行成功：def："+def+":"+sql);
				if (def==2){
					ArrayList<Object> paramsDef=new ArrayList<>();
					paramsDef.add(orgid);
					paramsDef.add("def");
					paramsDef.add(pageuid);
					paramsDef.add(i);
					paramsDef.add(dataIndex);
					paramsDef.add(orgtype);
					rs.executeUpdate(sql,paramsDef);
				}
			}

			i=0;
			for(UserDefCol col : unchoosedDefCols) {
				i++;
				String dataIndex=col.getDataIndex();
				ArrayList<Object> paramsReal=new ArrayList<>();
				paramsReal.add(orgid);
				paramsReal.add("");
				paramsReal.add(pageuid);
				paramsReal.add(i);
				paramsReal.add(dataIndex);
				paramsReal.add(orgtype);
				String sql;

				sql=" Insert into cloudstore_defcol(userid,sysid,pageuid,orders,display,dataindex,width,orgtype) ";
				sql+=" values(?,?,?,?,1,?,?,0,?) ";

				rs.executeUpdate(sql,paramsReal);
				logger.info("SQL执行成功：def："+def+":"+sql);
				if (def==2){
					ArrayList<Object> paramsDef=new ArrayList<>();
					paramsDef.add("orgid");
					paramsDef.add("def");
					paramsDef.add(pageuid);
					paramsDef.add(i);
					paramsDef.add(dataIndex);
					paramsDef.add(orgtype);
					rs.executeUpdate(sql,paramsDef);
				}
			}
		}
		return true;
	}


}
