package com.weaver.formmodel.util;

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

import weaver.conn.RecordSet;
import weaver.general.StaticObj;
import weaver.interfaces.datasource.DataSource;
import weaver.servicefiles.DataSourceXML;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.stat.TableStat.Column;

public class SQLParseHelper {

    public static String getDbType(String poolname){
        String dbType;
        if (StringHelper.isEmpty(poolname) || DataSourceXML.SYS_LOCAL_POOLNAME.equals(poolname)) {
        	dbType = new RecordSet().getDBType(poolname);
        } else {
            DataSource datasource = (DataSource) StaticObj.getServiceByFullname("datasource."+poolname, DataSource.class);
            dbType = datasource.getType();
        }
        return dbType;
    }
    
    public static SchemaStatVisitor getSchemaVisitor(String sql, String datasource){
        String dbType = getDbType(datasource);
        List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
        SQLStatement stmt = stmtList.get(0);
        SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(dbType);
        stmt.accept(visitor);
        return visitor;
    }
    
    public static List<String> formatAndSplit(String sql, String datasource){
        String dbType = getDbType(datasource);
        String format = SQLUtils.format(sql, dbType);
        String[] lines = format.split("\n");
        List<String> mainLines = new ArrayList<>();
        for(int i = 0; i < lines.length; i++){
            String currLine = lines[i];
            if(currLine.startsWith("\t")){
                String currMainLine = mainLines.remove(mainLines.size()-1);
                currMainLine += currLine.replace("\t", " ");
                mainLines.add(currMainLine);
            }else{
                mainLines.add(currLine);
            }
        }
        return mainLines;
    }
    
    public static Map<String, Object> getOrderByMap(String sql, String datasource){
        SchemaStatVisitor visitor = getSchemaVisitor(sql, datasource);
        List<Column> orderbyColumns = visitor.getOrderByColumns();
        Map<String, Object> orderByMap = null;
        if(orderbyColumns != null && orderbyColumns.size() > 0){
            orderByMap = orderbyColumns.stream().collect(Collectors.toMap(Column::getName, c -> {
                Object orderType = c.getAttributes().get("orderBy.type");
                if(orderType == null){
                    orderType = "ASC";
                }
                return orderType;
            }));
        }
        return  orderByMap;
    }


    public static void main(String[] args) {
        String sql= "select id, lastname, loginid, (select departmentname from HrmDepartment where id=departmentid) deptname from hrmresource "
                + "where loginid like '%y%' and lastname like '%{searchKey}%' and managerid=? and id < 100 "
                + "order    by id asc,loginid desc";
        
//        sql = "select a.SecuCode,a.ChiName,a.ChiNameAbbr,a.EngName,b.SecondIndustryName,b.ssztbk,b.zyyw,b.cs,b.wz,c.zyywjs,dydgd,cwbbfx "
//                + "from secumain a left join zhym_dwzt b on a.InnerCode=b.InnerCode "
//                + "left join zhym_dyzt c on a.InnerCode=c.innercode order by a.innercode asc";
        
        System.out.println("orderBy:");
        System.out.println(getOrderByMap(sql, null));
        
        System.out.println("\nformatAndSplit:");
        System.out.println(formatAndSplit(sql, null).stream().collect(Collectors.joining(" ")));
    }

}
