package com.engine.htsc.cooperation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
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.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.MessageDetailLog;
import weaver.interfaces.htsc.comInfo.PropBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.text.SimpleDateFormat;
import java.util.*;

public class TaskShareUser {

    @POST
    @Path("/TaskShareUser")
    @Produces({MediaType.TEXT_PLAIN})
    public String TaskShareUser(@Context HttpServletRequest request, @Context HttpServletResponse response){
        PropBean propBean = new PropBean();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        ModeRightInfo mode=new ModeRightInfo();
        Map<String, Object> apidatas = new HashMap<String, Object>();
        SimpleDateFormat sd= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MessageDetailLog meslog=new MessageDetailLog("uf_rw_dt2");
        String datetime=sd.format(new Date());
        String rwbillid="";
        try{
            User user = HrmUserVarify.getUser(request, response);
            rwbillid = Util.null2String(request.getParameter("billid"));
            String bgxr = Util.null2String(request.getParameter("bgxr"));
            if(rwbillid==""||bgxr==""){
                apidatas.put("status", false);
                apidatas.put("errormsg", "传递参数为空");
            }

            List<String> gzrList = new ArrayList<>();
            String sql = "select gzr from uf_rw where id = '"+rwbillid+"'";
            rs.executeQuery(sql);
            if(rs.next()){
                String gzr = Util.null2String(rs.getString("gzr"));
                if(StringUtils.isNotEmpty(gzr)){
                    gzrList.addAll(Arrays.asList(gzr.split(",")));
                }
            }

            String userarray= JAVATools.disinctrlist(bgxr.split(","));
            String[] userlist = userarray.split(",");
            bb.writeLog("userarray:"+userarray);
            for (int i=0;i<userlist.length;i++) {
                if(!"".equals(userlist[i])) {

                    bb.writeLog("userlist:"+userlist[i]);

                    try {
                        String usernewid=JAVATools.getmainhrmid(userlist[i]);

                        //共享人添加到参与人，去重
                        boolean flag = false;
                        for(String gzrid:gzrList){
                            String gzrmainid = JAVATools.getmainhrmid(gzrid);
                            if(usernewid.equals(gzrmainid)){
                                flag = true;
                                break;
                            }
                        }
                        if(!flag){
                            gzrList.add(userlist[i]);
                        }

                        String sqlvalue = "insert into uf_rw_dt2(mainid,czr,bgxr,gxsj) values(?,?,?,?)";
                        rs.executeQuery(sqlvalue, new Object[]{rwbillid, user.getUID(), usernewid, datetime});
                   }catch (Exception exo){
                        String mes="czr:"+ user.getUID()+"bgxr:"+userlist[i]+"gxsj:"+datetime+" "+meslog.error;
                        meslog.writLogsnotretrun(rwbillid,exo.getMessage(),"0",meslog.error);
                    }
                }
            }

            String newgzr = String.join(",",gzrList);
            String tzydzzhyc = "" ;
            if(!"".equals(newgzr)){
                tzydzzhyc= JAVATools.GetZctogid(newgzr);
            }
            String updateSql = "update uf_rw set gzr = '"+newgzr+"', tzydzzhyc = '"+tzydzzhyc+"'  where id = '"+rwbillid+"'";
            bb.writeLog(updateSql);
            rs.executeUpdate(updateSql);

            JSONObject jsonObject=propBean.getModeInfoByUUID(propBean.getPropName("UF_RW_CUBEUUID"));
            int nodeid = Integer.parseInt(jsonObject.get("modeid").toString());
            mode.editModeDataShare(user.getUID(),nodeid,Integer.parseInt(rwbillid));

            apidatas.put("status", true);
        }catch (Exception e) {
            e.printStackTrace();
            apidatas.put("status", false);
            apidatas.put("errormsg", "catch exception : " + e.getMessage());
            meslog.writLogsnotretrun(rwbillid,e.getMessage(),"0",meslog.error);

        }

        return JSON.toJSONString(apidatas);
    }



