package com.engine.htxc.commonutil.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.engine.htxc.commonutil.log.CustomizeLog;
import com.engine.integration.util.StringUtils;

import weaver.conn.RecordSet;
import weaver.general.Util;

/**
 * <p>
 * 文件夹将慢慢代替JAVATool（命名不规范、代码不规格）这个文件/p>
 * <p>
 * 关于数据库层面的操作
 * </p>
 * 
 * @author K1810015
 * @version 1.0.0
 * @ClassName DbTools.java
 * @createTime 2022年04月08日 14:46:00
 */
public class DbTools {
    private RecordSet rs = new RecordSet();
    private RecordSet rsupdate = new RecordSet();
    private RecordSet rsinsert = new RecordSet();
    private RecordSet redelete = new RecordSet();
    public String dbpk = "id";

    /**
     * <p>
     * 获取requestname
     * </p>
     * 
     * @title getRequesName
     * @author K1810015
     * @updateTime 2022/4/8 14:49
     * @throws
     */
    public String getRequesName(Map<String, Object> map) {
        String value = "";
        if (map == null || map.size() <= 0) {
            return value;
        }
        String requestid = Util.null2String(map.get("requestid"));
        if (StringUtils.isBlank(requestid)) {
            return value;
        }
        String sql = " select requestname from workflow_requestbase where requestid=?";
        Map<String, Object> mapvalue = getsqltomap(sql, requestid);
        if (mapvalue == null || mapvalue.size() <= 0) {
            return value;
        }
        return Util.null2String(mapvalue.get("requestname"));
    }

    /**
     * <p>
     * 根据requestid 获取表名
     * </p>
     * 
     * @title gettablename
     * @author K1810015
     * @param requestid
     *            requestid
     * @updateTime 2022/4/25 10:47
     */
    public String getTableName(String requestid) {
        if (StringUtils.isBlank(requestid)) {
            return "";
        }
        String sql = " select abs(t.formid) as formid \n" + " from workflow_base t\n"
            + " inner join workflow_requestbase l on l.workflowid = t.id\n" + " where l.requestid=" + requestid + "";
        rs.execute(sql);
        String formid = "formtable_main_";

        if (rs.next()) {
            formid = formid + com.weaver.general.Util.getIntValues(rs.getString("formid"));
        }
        return formid;
    }

    /**
     * <p>
     * 根据自有节点的nodenumber获取id
     * </p>
     * 
     * @title getNodeunnumberToid
     * @author K1810015
     * @updateTime 2022/8/15 10:07
     * @throws
     */
    public String getNodeunnumberToid(String nodeunnumber) {
        if (StringUtils.isBlank(nodeunnumber)) {
            return "";
        }
        String sql = " select id from workflow_nodebase  where unnumber=?";
        return getsqlonevalue(sql, nodeunnumber);
    }


    public  String getRequestidByRequestMark(String requestMark) {
        RecordSet rs = new RecordSet();
        String requestid = "";
        if (org.apache.commons.lang.StringUtils.isNotEmpty(requestMark)) {
            String sql = "select requestid from workflow_requestbase where requestMark = '" + requestMark + "'";
            rs.executeQuery(sql);
            if (rs.next()) {
                requestid = Util.null2String(rs.getString("requestid"));
            }
        }
        return requestid;
    }

    public String getFormmodeidToTable(String formid){
        if(StringUtils.isBlank(formid)){
            return "";
        }
        String sql=" select wb.tablename from modeinfo  m inner join workflow_bill wb on m.formid=wb.id where m.id=?";
        return this.getsqlonevalue(sql,formid);
    }

    public String getFormidToTable(String formid){
        if(StringUtils.isBlank(formid)){
            return "";
        }
        String sql="select tablename from workflow_bill where id=?";
        return this.getsqlonevalue(sql,formid);
    }
    /**
     * <p>
     * 根据requestid 获取表名
     * </p>
     * 
     * @title getUnnumberToTablename
     * @author K1810015
     * @param unnumber
     * @updateTime 2022/4/25 10:47
     * @throws
     */
    public String getUnnumberToTablename(String unnumber) {
        if (StringUtils.isBlank(unnumber)) {
            return "";
        }
        String sql =
            " select abs(t.formid) as formid " + " from workflow_base t " + " where t.unnumber='" + unnumber + "'";

        String formid = "formtable_main_";
        return (formid + getsqlonevalue(sql, (Object)null));

    }

    //获取主表的number
    public  String getmainunnumber(String reqid) {
        String sql = " select t.unnumber as unnumber \n" +
                " from workflow_base t\n" +
                " inner join workflow_requestbase l on l.workflowid = t.id\n" +
                " where   rownum=1 and l.requestid=" + reqid + "";
        String unnumber = getsqlonevalue(sql);
        return unnumber;
    }



