package com.customization.htsc.receipt;

import com.alibaba.fastjson.JSON;
import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.htsc.workflow.util.WorkflowUtil;
import com.engine.workflow.cmd.requestForm.RequestSubmitCmd;
import com.engine.workflow.entity.requestForm.RequestOperationResultBean;
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.comInfo.PropBean;
import weaver.workflow.request.RequestManager;
import weaver.workflow.request.SubWorkflowTriggerService;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@CommandDynamicProxy(target = RequestSubmitCmd.class, desc = "公司收文触发子流程")
public class ReceiptSubWorkflowCmd extends AbstractCommandProxy<Map<String, Object>> {

    @Override
    public Map<String, Object> execute(Command<Map<String, Object>> targetCommand) {
        //获取到被代理对象
        RequestSubmitCmd requestSubmitCmd = (RequestSubmitCmd) targetCommand;
        HttpServletRequest request = requestSubmitCmd.getRequest();//从request中可以取到参数，不用以前的方法了
        User user = requestSubmitCmd.getUser();
        String requestid = Util.null2String(request.getParameter("requestid"));
        String workflowid = Util.null2String(request.getParameter("workflowid"));
        String nodeid = Util.null2String(request.getParameter("nodeid"));
        String src = Util.null2String(request.getParameter("src"));
        String receiptSubSign = Util.null2String(request.getParameter("receiptSubSign"));
        //执行标准的业务处理
        Map<String, Object> result = nextExecute(targetCommand);
        RequestOperationResultBean resultBean = (RequestOperationResultBean) result.get("data");
        String type = Util.null2String(resultBean.getType());
        if(StringUtils.isNotEmpty(receiptSubSign)&&"save".equalsIgnoreCase(src)&&"SUCCESS".equalsIgnoreCase(type)){
            BaseBean bs = new BaseBean();
            PropBean pb = new PropBean();

            String gssw = pb.getPropName("gssw");
            String recriptWorkflowid = pb.getActiveWorkflowIdByUnNumber(gssw);
            bs.writeLog("recriptWorkflowid:"+recriptWorkflowid);

            if(workflowid.equals(recriptWorkflowid)){
                bs.writeLog("----ReceiptSubWorkflow-------");
                try{
                    Map<String, Object> apidatas = new HashMap<String, Object>();
                    String paramSubwfSetId = "";
                    if("0".equals(receiptSubSign)){//领导审阅
                        paramSubwfSetId = pb.getPropName("receipt-subwfset-ldsy");
                        bs.writeLog("paramSubwfSetId:"+paramSubwfSetId);
                        apidatas = creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId);
                    }else if("1".equals(receiptSubSign)){//主办部门
                        paramSubwfSetId = pb.getPropName("receipt-subwfset-zbbm");
                        bs.writeLog("paramSubwfSetId:"+paramSubwfSetId);
                        apidatas = creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId);
                    }else if("3".equals(receiptSubSign)){//协办部门
                        paramSubwfSetId = pb.getPropName("receipt-subwfset-xbbmld");
                        bs.writeLog("paramSubwfSetId:"+paramSubwfSetId);
                        String mainTableName = "";
                        RecordSet rs = new RecordSet();
                        String 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 = '"+requestid+"'";
                        bs.writeLog(sql);
                        rs.executeQuery(sql);
                        if(rs.next()){
                            mainTableName = Util.null2String(rs.getString("tablename"));
                        }
                        String mainid = "";
                        sql = "select id from "+mainTableName+" where requestid = '"+requestid + "'";
                        bs.writeLog(sql);
                        rs.executeQuery(sql);
                        if(rs.next()){
                            mainid = Util.null2String(rs.getString("id"));
                        }

                        List<Map<String,Object>> xbList = new ArrayList<>();
                        sql = "select bmld,xbblry from "+mainTableName+"_dt8 t where sfsxb = '1' and mainid = '"+mainid+"'";
                        bs.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 "+mainTableName+" set fzxbbmld = '"+xb.get("bmld")+"',fzxbry = '"+xb.get("xbblry")+"' where requestid = '"+requestid+"'";
                            bs.writeLog(update_sql);
                            rs.executeUpdate(update_sql);
                            apidatas = creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId);
                        }

//                        String fzxbbmld = "";
//                        String fzxbry = "";
//                        sql = "select fzxbbmld,fzxbry from "+mainTableName+" where requestid = '"+requestid+"'";
//                        log.info(sql);
//                        rs.executeQuery(sql);
//                        if (rs.next()) {
//                            fzxbbmld = Util.null2String(rs.getString("fzxbbmld"));
//                            fzxbry = Util.null2String(rs.getString("fzxbry"));
//                        }
//
//                        if(StringUtils.isNotEmpty(fzxbbmld)){
//                            paramSubwfSetId = pb.getPropName("receipt-subwfset-xbbmld");
//                            log.info("paramSubwfSetId:"+paramSubwfSetId);
//                            apidatas = creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId);
//                            String update_sql = "update "+mainTableName+" set fzxbbmld = '' where requestid = '"+requestid+"'";
//                            log.info(update_sql);
//                            rs.executeUpdate(update_sql);
//                        }
//                        if(StringUtils.isNotEmpty(fzxbry)){
//                            paramSubwfSetId = pb.getPropName("receipt-subwfset-xbbmry");
//                            log.info("paramSubwfSetId:"+paramSubwfSetId);
//                            apidatas = creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId);
//                        }
                    }else if("6".equals(receiptSubSign)){//看阅部门
                        paramSubwfSetId = pb.getPropName("receipt-subwfset-yz");
                        bs.writeLog("paramSubwfSetId:"+paramSubwfSetId);
                        apidatas = creatrSubWorkflow(user,requestid,nodeid,paramSubwfSetId);
                    }
                    bs.writeLog("apidatas:"+JSON.toJSON(apidatas));
                    result.put("subwfResult",apidatas.get("type"));
                    getSubProcessInfo(requestid);
                }catch(Exception e){
                    result.put("subwfResult","FAILD");
                }
            }
            bs.writeLog("result:"+JSON.toJSON(result));
        }
        return result;
    }

    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 = Util.getIntValue(requestid, 0);
        int nodeId = 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(Util.getIntValue(rs.getString("workflowid"), 0));
                mainRequest.setCreater(Util.getIntValue(rs.getString("creater"), 0));
                mainRequest.setCreatertype(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(Util.getIntValue(rs.getString("isbill"), 0));
                mainRequest.setFormid(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 sql = "";

            //获取主流程表名
            String mainTableName = "";
            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 = '"+mainRequestId+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainTableName = Util.null2String(rs.getString("tablename"));
            }

            //获取主流程表内Id
            String mainId = "";
            sql = "select id from "+mainTableName+" where requestid = '"+mainRequestId + "'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainId = 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(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(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 = 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 = Util.null2String(rs.getString("workflowid"));
//                    requestNumber = Util.null2String(rs.getString("requestmark"));
                    requestTime = Util.null2String(rs.getString("createdate"))+" "+Util.null2String(rs.getString("createtime"));
                }
                sql = "select lcbh from "+subTableName+" where requestid = '"+subRequestId + "'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    requestNumber = 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 = 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 = 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(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(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);
        }
    }
}
