package com.engine.htsc.zbzysx.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.htsc.zbzysx.util.ZbzysxUtil;
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 weaver.interfaces.htsc.comInfo.PropBean;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;

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.*;

public class ZbzysxControlAction {

    /**
     * 查询人员待办
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/getfreefode")
    @Produces({MediaType.TEXT_PLAIN})
    public String getFreeNode(@Context HttpServletRequest request, @Context HttpServletResponse response){
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();

        int requestid = Util.getIntValue(Util.null2String(request.getParameter("requestid")));//申报类型
        int workflowid = Util.getIntValue( request.getParameter( "workflowid" ) );
        int nodeid = Util.getIntValue( request.getParameter( "nodeid" ) );
        int xybzvalue = Util.getIntValue( request.getParameter( "xybzvalue" ) );
        JSONObject json = new JSONObject();
        DepartmentComInfo departInfo = null;
        try{
            String jdfl = "";
            if (xybzvalue == 0) {
                jdfl = "6";
            } else if (xybzvalue == 1) {
                jdfl = "11";
            }
            departInfo = new DepartmentComInfo();
            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 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<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 );
                Map<String,Object> resultMap = freeFlowService.generateFreeNode(params);
                if("true".equals(resultMap.get("result"))){
                    List<String> freeList = new ArrayList<String>();
                    rs.executeQuery( "select id from workflow_freenode where requestid ='" + requestid + "'" );
                    while (rs.next()) {
                        String id = Util.null2String(rs.getString("id"));
                        freeList.add(id);
                    }

                    List<String> uflist = new ArrayList<String>();
                    rs.executeQuery( " select freenode from uf_qzyjhqb where lcid ='" + requestid + "'" );
                    while(rs.next()){
                        String freenode = Util.null2String(rs.getString("freenode"));
                        uflist.addAll(Arrays.asList(freenode));
                    }

                    String bmfzrNode= "";
                    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 ;//自由节点
                        }
                    }

                    String zdryNode= "";
                    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 ;//自由节点
                        }
                    }

                    int formmodeid = 0;
                    ModeRightInfo moderight = new ModeRightInfo();
                    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 newFreeNode = "";
                    if(freeList.size() > 0 && freeList !=null){
                        for(String str : freeList){
                            if(!uflist.contains(str)){
                                newFreeNode += newFreeNode==""? str : ","+str ;
                            }
                        }
                    }

                    bb.writeLog( "=================newFreeNode:" + newFreeNode );
                    rs.executeUpdate( "insert into uf_qzyjhqb(lcid,jdfl,freenode,formmodeid,bmfzr,zdry) values('" + requestid + "','" + jdfl + "','" + newFreeNode + "','" + formmodeid + "','"+bmfzrNode+"','"+zdryNode+"')" );

                    /**
                     * 权限重构
                     */
                    rs.executeQuery( "select id from uf_qzyjhqb where requestid='" + requestid + "'" );
                    while (rs.next())
                    {
                        int id = Util.getIntValue( rs.getString( "id" ) );
                        moderight.editModeDataShare( userid, formmodeid, id );
                    }
                }

                json.put("flag",true);
            }else {
                json.put("flag",false);
            }
            bb.writeLog( "getFreeNode_Ajax=================json:" + json.toJSONString() );
        }catch (Exception e){
            bb.writeLog("e:"+e);
        }
        return json.toJSONString();
    }

    @GET
    @Path("/getldspbynode")
    @Produces({MediaType.TEXT_PLAIN})
    public String getLdspByNode(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        int requestid = Util.getIntValue(Util.null2String(request.getParameter("requestid")));    //
        int workflowid = Util.getIntValue(Util.null2String(request.getParameter("workflowid")));  //
        String nodeid = Util.null2String( request.getParameter( "nodeid" ) );

        List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
        Map<String,Object> dataMap = new HashMap<String,Object>();
        String fieldvalue = "";
        RecordSet rs = new RecordSet();

        String sql =" select t.userid,h.lastname,k.departmentname \n" +
                " from workflow_currentoperator t\n" +
                " inner join hrmresource h on h.id = t.userid\n" +
                " inner join hrmdepartment k on k.id = h.departmentid\n" +
                " where requestid=" +requestid +
                " and workflowid=" + workflowid+
                " and nodeid in("+nodeid+") ";
        rs.execute(sql);

        while (rs.next()){
            String userid = Util.null2String(rs.getString("userid"));
            String lastname = Util.null2String(rs.getString("lastname"));
            String departmentname = Util.null2String(rs.getString("departmentname"));
            fieldvalue += fieldvalue == ""? userid : ","+userid ;
            Map<String,String> itemMap = new HashMap<String,String>();
            itemMap.put("id",userid);
            itemMap.put("name",lastname+"("+departmentname+")");
            dataList.add(itemMap);
        }
        dataMap.put("value",fieldvalue);
        dataMap.put("specialobj",dataList);
        return net.sf.json.JSONObject.fromObject(dataMap).toString();
    }


    @GET
    @Path("/getSyfwModel")
    @Produces({MediaType.TEXT_PLAIN})
    public String getSyfwModel(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();

        String sblb = Util.null2String( request.getParameter( "sblb" ) );//申报类别
        String sblx = Util.null2String( request.getParameter( "sblx" ) );//申报类型
        String deptid = Util.null2String( request.getParameter( "szbm" ) );//部门ID

        JSONObject jsonData = new JSONObject();

        DepartmentComInfo DepartmentComInfo = null;
        ResourceComInfo ResourceComInfo = null ;
        try{
            ResourceComInfo = new ResourceComInfo();
            DepartmentComInfo = new DepartmentComInfo();
            String fgldsf = "";
            String deptleaders = "";
            String bjhqbms = "" ;  //必经会签部门
            String kxhqbms = "" ;  // 可选会签部门
            String qzsydx = "" ;  //强制会签部门
            String qzsyryid = ""; //强制送阅人员
            String sql = " select syfw,bjhqbm,fgldsf,qzsydx,qzsyry,zdfgld,kxhqbm from uf_zysxsyfw where sblb ='" + sblb + "' and sblx='" + sblx + "'";
            rs.executeQuery( sql );
            bb.writeLog( sql );
            if (rs.next()) {
                fgldsf = Util.null2String(rs.getString("fgldsf"));//分管领导审批
                bjhqbms = Util.null2String( rs.getString( "bjhqbm" ));//必经会签部门
                kxhqbms = Util.null2String( rs.getString( "kxhqbm" ) );//可选会签部门
                qzsydx = Util.null2String( rs.getString( "qzsydx" ) );//强制送阅部门
                qzsyryid = Util.null2String( rs.getString( "qzsyry" ) );//强制送阅人员
            }

            ZbzysxUtil ZbzysxUtil = new ZbzysxUtil();
            JSONArray jsonArray = new JSONArray();
            bb.writeLog("fgldsf:"+fgldsf);
            if (fgldsf.equals( "0" ))
            {
                deptleaders = ZbzysxUtil.getDeptleaders(deptid);
                if(!"".equals(deptleaders))
                {
                    List<String> leadersArry = Arrays.asList(deptleaders.split(","));
                    for(String leaders : leadersArry)
                    {
                        String deptleadersname = ResourceComInfo.getLastname(leaders);//部门分管领导名称
                        JSONObject json = new JSONObject();
                        json.put( "id", leaders );
                        json.put( "name", deptleadersname );
                        jsonArray.add( json );
                    }
                }
            }

            jsonData.put("ldspid", deptleaders );
            jsonData.put("ldsp", jsonArray);

            // 会签部门
            String bjhqbmids = "" ;
            JSONArray bjhqbmArray = new JSONArray();
            if(!"".equals(bjhqbms)){
                List<String> arr = Arrays.asList(bjhqbms.split(","));
                for (String bjhqbm : arr) {
                    if(!bjhqbm.equals(deptid))
                    {
                        JSONObject json1 = new JSONObject();
                        String bjhqbmname = DepartmentComInfo.getDepartmentName( bjhqbm );//必经会签部门名称
                        json1.put( "id", bjhqbm );
                        json1.put( "name", bjhqbmname );
                        bjhqbmArray.add( json1 );

                        bjhqbmids += bjhqbmids == "" ? bjhqbm : ","+bjhqbm ;
                    }
                }
            }

            jsonData.put( "bjhqbmid", bjhqbmids );
            if(!"".equals(kxhqbms)){
                List<String> arr1 = Arrays.asList(kxhqbms.split(","));
                for (String kxhqbm : arr1) {
                    if(!kxhqbm.equals(deptid)){
                        String kxhqbmname = DepartmentComInfo.getDepartmentName( kxhqbm );//可选会签部门名称
                        JSONObject json11 = new JSONObject();
                        json11.put( "id", kxhqbm );
                        json11.put( "name", kxhqbmname );
                        bjhqbmArray.add( json11 );
                    }
                }
            }
            jsonData.put( "kxhqbmid", kxhqbms );
            jsonData.put( "hqbm", bjhqbmArray );

            /***
             *   通知阅读对象汇总
             */
            String qzsydxids = "";
            List<String> qzsydxList = new ArrayList<String>();
            if(!"".equals(qzsydx))
            {
                String sql1 = " select id,lastname,departmentid from hrmresource where departmentid in (" + qzsydx + ") and status = 1 ";
                rs.executeQuery( sql1 );
                while (rs.next()) {
                    String id = Util.null2String( rs.getString( "id" ) );
                    qzsydxids += qzsydxids == "" ? id : "," + id;
                    String departmentid =  Util.null2String(rs.getString("departmentid"));
                    if(qzsydxList !=null && qzsydxList.size() > 0){
                        if(!qzsydxList.contains(departmentid)){
                            qzsydxList.add(departmentid);
                        }
                    }else{
                        qzsydxList.add(departmentid);
                    }
                }
            }
            JSONArray replaceObject  = ZbzysxUtil.getReplaceDatas(sblb,sblx);
            jsonData.put( "qzsyryid", qzsyryid ); //部门里人员ID
            jsonData.put( "qzsydxid", qzsydxids ); // 人员汇总ID
            jsonData.put( "tzyddx", replaceObject );  //人员名称，部门展示


            JSONObject replaceObj = new JSONObject();
            if(!"".equals(qzsyryid))
            {
                if(!"".equals(qzsydxids))
                {
                    qzsydxids = qzsydxids+","+qzsyryid;
                }else{
                    qzsydxids = qzsyryid;
                }
            }
            replaceObj.put("value",qzsydxids);
            replaceObj.put("status","1");
            replaceObj.put("specialobj",replaceObject);
            jsonData.put("tzyddxobj",replaceObj);

            String qzsyry = "";
            if(!"".equals(qzsyryid))
            {
                List<String> tzryArray = Arrays.asList(qzsyryid.split(","));
                if(tzryArray!=null && tzryArray.size() > 0){
                    for (String tzryid : tzryArray) {
                        qzsyry += qzsyry == "" ? "hrm_"+tzryid : "," + "hrm_"+tzryid;
                    }
                }
            }

            String qzsydxbm = "";
            if(qzsydxList !=null && qzsydxList.size() >0){
                for (String str : qzsydxList)
                {
                    qzsydxbm += qzsydxbm == "" ? "dept_"+str : "," + "dept_"+str;
                }
            }

            jsonData.put( "qzsyrys", qzsyry ); //人员
            jsonData.put( "qzsydxs", qzsydxbm );  //部门
        }catch (Exception e){

        }
        return jsonData.toString();
    }



    @GET
    @Path("/getTzyddx")
    @Produces({MediaType.TEXT_PLAIN})
    public String getTzyddx(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();

        String sblb = Util.null2String( request.getParameter( "sblb" ) );//申报类别
        String sblx = Util.null2String( request.getParameter( "sblx" ) );//申报类型

        JSONObject jsonData = new JSONObject();

        try{
            String qzsydx = "" ;  //强制会签部门
            String qzsyryid = ""; //强制送阅人员
            String sql = " select syfw,bjhqbm,fgldsf,qzsydx,qzsyry,zdfgld,kxhqbm from uf_zysxsyfw where sblb ='" + sblb + "' and sblx='" + sblx + "'";
            rs.executeQuery( sql );
            bb.writeLog( sql );
            if (rs.next()) {
                qzsydx = Util.null2String( rs.getString( "qzsydx" ) );//强制送阅部门
                qzsyryid = Util.null2String( rs.getString( "qzsyry" ) );//强制送阅人员
            }

            ZbzysxUtil ZbzysxUtil = new ZbzysxUtil();
            /***
             *   通知阅读对象汇总
             */
            if(!"".equals(qzsydx))
            {
                String sql1 = " select id,lastname,departmentid from hrmresource where departmentid in (" + qzsydx + ") and status = 1 ";
                rs.executeQuery( sql1 );
                while (rs.next()) {
                    String id = Util.null2String( rs.getString( "id" ) );
                    qzsyryid += qzsyryid == "" ? id : "," + id;
                }
            }
            JSONArray replaceObject  = ZbzysxUtil.getReplaceDatas(sblb,sblx);
            JSONObject replaceObj = new JSONObject();
            replaceObj.put("value",qzsyryid);
            replaceObj.put("status","1");
            replaceObj.put("specialobj",replaceObject);
            jsonData.put("tzyddxobj",replaceObj);
        }catch (Exception e){

        }
        return jsonData.toString();
    }




}