    /**
     * <p>
     * 查询sql语句，并且返回一个list
     * </p>
     * 
     * @title getsqltolist
     * @author K1810015
     * @param sql
     *            sql语句
     * @param value
     *            占位符参数
     * @updateTime 2022/8/17 21:17
     */
    public List<Map<String, Object>> getSqlToList(String sql, Object... value) {
        List<Map<String, Object>> listreturn = new ArrayList<>();

        if (value == null || value.length <= 0 || value.length <= 0 || value[0] == null
            || StringUtils.isBlank(Util.null2String(value))) {
            rs.execute(sql);
        } else {
            rs.executeQuery(sql, value);
        }

        while (rs.next()) {
            Map<String, Object> map = new HashMap<>(1);
            String[] colnums = rs.getColumnName();
            for (String colnumvalue : colnums) {
                map.put(colnumvalue.toLowerCase(), rs.getString(colnumvalue));
            }
            listreturn.add(map);

        }
        return listreturn;
    }

    /**
     * <p>
     * 根据一个request和fieldlist字段获取主表数据
     * </p>
     * 
     * @title getRequestidToMap
     * @author K1810015
     * @param requestid
     * @param fieldlist
     * @updateTime 2022/8/17 21:49
     */
    public Map<String, Object> getRequestidToMap(String requestid, List<String> fieldlist) {
        Map<String, Object> map = new HashMap<>(1);
        if (StringUtils.isBlank(requestid)) {
            return map;
        }
        String tablename = getTableName(requestid);
        if (StringUtils.isBlank(tablename)) {
            return map;
        }
        String fieldvalue = "*";
        if (fieldlist != null && fieldlist.size() > 0) {
            if (!fieldlist.contains(dbpk)) {
                fieldlist.add(dbpk);
            }
            fieldvalue = fieldlist.stream().collect(Collectors.joining(","));
        }
        String sql = "select " + fieldvalue + " from " + tablename + " where requestid=?";
        map = getsqltomap(sql, requestid);
        return map;
    }

