package com.engine.htsc.itxqlc.web;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.htsc.itxqlc.service.ItxqlcService;
import com.engine.htsc.itxqlc.service.impl.ItxqlcServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.itcglc.util.WorkflowUtil;
import weaver.interfaces.htsc.util.HT_WorkflowInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.*;
import java.util.stream.Collectors;

public class ItxqlcAction {

    public ItxqlcService getService(HttpServletRequest request, HttpServletResponse response){
        return  (ItxqlcService) ServiceUtil.getService(ItxqlcServiceImpl.class);
    }

    @POST
    @Path("/getItxqXgxtList")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String getItxqXgxtList(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            Map<String,Object> param = ParamUtil.request2Map(request);
            String userid = Util.null2String(param.get("usercode"));
            System.out.println("userid:"+userid);
            apidatas = getService(request,response).getItxqXgxtList(param);

            apidatas.put("api_status", true);
            apidatas.put("api_errormsg", "");
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/getSzbmInfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String getSzbmInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            RecordSet rs = new RecordSet();
            PropBean pb = new PropBean();
            String ngr = Util.null2String(request.getParameter("ngr"));
            String szbm = Util.null2String(request.getParameter("szbm"));

            String depttypecode = "" ;
            String deptclasscode = "" ;
            String departmentid = "" ;
            String sql =" select h.departmentid,d.depttypecode,d.deptscalelevelcode \n" +
                        " from hrmresource h\n" +
                        " inner join hrmdepartmentdefined d on d.deptid = h.departmentid\n" +
                        " where h.id="+ngr ;
            rs.execute(sql);
            if (rs.next()){
                depttypecode = Util.null2String(rs.getString("depttypecode"));
                deptclasscode = Util.null2String(rs.getString("deptscalelevelcode"));
                departmentid = Util.null2String(rs.getString("departmentid"));
            }
            String ngrsffzzd = "0" ;
            if(("JGLX04".equals(depttypecode)) && ("006".equals(deptclasscode))){
                ngrsffzzd = "1";
            }else if(("JGLX09".equals(depttypecode)) && ("009".equals(deptclasscode))){
                ngrsffzzd = "2";
            }else if(("JGLX04".equals(depttypecode)) && ("010".equals(deptclasscode))){
                ngrsffzzd = "2";
            }else if(("JGLX01".equals(depttypecode)) && ("001".equals(deptclasscode))){
                ngrsffzzd = "3";
            }else{
                ngrsffzzd = "0";
            }

            int iszb = 0;
            int isdept3 = 0;
            if(!"".equals(departmentid)){
                sql =   " select id from hrmdepartment d \n" +
                        " where d.id=" + szbm+
                        " connect by prior d.id = d.supdepid\n" +
                        " start with d.departmentcode ='ZZ001' ";
                rs.execute(sql);
                if (rs.next()){
                    iszb++;
                }

                String dept3id = pb.getPropName("ITXQ_dept");
                if(!"".equals(dept3id)){
                    dept3id = "'"+dept3id.replace(",","','")+"'";
                    sql =   " select id from hrmdepartment d \n" +
                            " where d.id=" + szbm+
                            " connect by prior d.id = d.supdepid\n" +
                            " start with d.departmentcode in("+dept3id+") ";
                    rs.execute(sql);
                    if (rs.next()){
                        isdept3++;
                    }
                }
            }

            String bshq = pb.getPropName("ITXQ_BSHQ");
            String ywlx_bm = pb.getPropName("ITXQ_YWLX_BM");
            List<String> ywlxList = new ArrayList<String>();
            if(!"".equals(ywlx_bm)){
                ywlx_bm = "'"+ywlx_bm.replace(",","','")+"'";
                sql =   " select id from hrmdepartment d where d.departmentcode in("+ywlx_bm+") ";
                rs.execute(sql);
                while (rs.next()){
                    String id = Util.null2String(rs.getString("id"));
                    ywlxList.add(id);
                }
            }
            int ishq = 0;
            if(ywlxList.contains(szbm)){
                ishq++;
            }

            String hqbmvalue = "" ;
            List<Map<String,Object>> hqmbList = new ArrayList<Map<String,Object>>();
            Map<String,Object> hqbmmap = null;

            if(ishq > 0)
            {
                if(!"".equals(bshq))
                {
                    bshq = "'"+bshq.replace(",","','")+"'";
                    sql =   " select id,departmentname from hrmdepartment d where d.departmentcode in("+bshq+") ";
                    rs.execute(sql);
                    while (rs.next()){
                        String id = Util.null2String(rs.getString("id"));
                        String departmentname = Util.null2String(rs.getString("departmentname"));
                        hqbmmap = new HashMap<String,Object>();
                        hqbmmap.put("id",id);
                        hqbmmap.put("name",departmentname);
                        hqmbList.add(hqbmmap);
                        hqbmvalue += hqbmvalue== "" ? id : ","+id ;
                    }
                }
            }


            apidatas.put("specialobj", hqmbList);
            apidatas.put("hqbmvalue", hqbmvalue);

            apidatas.put("isdept3", String.valueOf(isdept3)+"");
            apidatas.put("iszb", String.valueOf(iszb)+"");
            apidatas.put("ngrsffzzd", ngrsffzzd+"");
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }



