package com.engine.htsc.itxqlc.cmd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ServiceUtil;
import com.engine.core.interceptor.CommandContext;
import com.engine.workflow.service.RequestFreeFlowService;
import com.engine.workflow.service.impl.RequestFreeFlowServiceImpl;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.util.HashMap;
import java.util.Map;

public class ItxqlcFreeNodeCmd extends AbstractCommonCommand<Map<String, Object>> {

    public ItxqlcFreeNodeCmd(User user, Map<String, Object> params) {
        this.params = params;
        this.user = user;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        DepartmentComInfo departmentComInfo = null;

        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        bb.writeLog( "in=================ItxqlcFreeNodeCmd" );
        Map<String, Object> apimap = new HashMap<String, Object>();
        try{
            PropBean pb = new PropBean();
            int requestid = Util.getIntValue(Util.null2String(params.get("requestid")));
            int workflowid = Util.getIntValue(Util.null2String(params.get("workflowid")));
            int nodeid = Util.getIntValue(Util.null2String(params.get("nodeid")));
            int xybzvalue = Util.getIntValue(Util.null2String(params.get("xybzvalue")));

            String jdfl = pb.getPropName("itxqlc_xgry_qzyjlx");

            String jsonArr = Util.null2String(Util.null2String(params.get("jsonArr")));
            bb.writeLog("jsonArr:"+jsonArr);
            JSONArray jsonArray = JSONArray.parseArray( jsonArr );
            JSONObject freeNode = new JSONObject();
            JSONArray nodeData = new JSONArray();
            String xgrys = "";
            for (int i = 0; i < jsonArray.size(); i++) {
                String xgry = Util.null2String( jsonArray.getJSONObject( i ).get( "xgry" ) );
                bb.writeLog("xgry:"+xgry);
                String sfspg = Util.null2String( jsonArray.getJSONObject( i ).get( "sfspg" ) );
                if ("1".equals( sfspg )) {
                    JSONArray nodeArray = new JSONArray();


                    JSONObject nodeDataJson = new JSONObject();
                    nodeDataJson.put( "nodename", "相关人员审核" );
                    nodeDataJson.put( "signType", "1" );  //20201226
                    nodeDataJson.put( "operators", xgry );
                    nodeArray.add( nodeDataJson );
                    nodeData.add( nodeArray );
                    freeNode.put( "nodeData", nodeData );
                    freeNode.put( "mergeType", 1 );   //合并方式，（1:按比例方式通过，2:按分支数通过）
                    freeNode.put( "mergeValue", 100 );
                    xgrys += xgrys == "" ? "'" + xgry + "'" + "" : "," + "'" + xgry + "'";
                }
            }

            int userid = user.getUID();
            // 自由节点参数
            Map<String, Object> params = new HashMap<String, Object>();
            params.put( "requestid", requestid );
            params.put( "nodeid", nodeid );
            params.put( "workflowid", workflowid );
            params.put( "nodetype", 2 );
            params.put( "nextNodeEditPurview", 2 );
            params.put( "allowModify", 1 );
            params.put( "isFlowToNext", 0 );
            params.put( "isAddToParentGroup", 1 );
            params.put( "isParallel", 0 );
            params.put( "freeNodeData", freeNode );
            if (freeNode.size() > 0) {
                bb.writeLog( "=================params:" + params.toString() );

                //生产自由节点
                RequestFreeFlowService freeFlowService = ServiceUtil.getService( RequestFreeFlowServiceImpl.class, user );
                freeFlowService.generateFreeNode( params );
                int formmodeid = 0 ;
                rs.executeQuery( "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = 'uf_qzyjhqb'" );
                if(rs.next()){
                    formmodeid = Util.getIntValue( rs.getString( "id" ) );
                }


                String freenode = "";
                rs.executeQuery( "select id from workflow_freenode where requestid ='" + requestid + "'" );
                while (rs.next()) {
                    String id = Util.null2String(rs.getString("id"));
                    freenode += freenode==""? id : ","+id ;//自由节点
                }

                String uf_freenode = "";
                rs.executeQuery( " select freenode as id from uf_qzyjhqb where lcid ='" + requestid + "'" );
                while(rs.next()) {
                    String id = Util.null2String(rs.getString("id"));
                    uf_freenode += uf_freenode==""? id : ","+id ;//自由节点
                }

                String xyryNode= "";
                if(!"".equals(xgrys)){
                    rs.executeQuery( " select id from workflow_freenode where requestid ='" + requestid + "' and to_char(operatorids) in ("+xgrys+")" );
                    while(rs.next()) {
                        String id = Util.null2String(rs.getString("id"));
                        xyryNode += xyryNode ==""? id : ","+id ;//自由节点
                    }
                }

                bb.writeLog( "=================freenode:" + freenode + ",freenode1:" + uf_freenode );
                String str = equestStr( freenode, uf_freenode );
                boolean flag =  rs.executeUpdate( "insert into uf_qzyjhqb(lcid,jdfl,freenode,formmodeid,bmfzr,zdry) values('" + requestid + "','" + jdfl + "','" + str + "','" + formmodeid + "','"+xyryNode+"','')" );
                if(flag){
                    rs.executeQuery( "select id from uf_qzyjhqb where requestid='" + requestid + "'" );
                    while (rs.next())
                    {
                        int id = Util.getIntValue(rs.getString( "id" ) );
                        ModeRightInfo moderight = new ModeRightInfo();
                        moderight.editModeDataShare( userid, formmodeid, id );
                    }
                    apimap.put("flag",true);
                }
            }else {
                apimap.put("flag",false);
            }

        }catch (Exception e){

        }
        return apimap;
    }

    /***
     *
     * @param str1
     * @param str2
     * @return
     */
    public static String equestStr(String str1, String str2)
    {
        StringBuilder sb = new StringBuilder();
        String[] strings = str1.split( "," );
        for (String s : strings) {
            if (!str2.contains( s )) {
                sb.append( s + "," );
            }
        }
        String str = sb.substring( 0, sb.length() - 1 ).toString();
        return str;
    }

}
