package weaver.interfaces.htsc.workflow.odoc;


import com.alibaba.fastjson.JSON;
import com.engine.htsc.workflow.util.WorkflowUtil;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;
import weaver.workflow.request.SubWorkflowTriggerService;

import java.util.*;

public class ReceiptSubWorkflowAction extends BaseBean implements Action {

    @Override
    public String execute(RequestInfo requestInfo) {
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        User user = requestInfo.getRequestManager().getUser();
        String requestid = requestInfo.getRequestid();
        String nodeid = String.valueOf(requestInfo.getRequestManager().getNodeid());
        String tablename = requestInfo.getRequestManager().getBillTableName();//主表
        writeLog("----ReceiptSubWorkflowAction-------" + requestid);
        try {
            String fsjxbz = "";
            String sql2 = "select fsjxbz from "+tablename+" where requestid = '"+requestid+"'";
            writeLog(sql2);
            rs.executeQuery(sql2);
            if(rs.next()){
                fsjxbz = Util.null2String(rs.getString("fsjxbz"));
            }
            if("1".equals(fsjxbz)){
                return Action.SUCCESS;
            }
            String updateSql = "update "+tablename+" set fsjxbz = '1' where requestid = '"+requestid+"'";
            writeLog(updateSql);
            rs.executeUpdate(updateSql);


            String paramSubwfSetId_ldsy = pb.getPropName("receipt-subwfset-bgs-ldsy");
            String paramSubwfSetId_zbbm = pb.getPropName("receipt-subwfset-bgs-zbbm");
            String paramSubwfSetId_xbbm = pb.getPropName("receipt-subwfset-bgs-xbbm");
            String paramSubwfSetId_kybm = pb.getPropName("receipt-subwfset-bgs-yz");

            String creater = pb.getPropName("receipt-subwfset-creater");
            String sql = "select id from hrmresource where loginid = '"+creater+"'";
            writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                int createrid = Util.getIntValue(rs.getString("id"));
                user = new User(createrid);
            }

            String fzldsp = "";
            String fzkybm = "";
            String fzzbbmld = "";
            sql = "select fzldsp,fzkybm,fzzbbmld from "+tablename+" where requestid = '"+requestid+"'";
            writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                fzldsp = Util.null2String(rs.getString("fzldsp"));
                fzkybm = Util.null2String(rs.getString("fzkybm"));
                fzzbbmld = Util.null2String(rs.getString("fzzbbmld"));
            }

            if(StringUtils.isNotEmpty(fzldsp)){//领导审阅
                writeLog("paramSubwfSetId_ldsy:"+paramSubwfSetId_ldsy);
                creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId_ldsy);
            }
            if(StringUtils.isNotEmpty(fzkybm)){//看阅部门
                writeLog("paramSubwfSetId_kybm:"+paramSubwfSetId_kybm);
                creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId_kybm);
            }
            if(StringUtils.isNotEmpty(fzzbbmld)){//主办部门
                writeLog("paramSubwfSetId_zbbm:"+paramSubwfSetId_zbbm);
                creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId_zbbm);
            }

            //协办部门
            String mainid = "";
            String xbbmry = "";//协办部门人员
            String sxbbm = "";//送协办部门
            sql = "select id,xbbmry,sxbbm from "+tablename+" where requestid = '"+requestid + "'";
            writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainid = Util.null2String(rs.getString("id"));
                xbbmry = Util.null2String(rs.getString("xbbmry"));
                sxbbm = Util.null2String(rs.getString("sxbbm"));
            }
            if("1".equals(sxbbm)&&StringUtils.isNotEmpty(xbbmry)){
                for(String userid:xbbmry.split(",")){
                    String update_sql = "update "+tablename+" set fzxbbmld = '"+userid+"' where requestid = '"+requestid+"'";
                    writeLog(update_sql);
                    rs.executeUpdate(update_sql);
                    writeLog("paramSubwfSetId_xbbm:"+paramSubwfSetId_xbbm);
                    creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId_xbbm);
                }
            }