    @GET
    @Path("/gethqbmData")
    @Produces({MediaType.TEXT_PLAIN})
    public String gethqbmData(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            BaseBean bb = new BaseBean();
            RecordSet rs = new RecordSet();
            PropBean pb = new PropBean();

            Map<String,Object> param = ParamUtil.request2Map(request);
            bb.writeLog("requestParams ----> "+param);

            String bshq = pb.getPropName("ITXQ_BSHQ");
            String bshq2 = pb.getPropName("ITXQ_BSHQ2");
            String ywlx_bm = pb.getPropName("ITXQ_YWLX_BM");
            String itxq_hqbm_sxfw = pb.getPropName("ITXQ_HQBM_SXFW");
            String szbm = Util.null2String(param.get("szbm"));

            int hqbmsxflag = 0;
            if(!"".equals(szbm) && !"".equals(itxq_hqbm_sxfw)){
                String sql = "select id, departmentname\n" +
                        "  from hrmdepartment\n" +
                        " where id = "+szbm+"\n" +
                        "connect by prior id = supdepid\n" +
                        " start with departmentcode = '"+itxq_hqbm_sxfw+"'" ;
                bb.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    hqbmsxflag++;
                }
            }
            bb.writeLog("bshq:"+bshq);
            bb.writeLog("ywlx_bm:"+ywlx_bm);
            List<String> ywlxList = new ArrayList<String>();

            if(!"".equals(ywlx_bm)){
                ywlx_bm = "'"+ywlx_bm.replace(",","','")+"'";
                String sql =   " select id from hrmdepartment d where d.departmentcode in("+ywlx_bm+") ";
                bb.writeLog(sql);
                rs.execute(sql);
                while (rs.next()){
                    String id = Util.null2String(rs.getString("id"));
                    ywlxList.add(id);
                }
            }

            List<String> xtmcList = new ArrayList<String>();
            String xtmc_bm = pb.getPropName("ITXQ_XTMC_BM");
            bb.writeLog("xtmc_bm:"+xtmc_bm);
            if(!"".equals(xtmc_bm)){
                xtmc_bm = "'"+xtmc_bm.replace(",","','")+"'";
                String sql =   " select id from hrmdepartment d where d.departmentcode in("+xtmc_bm+") ";
                bb.writeLog(sql);
                rs.execute(sql);
                while (rs.next()){
                    String id = Util.null2String(rs.getString("id"));
                    xtmcList.add(id);
                }
            }

            String xgxt_code = pb.getPropName("ITXQ_XGXT_CODE");
            //需求相关系统：电子印章管理平台
            String xgxt_code2 = pb.getPropName("xqxgxt2");

            String hqbmvalue = "" ;
            List<Map<String,Object>> hqmbList = new ArrayList<Map<String,Object>>();
            Map<String,Object> hqbmmap = null;

            int ishq = 0;
            int ishq2 = 0;


            String hgfxdj = Util.null2String(param.get("hgfxdj"));
            String sfxyw = Util.null2String(param.get("sfxyw"));
            String sfcyxxxt = Util.null2String(param.get("sfcyxxxt"));
            String sfsjywxghgfkgn = Util.null2String(param.get("sfsjywxghgfkgn"));
            String ywlb = Util.null2String(param.get("ywlb"));
            String xqxgxt = Util.null2String(param.get("xqxgxt"));
//            bb.writeLog("ywlb:"+ywlb);
//            bb.writeLog("xqxgxt:"+xqxgxt);
            if("2".equals(hgfxdj)){
                ishq++;
            }
            if("1".equals(sfxyw)){
                ishq++;
            }
            if(("1".equals(sfcyxxxt)) && ("1".equals(sfsjywxghgfkgn) || "2".equals(sfsjywxghgfkgn))){
                ishq++;
            }
//            bb.writeLog("ywlxList.contains(szbm):"+ywlxList.contains(szbm));
//            if((ywlxList.contains(szbm)) && ("1".equals(ywlb) || "4".equals(ywlb))){
//                ishq++;
//            }
            if(ywlxList.contains(szbm)){
                ishq++;
            }

//            if((xtmcList.contains(szbm)) &&((","+xgxt_code+",").indexOf(","+xqxgxt+",")>-1 )){
//                ishq++;
//            }

