package com.cloudstore.dev.api.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.browser.util.BoolAttr;
import com.cloudstore.api.util.Util_Base64;
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.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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * author： wangyiwu
 * create： 2023/12/10 19:12
 * description：***
 */
public class Dao_TableInformix implements Dao_Table {

    private static final Log logger = LogFactory.getLog(Dao_TableInformix.class);

    private String sql = null;
    private Dao_Table d = null;

    /**
     * 无参构造方法
     */
    public Dao_TableInformix() {
        d = Dao_TableFactory.getInstance().getDao("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) {
        String tFields = "";
        String tFrom = "";
        String tWhere = "";
        String tOrder = "";
//        RecordSet rs=new RecordSet();
        //wyw 读取Informin数据源
        RecordSetDataSource rs=new RecordSetDataSource("Informix");
        try {

            tFields = new String(
                    Util_Base64.decode(sqlObj.getString("tFields")), "UTF-8");
            tFrom = new String(Util_Base64.decode(sqlObj.getString("tFrom")), "UTF-8");
            tWhere = new String(Util_Base64.decode(sqlObj.getString("tWhere")), "UTF-8");
            tOrder = new String(Util_Base64.decode(sqlObj.getString("tOrder")), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("select * from (");
        sb.append("select " + tFields);
        if (!"".equals(tOrder)){
            sb.append(" ,ROW_NUMBER() OVER(order by ").append(tOrder)
                    .append(" ) as rn");
        } else {
            sb.append(",rownum as rn ");
        }
        sb.append(" ");
        if (!tFrom.startsWith("from"))
            sb.append("from");
        sb.append(" ").append(tFrom);
        sb.append(" ");
        if ((!tWhere.startsWith("where")) && (!"".equals(tWhere)))
            sb.append("where");
        sb.append(" ").append(tWhere);
        sb.append(") tmp");
        sb.append(" where 1=1");
        if (!"".equals(min))
            sb.append(" and tmp.rn>=").append(min);
        if (!"".equals(max))
            sb.append(" and tmp.rn<=").append(max);

        sql = sb.toString();
        logger.info("====>wyw getTableDatas() sql:"+ sql);
        logger.error("打印:"+sql);
        if (!rs.execute(sql))
            logger.error(sql);
        List mssl = new ArrayList();
        while (rs.next()) {
            Map mss = new HashMap();
            for (Iterator localIterator = columns.iterator(); localIterator
                    .hasNext();) {
                Object column = localIterator.next();
                JSONObject obj = (JSONObject) column;
                String dataIndex = obj.getString("dataIndex");
                mss.put(dataIndex, rs.getString(dataIndex));
            }
            mssl.add(mss);
        }
        return mssl;
    }

    /**
     * TODO
     *
     * @param sqlObj
     * @return
     */
    @Override
    public int getTableCount(JSONObject sqlObj) {
        // TODO Auto-generated method stub
        return d.getTableCount(sqlObj);
    }

    /**
     * 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) {
        // TODO Auto-generated method stub
        //logger.error("setDevTableDatas sql :" + sql);
        return d.setDevTableDatas(sqlObj, sql, columns, getBroList, timeMarker);
    }

    // public static String Util_public.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
     * @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
        logger.info("====>wyw getDevTableDatas() params sqlObj:"+ JSON.toJSONString(sqlObj));
        logger.info("====>wyw getDevTableDatas() params columns:"+ JSON.toJSONString(columns));
        String tFields = 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_public.toSqlForSplitPage(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 sqlPrimaryKey = Util.null2String(sqlObj.getString("sqlprimarykey"));
        String openPrimaryKeyOrder = sqlObj.getString("openprimarykeyorder");
        String mergeOrder = sqlObj.getString("mergeorder");

        tOrder = Util_public.createSqlOrder(sortParams, tOrder, tOrderWay, sqlPrimaryKey,
                BoolAttr.TRUE.getStringVal().equals(openPrimaryKeyOrder),BoolAttr.TRUE.getStringVal().equals(mergeOrder));

        String tGroupBy = Util.null2String(sqlObj.getString("sqlgroupby")).trim();

        // 》》》
        StringBuilder sb = new StringBuilder();
        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"));
        if (!"".equals(tOrder))
            sb.append(" order by ").append(tOrder);
        // 偏移量
        int minNum = Integer.parseInt(min);
        minNum = minNum > 0 ? minNum - 1 : 0;
        String sqlnew = "";
        if (!"".equals(max) && !"".equals(min)){
//            sb.append(" limit (").append(minNum).append(",").append(max).append(")");
            int maxNum = Integer.parseInt(max);
            int cou = maxNum - minNum;
            new BaseBean().writeLog("==min:"+min+" minNum:"+minNum+" max:"+max+" maxNum:"+maxNum);

            sqlnew = " select skip "+minNum+" first "+cou+" t0.* from ("+sb.toString()+") as t0 ";
            new BaseBean().writeLog("==sqlnew:"+sqlnew);

        }else{
            sqlnew = sb.toString();
        }

        new BaseBean().writeLog("==sqlnew:"+sqlnew);

		/*
		===============================================================================
        sb.append(" select r.* ");
        if (sqlObj.containsKey("outfields")
                && !"".equals(sqlObj.getString("outfields"))) {
            sb.append(" ,").append(sqlObj.getString("outfields"));
        }
        sb.append(" from (select tmp.*,rownum as rn 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"));
        if (!"".equals(tOrder))
            sb.append(" order by ").append(tOrder);
        //优化执行效率 AndyZhang
        if (!"".equals(max)) {
            sb.append(" ) tmp where rownum <= ").append(max).append(" ) r");
        } else{
            sb.append(" ) tmp  ) r");
        }
        sb.append(" where 1=1");
        if (!"".equals(min))
            sb.append(" and r.rn>=").append(min);
        ===============================================================================
		 */
		/*if (!"".equals(max))
			sb.append(" and r.rn<=").append(max);*/
        //logger.info(sb.toString());

        logger.info("====> getDevTableDatas() sql : "+ sb.toString());
        timeMarker.mark("create sql");
        return this.setDevTableDatas(sqlObj, sqlnew, columns, getBroList, timeMarker);
    }

    /**
     * TODO
     *
     * @param sqlObj
     * @return
     */
    @Override
    public int getDevTableCount(JSONObject sqlObj) {
        // TODO Auto-generated method stub
        return d.getDevTableCount(sqlObj);
    }

    /**
     * TODO
     *
     * @return
     */
    @Override
    public boolean checkModeSkip(int customid) {
        // TODO Auto-generated method stub
        return d.checkModeSkip(customid);
    }

    /**
     * TODO
     *
     * @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);
            // 目前不能先删除后添加了。
            // rst.executeSql("delete from user_default_col where pageId='"+pageId+"'"+" and userId = "+user.getUID());
            // String dbname = "  ";
            // " user_default_col ";

            // if (!"".equals(pageUid))
            // dbname = " cloudstore_defcol ";
            sql = "update cloudstore_defcol 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 cloudstore_defcol 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 cloudstore_defcol 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 cloudstore_defcol (id,sysid,pageUid,userid,orders,display"
                            + ") values(cloudstore_defcol_seq.nextval,'"
                            + 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 user
     * @param pageUid
     * @param i
     * @return
     */
    @Override
    public JSONObject getDestTable(User user, String pageUid, int i) {
        // TODO Auto-generated method stub
        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");

            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);
            }

            if (getRlist.size() == 0) {
                // if (0 == type) {
                // getRlist.addAll(getDestTable(user, excludeId, includeId,
                // pageId, pageUid, 1));
                // } else {
                // 用户没有设置自定义列

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

                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) {
                    // 系统表不存在这个表单，需要保存一次记录

                    rObj.put("msg", "needInit");
                    return rObj;
                }
            }
            rObj.put("status", true);
            rObj.put("datas", getRlist);
        }

        return rObj;
    }

    /**
     * TODO
     *
     * @param user
     * @param pageUid
     * @param i
     * @return
     */
    @Override
    public JSONArray getSrcTable(User user, String pageUid, int i) {
        // TODO Auto-generated method stub
        RecordSet rs = new RecordSet();
        JSONArray getRlist = new JSONArray();
        StringBuilder sql2 = new StringBuilder();
        String dbname = "  cloudstore_defcol ";
        // " user_default_col ";
        // if (!"".equals(pageUid) && 0 == type)
        // 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(")");
        } 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;
    }

    /**
     * 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 (id,uuid,pageuid,key,display,orders,orderkey,text)values(cloudstore_sdfcol_seq.nextval,'"
                            + 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 (id,uuid,pageuid,key,display,orders,orderkey,text)values(cloudstore_sdfcol_seq.nextval,'"
                            + 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 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
     * @return
     */
    @Override
    public void insertUserSetting(int uid, String isload) {
        // TODO Auto-generated method stub

        RecordSet rs = new RecordSet();
        sql = "insert into HrmUserSetting(id,resourceid,rtxOnload,isCoworkHead,skin,cutoverWay,transitionTime,transitionWay) values(HRMUSERSETTING_ID.nextval,"
                + 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) {
        // TODO Auto-generated method stub
        RecordSet rs = new RecordSet();
        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) {
        // TODO Auto-generated method stub
        RecordSet rs = new RecordSet();
        sql = "insert into ecology_pagesize(id,pageId,pageSize,userid) values(ECOLOGY_PAGESIZE_ID.nextval,'"
                + 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) {
        // TODO Auto-generated method stub
        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;
    }

    @Override
    public Map<String, String> getSqlSum(JSONObject sp, String[] sumlist,
                                         Map<String, String> allSumMap) {
        // TODO Auto-generated method stub
        return d.getSqlSum(sp, sumlist, allSumMap);
    }

    @Override
    public boolean clearShowCol(String pageUid) {
        return d.clearShowCol(pageUid);
    }

    @Override
    public boolean clearShowCol(String pageUid, int uid) {
        return d.clearShowCol(pageUid, uid);
    }

    @Override
    public List<UserDefCol> getUserDefColumns(String pageUid, int uid) {
        return d.getUserDefColumns(pageUid, uid);
    }

    @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();
        }*/
    }

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

            String sqlWhere="";
            String sqlWhereAll="";
            List params=new ArrayList();
            if (OrgType.COMPANY==orgType){
                List<String> depList=d.getDepList(orgId);
                sqlWhere="  subcompanyid1 in  "+ WeaCommon.createWhereInSQL(orgId,params);
                sqlWhereAll=" where "+sqlWhere ;
                if (def==2)
                    rs.executeQuery("delete from cloudstore_defcol where pageuid=?  "+sqlWhere,pageuid);
                else
                    rs.executeQuery("delete from cloudstore_defcol where sysid<>? and pageuid=?  "+sqlWhere,def,pageuid);
                //logger.info("清除设置："+pageuid);
            }

            if (OrgType.DEPARTMENT==orgType){

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

            if (OrgType.PERSON==orgType){

                sqlWhere=" where id in "+WeaCommon.createWhereInSQL(orgId,params);
                sqlWhereAll=" where "+sqlWhere ;
                if (def==2)
                    rs.executeQuery("delete from cloudstore_defcol where pageuid=?  "+sqlWhere,pageuid);
                else
                    rs.executeQuery("delete from cloudstore_defcol where sysid<>'def' and pageuid=?  "+sqlWhere,pageuid);
            }

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

                sql=" Insert into cloudstore_defcol(id,userid,sysid,pageuid,orders,display,dataindex,width) ";
                sql+=" select cloudstore_defcol_seq.nextval,id,?,?,?,1,?,'' from HrmResource "+sqlWhereAll;

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

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

                sql=" Insert into cloudstore_defcol(id,userid,sysid,pageuid,orders,display,dataindex,width) ";
                sql+=" select cloudstore_defcol_seq.nextval,id,?,?,?,0,?,'' from HrmResource "+sqlWhereAll;

                rs.executeUpdate(sql,paramsReal);
                logger.info("SQL执行成功：def："+def+":"+sql);
                if (def==2){
                    ArrayList<Object> paramsDef=new ArrayList<>();
                    paramsDef.add("def");
                    paramsDef.add(pageuid);
                    paramsDef.add(i);
                    paramsDef.add(dataIndex);
                    rs.executeUpdate(sql,paramsDef);
                }
            }
            logger.info("SQL执行成功："+pageuid);
            LogUtil.writeBizLog(bizLogContext);
        }
        catch (Exception ex	) {
            logger.error(ex.getMessage());
            return  false;
        }

        return true;
    }

    @Override
    public List<String> getDepList(String departmentIds) throws Exception {
        return d.getDepList(departmentIds);
    }


	/*@Override
	public void setExpandOperate(int uid, String pageId, String value) {
		RecordSet rs=new RecordSet();
		boolean hasOperate=false;
		String sql = "select Operate from ecology_pagesize where pageId = ? and userid= ? ";
		if (rs.executeQuery(sql,uid,pageId))
			hasOperate=rs.next();
		if (!hasOperate) {
			sql = "insert into ecology_pagesize(id,pageId,Operate,userid) values(ECOLOGY_PAGESIZE_ID.nextval,?,?,?)";
			if (!rs.executeQuery(sql, pageId, value, uid)) {
				logger.error("insertPageSize wrong sql :" + sql);
			}
		}
		else{
			sql = "update ecology_pagesize set Operate=? where pageId=? and userid=?";
			if (!rs.executeQuery(sql,value,pageId,uid)) {
				logger.error("updatePageSize wrong sql :" + sql);
			}
		}
	}

	@Override
	public String getExpandOperate(int uid, String pageId) {
		return d.getExpandOperate(uid,pageId);
	}*/

    private void batchInsert(List<UserDefCol> cols) {
        RecordSet rs = new RecordSet();
        for (UserDefCol col : cols) {
            StringBuilder builder = new StringBuilder("insert into cloudstore_defcol ( id, dataIndex,sysid, orders, display, pageUid,userid,width) values ");
            List<Object> params = Lists.newArrayList();
            builder.append("(cloudstore_defcol_seq.nextval,?,'nullSysId',?,?,?,?,?)");
            params.add(col.getDataIndex());
            params.add(col.getOrders());
            params.add(col.getDisplay());
            params.add(col.getPageUid());
            params.add(col.getUserId());
            params.add(col.getWidth());
            rs.executeUpdate(builder.toString(), params.toArray());
        }
    }
}
