package weaver.interfaces.ythpt.workflow;

import com.engine.common.util.ServiceUtil;
import com.engine.secret.util.ConfigUtil;
import com.engine.workflow.biz.freeNode.FreeNodeBiz;
import com.engine.workflow.constant.PAResponseCode;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

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

/**
 * 审批复核 归档Action
 *
 * @author:dxfeng
 * @createTime: 2025/04/09
 * @version: 1.0
 */
public class WorkflowMonitorAction implements Action {
    private WorkflowRequestOperatePA getRequestOperatePA() {
        return (WorkflowRequestOperatePAImpl) ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        try {
            String ip = requestInfo.getRequestManager().getIp();
            int requestId = Util.getIntValue(requestInfo.getRequestid());
            String formTableName = requestInfo.getRequestManager().getBillTableName();
            User user = requestInfo.getRequestManager().getUser();
            String userId = String.valueOf(user.getUID());


            String spfhjl = "";
            String thgc = "";
            int zlcid = 0;
            String sql = "select spfhjl,zlcid,thgc from " + formTableName + " where requestid=" + requestId;
            rs.executeQuery(sql);
            if (rs.next()) {
                spfhjl = Util.null2String(rs.getString("spfhjl"));
                zlcid = Util.getIntValue(Util.null2String(rs.getString("zlcid")));
                thgc = Util.null2String(rs.getString("thgc"));
            }

            if("2".equals(spfhjl)){
                WorkflowRequestOperatePA operatePA = getRequestOperatePA();
                String nodeId  = "";
                if("0".equals(thgc)){
                    nodeId  = ConfigUtil.getConfig("smsc_nodeid");
                }else if("1".equals(thgc)){
                    nodeId  = ConfigUtil.getConfig("xcsc_nodeid");
                }

                if(StringUtils.isNotBlank(nodeId)){
                    bb.writeLog("~~~~doIntervenor接口报文~~~~userId:"+user.getUID());
                    if(zlcid > 0){
                        ReqOperateRequestEntity reqOperateRequestEntity = intervenor2Entity(zlcid,ip,userId,nodeId);
                        PAResponseEntity paResponseEntity = operatePA.doIntervenor(user,reqOperateRequestEntity);
                        PAResponseCode paResponseCode = paResponseEntity.getCode();
                        bb.writeLog("PAResponseCode:"+paResponseCode);
                        if(paResponseCode.getStatusCode() == 1){

                            List<String> list = new ArrayList<String>();
                            String xcscFormtable  = ConfigUtil.getConfig("xcsc_formtable");
                            sql = " select t.requestid " +
                                    " from "+xcscFormtable+" t " +
                                    " inner join workflow_requestbase k on k.requestid = t.requestid " +
                                    " where t.zlcid = "+zlcid +" and k.currentoperatortype in(0,1,2) ";

                            bb.writeLog("sql:"+sql);
                            rs.executeQuery(sql);
                            while(rs.next()){
                                String requestid = Util.null2String(rs.getString("requestid"));
                                list.add(requestid);
                            }
                            bb.writeLog("list:"+list.size());
                            int errcount = 0;
                            for(String lcid : list){
                                bb.writeLog("lcid:"+lcid);

                                PAResponseEntity forceoverEntity = doForceOver(user,Integer.parseInt(lcid),ip);
                                PAResponseCode pa_ResponseCode = forceoverEntity.getCode();
                                bb.writeLog("code:"+pa_ResponseCode.getStatusCode());
                                if(pa_ResponseCode.getStatusCode() != 1){
                                    errcount++;
                                }
                            }
                            if(errcount > 0){
                                requestInfo.getRequestManager().setMessageid("1111");
                                    requestInfo.getRequestManager().setMessagecontent("现场检查流程强制归档失败");
                                return FAILURE_AND_CONTINUE;
                            }

                        }else{
                            requestInfo.getRequestManager().setMessageid("1111");
                            requestInfo.getRequestManager().setMessagecontent("干预行政许可主流程失败");
                            return FAILURE_AND_CONTINUE;
                        }
                    }
                }
            }

        } catch (Exception e) {
            bb.writeLog(e);
            requestInfo.getRequestManager().setMessageid("1111");
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return FAILURE_AND_CONTINUE;
        }

        return SUCCESS;
    }


