package weaver.interfaces.htsc.workflowFile;

import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.customjavacode.AbstractCustomSqlConditionJavaCode;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class WorkflowDocid extends AbstractCustomSqlConditionJavaCode {

    public String generateSqlCondition(Map<String, Object> param) throws Exception {
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        User user = (User)param.get("user");
        String requestid = Util.null2String(param.get("requestid"));

        List<String> docidList = new ArrayList<>();
        String tableName = "";
        String fieldName = "";
        String sql = "select e.tablename,listagg (f.fieldname,',') within group(order by a.requestid) as fieldname " +
                "from workflow_requestbase a " +
                "left join workflow_freenode b on a.lastnodeid=b.id " +
                "left join workflow_nodebase c on a.lastnodeid=c.id " +
                "left join workflow_base d on a.workflowid=d.id " +
                "left join workflow_bill e on d.formid=e.id " +
                "left join workflow_billfield f on e.id=f.billid " +
                " where (fieldhtmltype='6' or type=9 ) and a.requestid = '"+requestid+"' " +
                "group by a.requestid,a.workflowid,a.creater,a.requestname,a.requestmark,a.lastnodeid,nvl(b.nodename,c.nodename) ,d.formid,e.tablename";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            tableName = Util.null2String(rs.getString("tablename"));
            fieldName = Util.null2String(rs.getString("fieldName"));
        }
        bs.writeLog("tableName:"+tableName);
        bs.writeLog("fieldName:"+fieldName);

        if(StringUtils.isNotEmpty(tableName)&&StringUtils.isNotEmpty(fieldName)){
            List<String> fieldList = Arrays.asList(fieldName.split(","));
            for(String field:fieldList){
                sql = "select regexp_substr("+field+", '[^,]+', 1, level)docid " +
                        "from "+tableName+" " +
                        "where requestid ='"+requestid+"' and "+field+" is not null " +
                        "connect by level <= regexp_count("+field+", '\\,\\') + 1" +
                        "and "+field+" = prior "+field+" and prior dbms_random.value > 0";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                while (rs.next()){
                    bs.writeLog("docid:"+Util.null2String(rs.getString("docid")));
                    docidList.add(Util.null2String(rs.getString("docid")));
                }
            }
        }

        String value = "t1.docid in ("+String.join(",",docidList)+")";
        bs.writeLog("value:"+value);
        return value;
    }
}