            List<String> xgxt_codeList = convertStringToList(xgxt_code);
            List<String> xgxt_codeList2 = convertStringToList(xgxt_code2);
            if (StringUtils.isNotBlank(xqxgxt)){
                List<String> xqxgxtList = convertStringToList(xqxgxt);
                bb.writeLog("xgxt_codeList-------->"+xgxt_codeList);
                bb.writeLog("xgxt_codeList2-------->"+xgxt_codeList2);
                bb.writeLog("xqxgxtList-------->"+xqxgxtList);
                if (xqxgxtList != null && !xqxgxtList.isEmpty()){
                    if((xtmcList.contains(szbm)) && (!Collections.disjoint(xgxt_codeList, xqxgxtList))){
                        ishq++;
                    }
                    // 判断两个集合是否有相同元素 有的话返回false，没有返回true
                    if (!Collections.disjoint(xgxt_codeList2, xqxgxtList)){
                        ishq2++;
                    }
                }
            }


//            bb.writeLog("ishq:"+ishq);
            if(hqbmsxflag >0)
            {
                if(ishq > 0)
                {
                    if(!"".equals(bshq))
                    {
                        bshq = "'"+bshq.replace(",","','")+"'";
                        String sql =   " select id,departmentname from hrmdepartment d where d.departmentcode in("+bshq+") ";
                        bb.writeLog("sql:"+sql);
                        rs.execute(sql);
                        while (rs.next()){
                            String id = Util.null2String(rs.getString("id"));
                            String departmentname = Util.null2String(rs.getString("departmentname"));
                            hqbmmap = new HashMap<>();
                            hqbmmap.put("id",id);
                            hqbmmap.put("name",departmentname);
                            hqmbList.add(hqbmmap);
                            hqbmvalue += hqbmvalue== "" ? id : ","+id ;
                        }
                    }
                }
                if(ishq2 > 0)
                {
                    if(!"".equals(bshq2))
                    {
                        bshq2 = "'"+bshq2.replace(",","','")+"'";
                        String sql =   " select id,departmentname from hrmdepartment d where d.departmentcode in("+bshq2+") ";
                        bb.writeLog("sql:"+sql);
                        rs.execute(sql);
                        while (rs.next()){
                            String id = Util.null2String(rs.getString("id"));
                            String departmentname = Util.null2String(rs.getString("departmentname"));
                            hqbmmap = new HashMap<>();
                            hqbmmap.put("id",id);
                            hqbmmap.put("name",departmentname);
                            hqmbList.add(hqbmmap);
                            hqbmvalue += hqbmvalue== "" ? id : ","+id ;
                        }
                    }
                }
            }
            String newHqbmValue = "";
            if (StringUtils.isNotBlank(hqbmvalue)){
                // 去重
                List<String> hqbmValueList = convertStringToList(hqbmvalue);
                List<String> newHqbmValueList = delRepeat1(hqbmValueList);
                newHqbmValue = newHqbmValueList.stream().collect(Collectors.joining(","));
            }