    public ReqOperateRequestEntity intervenor2Entity(int requestId,String ip,String userId,String nodeId) {
        ReqOperateRequestEntity operateRequestEntity = new ReqOperateRequestEntity();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        try {
            if(requestId > 0){

                // 干预是否执行节点前附加操作
                boolean enableIntervenor = true;
                // 会签类型 0 ：非会签 1：会签 2：依次逐个处理
                String SignType = "0";
                String remark  = "";
                //干预节点接收人，多个人以","号隔开
                String Intervenorid = userId;
                // 目标节点ID
                int submitNodeId = Util.getIntValue(nodeId) ;

                int workflowId = 0;
                String requestName = "";

//                int userId = 0;
//                int forwardFlag = 0;
//                String forwardResourceIds = "";
//                int isremind = 0;

                String sql = " select workflowid,requestname from workflow_requestbase where requestid = "+requestId ;
                rs.executeQuery(sql);
                if(rs.next()){
                    requestName = Util.null2String(rs.getString("requestname"));
                    workflowId = Util.getIntValue(rs.getString("workflowid"));
                }

                operateRequestEntity.setWorkflowId(workflowId);
                operateRequestEntity.setRequestId(requestId);
                operateRequestEntity.setRequestName(requestName);
//                operateRequestEntity.setUserId(userId);
                operateRequestEntity.setRemark(remark);
//                operateRequestEntity.setRequestLevel(requestLevel);
//                operateRequestEntity.setForwardFlag(forwardFlag);
//                operateRequestEntity.setForwardResourceIds(forwardResourceIds);
                operateRequestEntity.setClientIp(ip);
//                operateRequestEntity.setIsremind(isremind);
                //干预参数
                if (submitNodeId > 0 || FreeNodeBiz.isFreeNode(submitNodeId)) {
                    operateRequestEntity.setSubmitNodeId(submitNodeId);
                    operateRequestEntity.setEnableIntervenor(enableIntervenor);
                    operateRequestEntity.setSignType(Util.getIntValue(Util.null2String(SignType), 0));
                    operateRequestEntity.setIntervenorid(Util.null2String(Intervenorid));
                }
                bb.writeLog("workflowId:"+workflowId+"  requestId:"+requestId+"  requestName:"+requestName+"remark:"+remark+ "  submitNodeId:"+submitNodeId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            bb.writeLog(e);
        }
        return operateRequestEntity;
    }


    public PAResponseEntity doForceOver(User user, int requestId,String ip) {
        BaseBean bb = new BaseBean();
        WorkflowRequestOperatePA operatePA = getRequestOperatePA();
        bb.writeLog("~~~~doForceOver接口报文~~~~userId:"+user.getUID());
        PAResponseEntity paResponseEntity = operatePA.doForceOver(user, forceOver2Entity(requestId,ip));
        return paResponseEntity;
    }


    public ReqOperateRequestEntity forceOver2Entity(int requestId,String ip) {
        ReqOperateRequestEntity operateRequestEntity = new ReqOperateRequestEntity();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        try {
            if(requestId > 0){

                String remark  = "";
                int workflowId = 0;
                String requestName = "";
                String sql = " select workflowid,requestname from workflow_requestbase where requestid = "+requestId ;
                rs.executeQuery(sql);
                if(rs.next()){
                    requestName = Util.null2String(rs.getString("requestname"));
                    workflowId = Util.getIntValue(rs.getString("workflowid"));
                }

                Map<String, Object> otherParams = new HashMap<String,Object>();
                otherParams.put("ismonitor","1");
                operateRequestEntity.setOtherParams(otherParams);

                operateRequestEntity.setWorkflowId(workflowId);
                operateRequestEntity.setRequestId(requestId);
                operateRequestEntity.setRequestName(requestName);
//                operateRequestEntity.setUserId(userId);
                operateRequestEntity.setRemark(remark);
//                operateRequestEntity.setRequestLevel(requestLevel);
//                operateRequestEntity.setForwardFlag(forwardFlag);
//                operateRequestEntity.setForwardResourceIds(forwardResourceIds);
                operateRequestEntity.setClientIp(ip);
//                operateRequestEntity.setIsremind(isremind);

                bb.writeLog("workflowId:"+workflowId+"  requestId:"+requestId+"  requestName:"+requestName+"remark:"+remark);

            }

        } catch (Exception e) {
            e.printStackTrace();
            bb.writeLog(e);
        }
        return operateRequestEntity;
    }



}