//            List<Map<String,Object>> xbList = new ArrayList<>();
//            sql = "select bmld,xbblry from "+tablename+"_dt8 t where sfsxb = '1' and mainid = '"+mainid+"'";
//            writeLog(sql);
//            rs.executeQuery(sql);
//            while(rs.next()){
//                Map<String,Object> xb = new HashMap<>();
//                xb.put("bmld", StringUtils.isNotEmpty(Util.null2String(rs.getString("bmld")))?Util.null2String(rs.getString("bmld")):"");
//                xb.put("xbblry",StringUtils.isNotEmpty(Util.null2String(rs.getString("xbblry")))?Util.null2String(rs.getString("xbblry")):"");
//                xbList.add(xb);
//            }
//            for(Map<String,Object> xb:xbList){
//                String update_sql = "update "+tablename+" set fzxbbmld = '"+xb.get("bmld")+"',fzxbry = '"+xb.get("xbblry")+"' where requestid = '"+requestid+"'";
//                writeLog(update_sql);
//                rs.executeUpdate(update_sql);
//                writeLog("paramSubwfSetId_xbbm:"+paramSubwfSetId_xbbm);
//                creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId_xbbm);
//            }

            getSubProcessInfo(requestid);
        }catch (Exception e) {
            e.printStackTrace();
            writeLog("ReceiptSubEndAction error:" + e);
            requestInfo.getRequestManager().setMessageid("222222");
            requestInfo.getRequestManager().setMessagecontent("流程提交异常,请联系管理员!");
            return Action.FAILURE_AND_CONTINUE;
        }finally {
            String updateSql = "update "+tablename+" set fsjxbz = '0' where requestid = '"+requestid+"'";
            writeLog(updateSql);
            rs.executeUpdate(updateSql);
        }
        return Action.SUCCESS;
    }

    private Map<String, Object> creatrSubWorkflow(User user, String requestid, String nodeid, String paramSubwfSetId){
        BaseBean bs = new BaseBean();
        Map<String, Object> apidatas = new HashMap<String, Object>();
        int requestId = weaver.general.Util.getIntValue(requestid, 0);
        int nodeId = weaver.general.Util.getIntValue(nodeid, 0);
        String triggerTime = "1";
        String hasTriggeredSubwf = "";
        String triggerType = "2";
        try {
            RequestManager mainRequest = new RequestManager();
            RecordSet rs = new RecordSet();
            String sql = "select a.*,b.isbill,b.formid from workflow_requestbase a inner join workflow_base b on a.workflowid=b.id where a.requestid= '"+requestId+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if (rs.next()) {
                mainRequest.setWorkflowid(weaver.general.Util.getIntValue(rs.getString("workflowid"), 0));
                mainRequest.setCreater(weaver.general.Util.getIntValue(rs.getString("creater"), 0));
                mainRequest.setCreatertype(weaver.general.Util.getIntValue(rs.getString("createrType"), 0));
                mainRequest.setRequestid(requestId);
                mainRequest.setRequestname(rs.getString("requestname"));
                mainRequest.setRequestlevel(rs.getString("requestlevel"));
                mainRequest.setMessageType(rs.getString("messagetype"));
                mainRequest.setSrc("submit");
                mainRequest.setIsbill(weaver.general.Util.getIntValue(rs.getString("isbill"), 0));
                mainRequest.setFormid(weaver.general.Util.getIntValue(rs.getString("formid"), 0));
            }
            SubWorkflowTriggerService triggerService = new SubWorkflowTriggerService(mainRequest, nodeId, hasTriggeredSubwf, user);
            triggerService.triggerSubWorkflow(triggerType, triggerTime, paramSubwfSetId);
            apidatas.put("type", "SUCCESS");
        } catch (Exception e) {
            apidatas.put("type", "FAILD");
        }
        return apidatas;
    }

    private void getSubProcessInfo(String mainRequestId){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        bs.writeLog("----Receipt-getSubProcessInfo-------" + mainRequestId);
        try {
            String mainTableName = JAVATools.getMaintable(mainRequestId);
            String mainId = "";
            String sql = "select id from "+mainTableName+" where requestid = '"+mainRequestId + "'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainId = weaver.general.Util.null2String(rs.getString("id"));
            }

            //获取需要新增的子流程Id
            List<String> allList = new ArrayList<>();
            List<String> currentList = new ArrayList<>();
            List<String> newList = new ArrayList<>();
            sql = "select subrequestid from WORKFLOW_SUBWFREQUEST where mainrequestid = '"+mainRequestId+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                allList.add(weaver.general.Util.null2String(rs.getString("subrequestid")));
            }
            sql = "select lcmc from "+mainTableName+"_dt11 where mainid = '"+mainId+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                currentList.add(weaver.general.Util.null2String(rs.getString("lcmc")));
            }
            for(String subRequestId:allList){
                if(!currentList.contains(subRequestId)){
                    newList.add(subRequestId);
                }
            }
            for(String subRequestId:newList){
                //获取子流程表名
                String subTableName = "";
                sql = "select t3.tablename from WORKFLOW_REQUESTBASE t1,WORKFLOW_BASE t2,WORKFLOW_BILL t3 "
                        +"where t2.id = t1.workflowid and t3.id = t2.formid and t1.requestid = '"+subRequestId+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    subTableName = weaver.general.Util.null2String(rs.getString("tablename"));
                }

                //获取子流程信息
                String requestNumber = "";
                String requestHandler = "";
                String requestDept = "";
                String requestTime = "";
                String subWorkflowid = "";
                sql = "select workflowid,requestmark,createdate,createtime from WORKFLOW_REQUESTBASE where requestid = '"+subRequestId+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    subWorkflowid = weaver.general.Util.null2String(rs.getString("workflowid"));
                    requestTime = weaver.general.Util.null2String(rs.getString("createdate"))+" "+ weaver.general.Util.null2String(rs.getString("createtime"));
                }
                sql = "select lcbh from "+subTableName+" where requestid = '"+subRequestId + "'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    requestNumber = weaver.general.Util.null2String(rs.getString("lcbh"));
                }
                String update_sql = "update WORKFLOW_REQUESTBASE set requestmark = '"+requestNumber+"' where requestid = '"+subRequestId+"'";
                bs.writeLog(update_sql);
                rs.executeUpdate(update_sql);


                String gsswldsy = pb.getPropName("gsswldsy");
                String gsswldsy_workflowid = pb.getActiveWorkflowIdByUnNumber(gsswldsy);
                bs.writeLog("gsswldsy:"+gsswldsy);
                bs.writeLog("gsswldsy_workflowid:"+gsswldsy_workflowid);

                String gsswyz = pb.getPropName("gsswyz");
                String gsswyz_workflowid = pb.getActiveWorkflowIdByUnNumber(gsswyz);
                bs.writeLog("gsswyz:"+gsswyz);
                bs.writeLog("gsswyz_workflowid:"+gsswyz_workflowid);

                if(subWorkflowid.equals(gsswldsy_workflowid)){
                    sql = "select fzldsp from "+subTableName+" where requestid = '"+subRequestId + "'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        requestHandler = weaver.general.Util.null2String(rs.getString("fzldsp"));
                    }
                }else if(subWorkflowid.equals(gsswyz_workflowid)){
                    sql = "select fzkybm from "+subTableName+" where requestid = '"+subRequestId + "'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        requestHandler = weaver.general.Util.null2String(rs.getString("fzkybm"));
                    }
                }else{
                    List<String> handlerList = new ArrayList<>();
                    sql = "select userid from WORKFLOW_CURRENTOPERATOR where requestid = '"+subRequestId+"' and isremark = '0'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    while(rs.next()){
                        handlerList.add(weaver.general.Util.null2String(rs.getString("userid")));
                    }
                    requestHandler = String.join(",",handlerList);
                }

                Set<String> deptSet = new LinkedHashSet<>();
                List<String> handlerList = Arrays.asList(requestHandler.split(","));
                for(String handler:handlerList){
                    sql = "select departmentid from HRMRESOURCE where id = '"+handler+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        deptSet.add(weaver.general.Util.null2String(rs.getString("departmentid")));
                    }
                }
                requestDept = String.join(",",deptSet);

                List<String> deptNameList = new ArrayList<>();
                DepartmentComInfo departmentComInfo = new DepartmentComInfo();
                for(String deptid:deptSet){
                    String showName = departmentComInfo.getDepartmentname(deptid);
                    String orgid = "";
                    sql = " select l.id from (select t.id from HrmDepartment t where t.supdepid is null or t.supdepid = 0 start with t.id="+deptid+" connect by prior t.supdepid=t.id ) l";
                    rs.execute(sql);
                    if(rs.next()){
                        orgid = com.weaver.general.Util.null2String(rs.getString("id"));
                    }
                    if(!deptid.equals(orgid)){
                        String orgName = WorkflowUtil.getTopDeptShortName(orgid);
                        showName = showName+"("+orgName+")";
                    }
                    deptNameList.add(showName);
                }
                String deptNameStr = String.join(" ", deptNameList);

                String subWorkflowUnNumber = "";
                if(!"".equals(subWorkflowid)){
                    subWorkflowUnNumber = pb.getWorkflowUnNumberByid(subWorkflowid);
                }
                bs.writeLog("subWorkflowUnNumber:"+subWorkflowUnNumber);

                String insert_sql = "insert into " + mainTableName + "_dt11(mainid,lcmc,lcbh,lcclr,fsbm,bm,lcfqsj,lclx,sfbj) "
                        +"values('"+mainId+"','"+subRequestId+"','"+requestNumber+"','"+requestHandler+"','"+requestDept+"','"+deptNameStr+"','"+requestTime+"','"+subWorkflowUnNumber+"','"+0+"')";
                bs.writeLog(insert_sql);
                rs.executeUpdate(insert_sql);
            }
        } catch (Exception e) {
            e.printStackTrace();
            bs.writeLog("error---------------",e);
        }
    }
}
