package com.engine.htxc.tycgsq.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
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.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: K1810027
 * @version: 1.0
 * @CreateDate: 2022-08-24 11:26
 * @Description:
 * @ModifyLog:
 **/
public class GetFreeNodeAjax {
    @GET
    @Path("/getFreeNodeAjax")
    @Produces({MediaType.TEXT_PLAIN})
    public String getFreeNodeAjax(@Context HttpServletRequest request, @Context HttpServletResponse response){
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        RecordSet rs2 = new RecordSet();
        RecordSet rs3 = new RecordSet();
        HashMap<String, Object> map = new HashMap<>();
        try {
            ResourceComInfo resourceInfo = new ResourceComInfo();
            DepartmentComInfo departInfo = new DepartmentComInfo();
            bb.writeLog( "in=================getFreeNode_Ajax" );
            int requestid = Util.getIntValue( request.getParameter( "requestid" ) );
            int workflowid = Util.getIntValue( request.getParameter( "workflowid" ) );
            int nodeid = Util.getIntValue( request.getParameter( "nodeid" ) );
            JSONObject json = new JSONObject();
            bb.writeLog( "in=================nodeid:" + nodeid );
            int xybzvalue = Util.getIntValue( request.getParameter( "xybzvalue" ) );
            String jdfl = "";
            if (xybzvalue == 0) {
                jdfl = "6";
            } else if (xybzvalue == 1) {
                jdfl = "11";
            }
            String jsonArr = Util.null2String( request.getParameter( "jsonArr" ) );
            bb.writeLog("jsonArr:"+jsonArr);
            JSONArray jsonArray = JSONArray.parseArray( jsonArr );
            JSONObject freeNode = new JSONObject();
            JSONArray nodeData = new JSONArray();
            String bmfzrs = "";
            String zdrys = "";
            for (int i = 0; i < jsonArray.size(); i++) {
                String hqbmvalue = Util.null2String( jsonArray.getJSONObject( i ).get( "hqbmvalue" ) );
                String hqbm = departInfo.getDepartmentName( hqbmvalue );
                String zdry = Util.null2String( jsonArray.getJSONObject( i ).get( "zdry" ) );
                String bmfzr = Util.null2String( jsonArray.getJSONObject( i ).get( "bmfzr" ) );
                bb.writeLog("zdry:"+zdry);
                bb.writeLog("bmfzr:"+bmfzr);
                String sfhq = Util.null2String( jsonArray.getJSONObject( i ).get( "sfhq" ) );
                if ("1".equals( sfhq )) {
                    JSONArray nodeArray = new JSONArray();
                    if (!"".equals( zdry ) && !"".equals( bmfzr )) {
                        JSONObject nodeDataJson1 = new JSONObject();
                        if(xybzvalue==0){
                            nodeDataJson1.put( "nodename", "指定人员" );
                            nodeDataJson1.put( "operators", zdry );
                            nodeDataJson1.put( "signType", 1 );  //会签方式,(0:非会签、1:会签、2:依次逐个签)	//20201226
                        }
                        if(xybzvalue==1){
                            nodeDataJson1.put( "nodename", "跨公司会签" );
                            nodeDataJson1.put( "operators", zdry );
                            nodeDataJson1.put( "signType", Util.getIntValue( sfhq ) );  //会签方式,(0:非会签、1:会签、2:依次逐个签)
                        }
                        nodeArray.add( nodeDataJson1 );
                        JSONObject nodeDataJson2 = new JSONObject();
                        if(xybzvalue==0){
                            nodeDataJson2.put( "nodename", "会签部门负责人" );
                            String deptcode = departInfo.getDepartmentCode(hqbmvalue);
                            bb.writeLog("deptcode:"+deptcode);
                            // ZZ001014
                            if("ZZ001014".equals(deptcode)){
                                nodeDataJson2.put( "signType", "0" );  //20201226
                            }else{
                                nodeDataJson2.put( "signType", "1" );  //20201226
                            }
                        }
                        if(xybzvalue==1){
                            nodeDataJson2.put( "nodename", "跨公司会签" );
                            nodeDataJson2.put( "signType", Util.getIntValue( sfhq ) );
                        }
                        nodeDataJson2.put( "operators", bmfzr );
                        nodeArray.add( nodeDataJson2 );

                    } else if (!"".equals( zdry ) && "".equals( bmfzr )) {
                        JSONObject nodeDataJson1 = new JSONObject();
                        if(xybzvalue==0){
                            nodeDataJson1.put( "nodename", "指定人员" );
                            nodeDataJson1.put( "operators", zdry );
                            nodeDataJson1.put( "signType", 1 );
                        }
                        if(xybzvalue==1){
                            nodeDataJson1.put( "nodename", "跨公司会签" );
                            nodeDataJson1.put( "operators", zdry );
                            nodeDataJson1.put( "signType", Util.getIntValue( sfhq ) );
                        }

                        nodeArray.add( nodeDataJson1 );
                    } else if ("".equals( zdry ) && !"".equals( bmfzr )) {
                        JSONObject nodeDataJson2 = new JSONObject();
                        if(xybzvalue==0){
                            nodeDataJson2.put( "nodename", "会签部门负责人" );
                            //nodeDataJson2.put( "signType", "1" );

                            String deptcode = departInfo.getDepartmentCode(hqbmvalue);
                            bb.writeLog("deptcode:"+deptcode);
                            // ZZ001014
                            if("ZZ001014".equals(deptcode)){
                                nodeDataJson2.put( "signType", "0" );  //20201226
                            }else{
                                nodeDataJson2.put( "signType", "1" );  //20201226
                            }
                        }

                        if(xybzvalue==1){
                            nodeDataJson2.put( "nodename", "跨公司会签" );
                            nodeDataJson2.put( "signType", Util.getIntValue( sfhq ) );
                        }
                        nodeDataJson2.put( "operators", bmfzr );

                        nodeArray.add( nodeDataJson2 );
                    }
                    nodeData.add( nodeArray );
                    freeNode.put( "nodeData", nodeData );
                    freeNode.put( "mergeType", 1 );   //合并方式，（1:按比例方式通过，2:按分支数通过）
                    freeNode.put( "mergeValue", 100 );
                    bmfzrs += bmfzrs == "" ? "'" + bmfzr + "'" + "" : "," + "'" + bmfzr + "'";
                    zdrys += zdrys == "" ? "'" + zdry + "'" + "" : "," + "'" + zdry + "'";
                }
            }
            User user = HrmUserVarify.getUser( request, response );
            int userid = user.getUID();
            // 自由节点参数
            Map<String, Object> params = new HashMap<>();
            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 );
                rs.executeQuery( "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = 'uf_qzyjhqb'" );
                rs.next();
                int formmodeid = Util.getIntValue( rs.getString( "id" ) );
                String freenode = "";
                String freenode1 = "";
                rs2.executeQuery( "select id from workflow_freenode where requestid ='" + requestid + "'" );
                while (rs2.next()) {
                    String id = Util.null2String(rs2.getString("id"));
                    freenode += freenode==""? id : ","+id ;//自由节点
                }
                rs3.executeQuery( " select freenode as id from uf_qzyjhqb where lcid ='" + requestid + "'" );
                while(rs3.next()) {
                    //freenode1 = Util.null2String( rs3.getString( "freenode1" ) );//自由节点
                    String id = Util.null2String(rs3.getString("id"));
                    freenode1 += freenode1==""? id : ","+id ;//自由节点

                }
                String bmfzrNode= "";
                String zdryNode= "";
                if(!"".equals(bmfzrs)){
                    rs.executeQuery( " select id from workflow_freenode where requestid ='" + requestid + "' and to_char(operatorids) in ("+bmfzrs+")" );
                    while(rs.next()) {

                        String id = Util.null2String(rs.getString("id"));
                        bmfzrNode += bmfzrNode ==""? id : ","+id ;//自由节点
                        //bmfzrNode = Util.null2String( rs.getString( "bmfzrNode" ) );//部门负责人节点
                    }
                }
                if(!"".equals(zdrys)){
                    rs.executeQuery( " select id from workflow_freenode where requestid ='" + requestid + "' and to_char(operatorids) in ("+zdrys+")" );
                    while (rs.next()) {
                        String id = Util.null2String(rs.getString("id"));
                        zdryNode += zdryNode ==""? id : ","+id ;//自由节点
                        //zdryNode = Util.null2String( rs.getString( "zdryNode" ) );//指定人员节点
                    }
                }
                bb.writeLog( "=================freenode:" + freenode + ",freenode1:" + freenode1 );
                String str = equestStr( freenode, freenode1 );
                rs2.executeUpdate( "insert into uf_qzyjhqb(lcid,jdfl,freenode,formmodeid,bmfzr,zdry) values('" + requestid + "','" + jdfl + "','" + str + "','" + formmodeid + "','"+bmfzrNode+"','"+zdryNode+"')" );
                rs1.executeQuery( "select id from uf_qzyjhqb where requestid='" + requestid + "'" );
                while (rs1.next()) {
                    int id = Util.getIntValue( rs1.getString( "id" ) );
                    ModeRightInfo moderight = new ModeRightInfo();
                    moderight.editModeDataShare( userid, formmodeid, id );
                }

                map.put("flag",true);
                map.put("code",200);
                map.put("msg","SUCCESS");
            }else {
                map.put("flag",false);
                map.put("code",200);
                map.put("msg","SUCCESS");
            }
            bb.writeLog( "getFreeNode_Ajax=================json:" + JSONObject.toJSONString(map) );
            return JSONObject.toJSONString(map);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg",e.getMessage());
            map.put("code",500);
            return JSONObject.toJSONString(map);
        }

    }
    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;
    }
}