    /**
     * <p>
     * 根据一个request和fieldlist字段获取主表数据-多条
     * </p>
     * 
     * @title getRequestidToMapList
     * @author K1810015
     * @param requestid
     * @param fieldlist
     * @updateTime 2022/8/17 21:49
     */
    public List<Map<String, Object>> getRequestidToMapList(String requestid, List<String> fieldlist, int detailnumber) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (StringUtils.isBlank(requestid) || detailnumber < 0) {
            return list;
        }
        String tablename = getTableName(requestid);
        if (StringUtils.isBlank(tablename)) {
            return list;
        }
        String fieldvalue = "*";
        if (fieldlist != null && fieldlist.size() > 0) {
            if (!fieldlist.contains(dbpk)) {
                fieldlist.add(dbpk);
            }
            fieldvalue = fieldlist.stream().collect(Collectors.joining(","));
        }
        String sql = "select " + fieldvalue + " from " + tablename + "_dt" + detailnumber
            + " where mainid in (select id from " + tablename + " where requestid=?)";
        list = getSqlToList(sql, requestid);
        return list;
    }

    /**
     * <p>
     * 根据一个sql查询对应的表数据
     * </p>
     * <p>
     * ps:只会返回一条数据
     * </p>
     * 
     * @title getsqltomap
     * @author K1810015
     * @param sql
     * @param value
     * @updateTime 2022/8/17 21:26
     */
    public Map<String, Object> getsqltomap(String sql, Object... value) {

        Map<String, Object> map = new HashMap<>(1);
        if (value == null || value.length <= 0 || value[0] == null || StringUtils.isBlank(Util.null2String(value))) {
            rs.execute(sql);
        } else {
            rs.executeQuery(sql, value);
        }
        if (rs.next()) {
            String[] colnums = rs.getColumnName();
            for (String colnumvalue : colnums) {
                map.put(colnumvalue.toLowerCase(), rs.getString(colnumvalue));
            }

        }
        return map;
    }

    /**
     * <p>
     * 考虑到rs占位符有可能会无效的情况下
     * </p>
     * 
     * @title gettabletomap
     * @author K1810015
     * @updateTime 2022/8/22 20:33
     */
    public Map<String, Object> gettabletomap(String tablename, Map<String, String> wheremap) {
        Map<String, Object> mapnew = new HashMap<>(1);
        if (StringUtils.isBlank(tablename) || wheremap == null || wheremap.size() <= 0) {
            return mapnew;
        }

        List<String> wherekey = new ArrayList<>();
        wheremap.entrySet().forEach(key -> {
            wherekey.add(key.getKey() + "='" + key.getValue() + "'");
        });
        String sql =
            " select * from " + tablename + " where 1=1 and " + wherekey.stream().collect(Collectors.joining(" and "));
        mapnew = this.getsqltomap(sql, (Object)null);
        return mapnew;
    }

    /**
     * <p>
     * 根据一个request和明细表号来获取数据
     * </p>
     * 
     * @title gettableall
     * @author K1810015
     * @param requestid
     *            requestid
     * @param detailid
     *            明细表行
     * @updateTime 2022/8/17 21:24
     */
    public List<Map<String, Object>> gettableall(String requestid, int detailid) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (StringUtils.isBlank(requestid)) {
            return list;
        }
        String tablename = getTableName(requestid);
        if (StringUtils.isBlank(tablename)) {
            return list;
        }
        String sql = "select * from " + tablename + " where 1=1 and requestid='" + requestid + "'";
        if (detailid > 0) {
            sql = "select * from " + tablename + "_dt" + detailid + " where mainid in (" + "select id from " + tablename
                + " where 1=1 and requestid='" + requestid + "' )";
        }
        list = getSqlToList(sql);
        return list;
    }

    /**
     * <p>
     * 查询sql的第一个值
     * </p>
     * 
     * @title getsqlonevalue
     * @author K1810015
     * @updateTime 2022/8/17 21:06
     */
    public String getsqlonevalue(String sql, Object... value) {

        String retvalue = "";

        if (value == null || value.length <= 0 || value[0] == null || StringUtils.isBlank(Util.null2String(value))) {
            rs.execute(sql);
        } else {
            rs.executeQuery(sql, value);
        }

        if (rs.next()) {
            String[] colnums = rs.getColumnName();
            if (colnums.length > 0) {
                retvalue = Util.null2String(rs.getString(colnums[0]));
            }
        }
        return retvalue;
    }

    /**
     * <p>
     * 传递一个特殊的字符获取参数
     * </p>
     * 
     * @title gettablefeild
     * @author K1810015
     * @param requestid
     * @param field
     * @updateTime 2022/7/15 10:40
     * @throws
     */
    public String getTableField(String requestid, String field) {
        if (StringUtils.isBlank(requestid)) {
            return "";
        }
        String tablename = getTableName(requestid);
        if (StringUtils.isBlank(tablename)) {
            return "";
        }
        String sql = "select " + field + " from " + tablename + " where 1=1 and requestid='" + requestid + "'";
        Map<String, Object> retmap = getsqltomap(sql);
        if (retmap == null || retmap.size() <= 0) {
            return "";
        }
        return Util.null2String(retmap.get(field));
    }

    /**
     * <p>
     * 根据表名、字段值插入
     * </p>
     * 
     * @title insert
     * @author K1810015
     * @param tablename
     * @param setmap
     * @updateTime 2022/8/17 22:00
     */
    public boolean insert(String tablename, Map<String, String> setmap) {
        if (StringUtils.isBlank(tablename) || setmap == null || setmap.size() <= 0) {
            return false;
        }
        List<String> setkey = new ArrayList<>();
        List<String> setvalue = new ArrayList<>();
        setmap.entrySet().forEach(key -> {
            setkey.add(key.getKey());
            setvalue.add(key.getValue());
        });
        String sql = " insert into " + tablename + "(" + setkey.stream().collect(Collectors.joining(",")) + ") values("
            + setkey.stream().map(item -> "?").collect(Collectors.joining(",")) + ")";
        return rsinsert.executeUpdate(sql, new Object[] {setvalue});
    }

    /**
     * 修改数据,根据表名、插入字段的值（Map）、查询条件值（Map）修改数据
     * 
     * @title updateSql
     * @author K1810015
     * @param tablename
     * @param setmap
     * @param wheremap
     * @updateTime 2022/8/17 22:01
     */
    public boolean updateSql(String tablename, Map<String, String> setmap, Map<String, String> wheremap) {
        if (StringUtils.isBlank(tablename) || setmap == null || setmap.size() <= 0 || wheremap == null
            || wheremap.size() <= 0) {
            return false;
        }
        List<String> setkey = new ArrayList<>();
        List<String> setvalue = new ArrayList<>();
        List<String> wherekey = new ArrayList<>();

        setmap.entrySet().forEach(key -> {
            setkey.add(key.getKey() + "=?");
            setvalue.add(key.getValue());
        });
        if (setkey.isEmpty()) {
            return false;
        }
        wheremap.entrySet().forEach(key -> {
            wherekey.add(key.getKey() + "='" + key.getValue() + "'");
        });
        if (wherekey.isEmpty()) {
            return false;
        }
        String sql = "update " + tablename + " set " + setkey.stream().collect(Collectors.joining(","))
            + " where 1=1 and  " + wherekey.stream().collect(Collectors.joining(" and "));
        return rsupdate.executeUpdate(sql, new Object[] {setvalue});

    }

    /**
     * <p>
     * 执行sql(增删改)
     * </p>
     * 
     * @title execteSql
     * @author K1810015
     * @param sql
     * @param value
     * @updateTime 2022/8/17 22:05
     */
    public boolean execteSql(String sql, Object... value) {
        boolean flag = false;
        if (value == null || value.length <= 0 || value[0] == null || StringUtils.isBlank(Util.null2String(value))) {
            flag = rs.execute(sql);
        } else {
            flag = rs.executeQuery(sql, value);
        }
        return flag;
    } 

    /**
     * 批量修改数据,根据表名、插入字段的值（Map）、插入主键的名称（pkey）， <br/>
     * 查询条件的wherelist
     * 
     * @title updateAllSql
     * @author K1810015
     * @param tablename
     * @param setmap
     * @param pkey
     * @updateTime 2022/8/17 22:01
     */
    public boolean updateAllSql(String tablename, Map<String, String> setmap, String pkey, List<String> wherelist) {
        if (StringUtils.isBlank(tablename) || setmap == null || setmap.size() <= 0 || wherelist == null
            || wherelist.size() <= 0) {
            return false;
        }
        List<String> setkey = new ArrayList<>();
        List<String> setvalue = new ArrayList<>();
        setmap.entrySet().forEach(key -> {
            setkey.add(key.getKey() + "=?");
            setvalue.add(key.getValue());
        });
        if (setkey.isEmpty()) {
            return false;
        }
        String sql = "update " + tablename + " set " + setkey.stream().collect(Collectors.joining(","))
            + " where 1=1 and   " + pkey + "  in ("
            + wherelist.stream().map(item -> "\'" + item + "\'").collect(Collectors.joining(",")) + ")";
        CustomizeLog.printLog("sql:" + sql);
        return rsupdate.executeUpdate(sql, new Object[] {setvalue});
    }

    /**
     * 批量插入数据,根据表名、插入字段的值（Map）、查询条件值（Map）插入数据
     * 
     * @title insertAllSql
     * @author K1810015
     * @param tablename
     * @param setlist
     * @updateTime 2022/8/17 22:01
     */
    public boolean insertAllSql(String tablename, List<Map<String, String>> setlist) {
        if (StringUtils.isBlank(tablename) || setlist == null || setlist.size() <= 0) {
            return false;
        }

        List<String> sqlvalue = new ArrayList<>();
        setlist.forEach((setmaptemp) -> {
            Map<String, String> setmap = (HashMap)setmaptemp;
            List<String> setkey = new ArrayList<>();
            List<String> setvalue = new ArrayList<>();
            setmap.entrySet().forEach(key -> {
                setkey.add(key.getKey());
                setvalue.add(key.getValue());
            });
            sqlvalue
                .add(" insert into " + tablename + "(" + setkey.stream().collect(Collectors.joining(",")) + ") values("
                    + setvalue.stream().map(item -> "'" + item + "'").collect(Collectors.joining(",")) + ");");
        });
        rsinsert.executeUpdate(sqlvalue.stream().collect(Collectors.joining()));
        return true;
    }

    /**
     * 删除数据,根据表名、插入字段的值（Map）、查询条件值（Map）删除数据
     * 
     * @title delete
     * @author K1810015
     * @param tablename
     * @param wheremap
     * @updateTime 2022/8/17 22:01
     */
    public boolean delete(String tablename, Map<String, Object> wheremap) {
        if (StringUtils.isBlank(tablename) || wheremap == null || wheremap.size() <= 0) {
            return false;
        }
        String sql = "delete from " + tablename + " where 1=1 and ";
        List<String> wherekey = new ArrayList<>();
        List<String> wherevalue = new ArrayList<>();
        wheremap.entrySet().forEach(key -> {
            wherekey.add(key.getKey() + "=?");
            wherevalue.add(Util.null2String(key.getValue()));
        });
        sql += wherekey.stream().collect(Collectors.joining("and"));
        return redelete.executeUpdate(sql, wherevalue.stream().distinct().collect(Collectors.joining(",")));
    }

    public int ifExist(String sql) {
        rs.executeQuery(sql);
        if (rs.next()){
            int num = rs.getInt("num");
            return num;
        }
        return 0;
    }
}