            List<Map<String, Object>> newHqmbList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(hqmbList)){
                // 去重
                newHqmbList = removeRepeatMapByKey(hqmbList, "id");
            }

            bb.writeLog("hqmbList:"+newHqmbList);
            bb.writeLog("hqbmvalue:"+newHqbmValue);

            apidatas.put("specialobj", newHqmbList);
            apidatas.put("hqbmvalue", newHqbmValue);
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * 根据map中的某个key 去除List中重复的map
     * @param list
     * @param mapKey
     * @return
     */
    public List<Map<String, Object>> removeRepeatMapByKey(List<Map<String, Object>> list, String mapKey){
        if (CollectionUtils.isEmpty(list)) return null;
        //把list中的数据转换成msp,去掉同一id值多余数据，保留查找到第一个id值对应的数据
        List<Map<String, Object>> listMap = new ArrayList<>();
        Map<String, Map> msp = new HashMap<>();
        for(int i = list.size()-1 ; i>=0; i--){
            Map map = list.get(i);
            String id = (String)map.get(mapKey);
            map.remove(mapKey);
            msp.put(id, map);
        }
        //把msp再转换成list,就会得到根据某一字段去掉重复的数据的List<Map>
        Set<String> mspKey = msp.keySet();
        for(String key: mspKey){
            Map newMap = msp.get(key);
            newMap.put(mapKey, key);
            listMap.add(newMap);
        }
        return listMap;
    }

    // List<String> 去重
    public List<String> delRepeat1(List<String> list) {
        List<String> listNew2 = new ArrayList<String>(new LinkedHashSet<String>(list));
        return listNew2;
    }
    // 字符串转换成list
    public List<String> convertStringToList(String strs){
        if (StringUtils.isNotBlank(strs)){
            String[] idStrs = strs.trim().split(",");
            if (idStrs.length > 0){
                List<String> strsList = new ArrayList<String>();
                for (String str : idStrs) {
                    if (StringUtils.isNotBlank(str)){
                        strsList.add(str.trim());
                    }
                }
                if (strsList.size() > 0){
                    return strsList;
                }
            }
        }
        return  null;
    }

    @GET
    @Path("/getsfXqpg")
    @Produces({MediaType.TEXT_PLAIN})
    public String getsfXqpg(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            HT_WorkflowInfo HT_WorkflowInfo = new HT_WorkflowInfo();
            RecordSet rs = new RecordSet();
            PropBean pb = new PropBean();
//            User user = HrmUserVarify.getUser( request, response );
//            int userid = user.getUID();


            Map<String,Object> param = ParamUtil.request2Map(request);
            String requestid = Util.null2String(param.get("requestid"));
            String nodeid = Util.null2String(param.get("nodeid"));
            String userids = "" ;
            String sql = " select userid from workflow_currentoperator where requestid="+requestid+" and nodeid="+nodeid ;
            rs.execute(sql);
            while (rs.next()){
                String userid = Util.null2String(rs.getString("userid"));
                userids += userids=="" ? userid : ","+userid ;
            }

            String tablename = HT_WorkflowInfo.getFormTableByRequestid(requestid);
            String mainid = HT_WorkflowInfo.getMainidByRequestid(requestid);
            String sftgxqpg = "" ;
            if(!"".equals(userids)){
                userids = "'"+userids.replace(",","','")+"'" ;
                sql = " select sftgxqpg from "+tablename+"_dt5 where mainid = "+mainid+" and xgry in("+userids+") and sfspg=1 ";
                rs.execute(sql);
                if (rs.next()){
                    sftgxqpg = Util.null2String(rs.getString("sftgxqpg"));
                }
            }
            apidatas.put("sftgxqpg", sftgxqpg);
            apidatas.put("userid", userids+"");
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/getLsdpInfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String getLsdpInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            User user = HrmUserVarify.getUser( request, response );
            Map<String,Object> param = ParamUtil.request2Map(request);
            apidatas = getService(request,response).getLsdpInfo(param,user);
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }

    @GET
    @Path("/getXxjsbInfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String getXxjsbInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            User user = HrmUserVarify.getUser( request, response );
            Map<String,Object> param = ParamUtil.request2Map(request);
            apidatas = getService(request,response).getXxjsbInfo(param);
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/getQtrysh")
    @Produces({MediaType.TEXT_PLAIN})
    public String getQtrysh(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            HT_WorkflowInfo HT_WorkflowInfo = new HT_WorkflowInfo();
            RecordSet rs = new RecordSet();
            User user = HrmUserVarify.getUser( request, response );
            int userid = user.getUID();

            Map<String,Object> param = ParamUtil.request2Map(request);
            String requestid = Util.null2String(param.get("requestid"));
            String tablename = HT_WorkflowInfo.getFormTableByRequestid(requestid);
            String mainid = HT_WorkflowInfo.getMainidByRequestid(requestid);
            String sftgxqpg = "" ;
            String sql = " select sftgxqpg from "+tablename+"_dt5 where mainid="+mainid+" and instr(','||fzclrjh||',',','||"+userid+"||',')>0 and sfspg=1 and (yspg is null or yspg = 0)";
            rs.execute(sql);
            if (rs.next()){
                sftgxqpg = Util.null2String(rs.getString("sftgxqpg"));
            }
            apidatas.put("sftgxqpg", sftgxqpg);
            apidatas.put("userid", userid+"");
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }

    @POST
    @Path("/createFreeNode")
    @Produces({MediaType.TEXT_PLAIN})
    public String createFreeNode(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            User user = HrmUserVarify.getUser( request, response );
            Map<String,Object> param = ParamUtil.request2Map(request);
            apidatas = getService(request,response).createFreeNode(user,param);
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


    @GET
    @Path("/getldsplist")
    @Produces({MediaType.TEXT_PLAIN})
    public String getldsplist(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        try {
            int requestid = Util.getIntValue(Util.null2String(request.getParameter("requestid")));    //
            int workflowid = Util.getIntValue(Util.null2String(request.getParameter("workflowid")));  //

            PropBean pb = new PropBean();
            String nodeid = pb.getNodeIdsByUnNumber("itxqsq_gsld");

            List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
            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 t.requestid=" +requestid +
                    " and t.workflowid=" + workflowid+
                    " and t.nodeid in("+nodeid+") " +
                    " order by receivedate,receivetime";
            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);
            }
            apidatas.put("value",fieldvalue);
            apidatas.put("specialobj",dataList);
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


}