    @POST
    @Path("/CooperationShareUser")
    @Produces({MediaType.TEXT_PLAIN})
    public String CooperationShareUser(@Context HttpServletRequest request, @Context HttpServletResponse response){
        PropBean propBean = new PropBean();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        ModeRightInfo mode=new ModeRightInfo();
        Map<String, Object> apidatas = new HashMap<String, Object>();
        SimpleDateFormat sd= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MessageDetailLog meslog=new MessageDetailLog("uf_xzsy_dt1");
        String datetime=sd.format(new Date());
        String rwbillid="";
        try{
            User user = HrmUserVarify.getUser(request, response);
            rwbillid = Util.null2String(request.getParameter("billid"));
            String bgxr = Util.null2String(request.getParameter("bgxr"));
            if(rwbillid==""||bgxr==""){
                apidatas.put("status", false);
                apidatas.put("errormsg", "传递参数为空");
            }

            String modedatacreater = "" ;
            List<String> tzydrList = new ArrayList<>();
            String sql = " select modedatacreater,tzydr from uf_xzsy where id="+rwbillid ;
            rs.execute(sql);
            if(rs.next()){
                modedatacreater = Util.null2String(rs.getString("modedatacreater"));
                String tzydr = Util.null2String(rs.getString("tzydr"));
                if(StringUtils.isNotEmpty(tzydr)){
                    tzydrList.addAll(Arrays.asList(tzydr.split(",")));
                }
            }


            String userarray = JAVATools.disinctrlist(bgxr.split(","));
            for (String userid:userarray.split(",")) {
                if(!"".equals(userid)) {
                    try {
                        String usernewid = JAVATools.getmainhrmid(userid);

                        //共享人添加到参与人，去重
                        boolean flag = false;
                        for(String tzydrid:tzydrList){
                            String tzydrmainid = JAVATools.getmainhrmid(tzydrid);
                            if(usernewid.equals(tzydrmainid)){
                                flag = true;
                                break;
                            }
                        }
                        if(!flag){
                            tzydrList.add(userid);
                        }

                        String sqlvalue = "insert into uf_xzsy_dt1(mainid,czr,bgxr,gxsj) values(?,?,?,?)";
                        rs.executeQuery(sqlvalue, new Object[]{rwbillid, user.getUID(), usernewid, datetime});
                    }catch (Exception exo){
                        String mes="czr:"+ user.getUID()+"bgxr:"+userid+"gxsj:"+datetime+" "+meslog.error;
                        meslog.writLogsnotretrun(rwbillid,mes,"0",meslog.error);
                    }
                }
            }

            String newtzydr = String.join(",",tzydrList);
            String tzydzzhyc = "" ;
            if(!"".equals(newtzydr)){
                tzydzzhyc= JAVATools.GetZctogid(newtzydr);
            }
            String updateSql = "update uf_xzsy set tzydr = '"+newtzydr+"', tzydzzhyc = '"+tzydzzhyc+"'  where id = '"+rwbillid+"'";
            bb.writeLog(updateSql);
            rs.executeUpdate(updateSql);

            JSONObject jsonObject = propBean.getModeInfoByUUID(propBean.getPropName("UF_XZSY_CUBEUUIUD"));
            int modeid = Integer.parseInt(jsonObject.get("modeid").toString());
            mode.rebuildModeDataShareByEdit(Util.getIntValue(modedatacreater),modeid,Integer.parseInt(rwbillid));

            apidatas.put("status", true);
        }catch (Exception e) {
            e.printStackTrace();
            apidatas.put("status", false);
            apidatas.put("errormsg", "catch exception : " + e.getMessage());
            meslog.writLogsnotretrun(rwbillid,e.getMessage(),"0",meslog.error);

        }

        return JSON.toJSONString(apidatas);
    }

}
