package com.engine.htsc.collaboration.service;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.htsc.collaboration.entity.TaskEntity;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.CodeBuild;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.lang.reflect.Field;
import java.util.*;

public class WorkflowTaskService extends Service {

    private Map<String, Object> createTask(TaskEntity taskEntity){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();

        try{
            if(taskEntity!=null){
                String rwmodeid = pb.getPropName("UF_RW_CUBEUUIUD");
                JSONObject jsonObject_rw = pb.getModeInfoByUUID(rwmodeid);
                int modeid = Util.getIntValue(jsonObject_rw.getString("modeid"));

                String uuid = UUID.randomUUID().toString();
                taskEntity.setModeuuid(uuid);
                taskEntity.setFormmodeid(modeid);
                taskEntity.setModedatacreatertype(0);
                taskEntity.setModedatacreatedate(TimeUtil.getCurrentDateString());
                taskEntity.setModedatacreatetime(TimeUtil.getOnlyCurrentTimeString());
                taskEntity.setCjrq(TimeUtil.getCurrentTimeString());

                String cjr = taskEntity.getCjr().toString();
                if(StringUtils.isNotEmpty(cjr)){
                    List<String> idList = getAllUserid(cjr);
                    taskEntity.setCjrzczhyc(String.join(",",idList));
                }

                String jbr = taskEntity.getJbr();
                if(StringUtils.isNotEmpty(jbr)){
                    List<String> jbrList = Arrays.asList(jbr.split(","));
                    Set<String> idSet = new HashSet<>();
                    for(String id:jbrList){
                        idSet.addAll(getAllUserid(id));
                    }
                    taskEntity.setJbrzzhyc(String.join(",",idSet));
                }

                String gzr = taskEntity.getGzr();
                if(StringUtils.isNotEmpty(gzr)){
                    List<String> gzrList = Arrays.asList(gzr.split(","));
                    Set<String> idSet = new HashSet<>();
                    for(String id:gzrList){
                        idSet.addAll(getAllUserid(id));
                    }
                    taskEntity.setTzydzzhyc(String.join(",",idSet));
                }


                Class<?> clazz = taskEntity.getClass();
                Field[] fields = clazz.getDeclaredFields();
                String insertFields = " insert into uf_rw(";
                String paramsStr  = " values(";
                Object[] values = new Object[fields.length];
                for(int i=0;i<fields.length;i++){
                    fields[i].setAccessible( true );
                    if(i==fields.length-1){
                        insertFields += fields[i].getName()+" )";
                        paramsStr += "? )";
                    }else{
                        insertFields += fields[i].getName()+",";
                        paramsStr += "?,";
                    }
                    try{
                        values[i] = fields[i].get(taskEntity);
                    }catch (Exception e){
                        new BaseBean().writeLog("保存任务数据错误："+e);
                    }
                }
                String insertSql = insertFields + paramsStr;
                bs.writeLog("insertSql:"+insertSql);
                bs.writeLog("values:"+values);
                boolean res = rs.executeQuery(insertSql,values);
                bs.writeLog("res:"+res);

                if(res){
                    int billid = 0;
                    rs.executeQuery("select id from uf_rw where modeuuid='"+uuid+"'" );
                    if (rs.next()) {
                        billid = Util.getIntValue( rs.getString( "id" ) );
                        bs.writeLog("billid:"+billid);
                        ModeRightInfo moderight = new ModeRightInfo();
                        moderight.editModeDataShare(taskEntity.getModedatacreater(),taskEntity.getFormmodeid(),billid);
                    }

                    int formid = 0 ;
                    rs.executeQuery("select formid from modeinfo where id= "+ modeid);
                    if(rs.next()){
                        formid = Util.getIntValue(Util.null2String(rs.getString("formid")));
                    }
                    bs.writeLog("formid:"+formid);

                    String rwbh = "";
                    rs.executeQuery("select id,codefieldid from ModeCode where modeid=? and isuse='1'", new Object[]{modeid});
                    if(rs.next()) {
                        CodeBuild codeBuild = new CodeBuild(rs.getInt("id"));
                        codeBuild.setModeId(modeid);
                        codeBuild.setLanguage(7);
                        rwbh = codeBuild.getModeCodeStr(formid,billid);
                    }
                    bs.writeLog("rwbh:"+rwbh);

                    String sql = " update uf_rw set rwbh='"+rwbh+"',cjzt=1 where id="+billid;
                    bs.writeLog(sql);
                    boolean bool = rs.execute(sql);
                    if(bool){
                        result.put("billid",billid);
                        result.put("modeid",modeid);
                        result.put("formid",formid);
                        result.put("status","1");
                        result.put("message","任务创建成功");
                        if(1==taskEntity.getRwzt()){
                            String now = TimeUtil.getCurrentTimeString();
                            String updateSql = "update uf_rw set rwfbsj = '"+now+"' where id = '"+billid+"'";
                            bs.writeLog(updateSql);
                            rs.executeUpdate(updateSql);
                            TaskService taskService = ServiceUtil.getService(TaskService.class);
                            taskService.sendMessage(String.valueOf(user.getUID()),String.valueOf(billid),"1");
                        }
                    } else{
                        result.put("billid","0");
                        result.put("status","-1");
                        result.put("message","新建任务异常，请联系系统管理员");
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.put("billid","0");
            result.put("status","-2");
            result.put("message","系统错误,请联系系统管理员");
        }
        return result;
    }

    /**
     * 重要事项
     * @param requestid
     * @return
     */
    public Map<String, Object> createFromImportantMatters(User user, String requestid){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();

        try{
            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setGllc(requestid);
            String sql = "";

            sql = "select requestnamenew from WORKFLOW_REQUESTBASE where requestid = '"+requestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                taskEntity.setRwbt(Util.null2String(rs.getString("requestnamenew"))+"协作任务");
            }

            int creater = user.getUID();
//            int creater = 11260;
            taskEntity.setModedatacreater(creater);
            taskEntity.setCjr(creater);
//            sql = "select departmentid from HRMRESOURCE where id = '"+creater+"'";
//            bs.writeLog(sql);
//            rs.executeQuery(sql);
//            if(rs.next()){
//                taskEntity.setSzbm(Integer.parseInt(Util.null2String(rs.getString("departmentid"))));
//            }
//            HT_Util ht_util=new HT_Util();
//            taskEntity.setSzjg(Integer.parseInt(ht_util.getszjg(Integer.toString(creater))));

            String modelableid = getReceiptLab(creater,"重要事项");
            taskEntity.setModelableid(modelableid);
            taskEntity.setMrbq(modelableid);
            taskEntity.setYxj(1);//高中低
            taskEntity.setRwzt(0);
            result = createTask(taskEntity);
        }catch (Exception e){
            e.printStackTrace();
            result.put("billid","1");
            result.put("status","-2");
            result.put("message","系统错误,请联系系统管理员");
        }
        return result;
    }

    /**
     * 其他流程创建任务
     * @param requestid
     * @return
     */
    public Map<String, Object> createFromSubImportantMatters(User user, String requestid){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();

        try{
            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setGllc(requestid);
            String sql = "";

            sql = "select requestnamenew from WORKFLOW_REQUESTBASE where requestid = '"+requestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                taskEntity.setRwbt(Util.null2String(rs.getString("requestnamenew"))+"协作任务");
            }

            int creater = user.getUID();
//            int creater = 11260;
            taskEntity.setModedatacreater(creater);
            taskEntity.setCjr(creater);

            String modelableid = getReceiptLab(creater,"分支机构重要事项");
            taskEntity.setModelableid(modelableid);
            taskEntity.setMrbq(modelableid);
            taskEntity.setYxj(1);//高中低
            taskEntity.setRwzt(0);
            result = createTask(taskEntity);
        }catch (Exception e){
            e.printStackTrace();
            result.put("billid","1");
            result.put("status","-2");
            result.put("message","系统错误,请联系系统管理员");
        }
        return result;
    }


    /**
     * 分支机构重要事项
     * @param requestid
     * @return
     */
    public Map<String, Object> createfromothertask(User user, String requestid){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();

        try{
            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setGllc(requestid);
            String sql = "";
            String labelname="";
            sql = "select requestnamenew,(select workflowname from workflow_base t where t.id=workflowid)as workflowname from WORKFLOW_REQUESTBASE where requestid = '"+requestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                taskEntity.setRwbt(Util.null2String(rs.getString("requestnamenew"))+"协作任务");
                labelname=Util.null2String(rs.getString("workflowname"));
            }

            int creater = user.getUID();
//            int creater = 11260;
            taskEntity.setModedatacreater(creater);
            taskEntity.setCjr(creater);
            if(StringUtils.isBlank(labelname)){
                labelname="其他";
            }
            String modelableid = getReceiptLab(creater,labelname);
            taskEntity.setModelableid(modelableid);
            taskEntity.setMrbq(modelableid);
            taskEntity.setYxj(1);//高中低
            taskEntity.setRwzt(0);
            result = createTask(taskEntity);
        }catch (Exception e){
            e.printStackTrace();
            result.put("billid","1");
            result.put("status","-2");
            result.put("message","系统错误,请联系系统管理员");
        }
        return result;
    }

    /**
     * 公司收文-主办部门
     * @param requestid
     * @return
     */
    public Map<String, Object> createFromReceipt(String requestid){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();

        try{
            TaskEntity taskEntity = new TaskEntity();
            Set<String> noticeSet = new HashSet<>();
            String sql = "";

            //获取主流程id
            String mainRequestid = "";
            sql = "select mainrequestid from WORKFLOW_SUBWFREQUEST where subrequestid = '"+requestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainRequestid = Util.null2String(rs.getString("mainrequestid"));
                taskEntity.setGllc(mainRequestid);
            }

            sql = "select requestnamenew,creater from WORKFLOW_REQUESTBASE where requestid = '"+mainRequestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                String title = Util.null2String(rs.getString("requestnamenew"))+"协作任务";
                taskEntity.setRwbt(title);
                String creater = Util.null2String(rs.getString("creater"));
                noticeSet.add(creater);//主流程创建人
            }

            int creater = 1;
            sql = "select zdcjr,zdtzydren from uf_lcrwrywh where lcxinxi = 'gsswzbbm'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                creater = Util.getIntValue(rs.getString("zdcjr"));
                String zdtzydren = Util.null2String(rs.getString("zdtzydren"));
                taskEntity.setModedatacreater(creater);
                taskEntity.setCjr(creater);
                if(StringUtils.isNotEmpty(zdtzydren)){
                    noticeSet.addAll(Arrays.asList(zdtzydren.split(",")));//指定通知阅读人
                }
            }

            String tableName = JAVATools.getMaintable(requestid);
            String mainTableName = JAVATools.getMaintable(mainRequestid);

            sql = "select rwms,zbry,zbbmnbsh,fzzbbmld from "+tableName+" where requestid = '"+requestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                taskEntity.setRwgs(Util.null2String(rs.getString("rwms")));
                taskEntity.setJbr(Util.null2String(rs.getString("zbry")));
                String zbbmnbsh = Util.null2String(rs.getString("zbbmnbsh"));
                String fzzbbmld = Util.null2String(rs.getString("fzzbbmld"));
                if(StringUtils.isNotEmpty(zbbmnbsh)){
                    bs.writeLog("zbbmnbsh:"+zbbmnbsh);
                    noticeSet.addAll(Arrays.asList(zbbmnbsh.split(",")));//主办部门内部审核
                }
                if(StringUtils.isNotEmpty(fzzbbmld)){
                    bs.writeLog("fzzbbmld:"+fzzbbmld);
                    noticeSet.addAll(Arrays.asList(fzzbbmld.split(",")));//主办部门领导
                }
            }

            sql = "select zqtx,zqtxyf,zqtxrq,zqtxsj,clsx from "+mainTableName+" where requestid = '"+mainRequestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                taskEntity.setZqtx(Util.null2String(rs.getString("zqtx")));
                taskEntity.setZqtxyf(Util.null2String(rs.getString("zqtxyf")));
                taskEntity.setZqtxrq(Util.null2String(rs.getString("zqtxrq")));
                taskEntity.setZqtxsj(Util.null2String(rs.getString("zqtxsj")));
                taskEntity.setJzrq(Util.null2String(rs.getString("clsx")));
            }

            String modelableid = getReceiptLab(creater,"收文任务");
            taskEntity.setModelableid(modelableid);
            taskEntity.setMrbq(modelableid);
            taskEntity.setYxj(1);//高中低
            taskEntity.setRwzt(2);
            taskEntity.setGzr(StringUtils.join(noticeSet,","));
            result = createTask(taskEntity);
        }catch (Exception e){
            e.printStackTrace();
            result.put("billid","1");
            result.put("status","-2");
            result.put("message","系统错误,请联系系统管理员");
        }
        return result;
    }

    private String getReceiptLab(int creater, String tabname){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();

        JSONObject jsonObject_rw = pb.getModeInfoByUUID(pb.getPropName("UF_RW_CUBEUUIUD"));
        Integer rwmodeid = Util.getIntValue(jsonObject_rw.getString("modeid"));

        String id = "";
        String sql = "select id from modeTabs_"+rwmodeid+" where tabname = '"+tabname+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            id = Util.null2String(rs.getString("id"));
        }else{
            Map<String,String> map = new HashMap<String,String>();
            map.put("tabname",tabname);
            map.put("color","722ed1");
            map.put("bgcolor","f9f0ff");
            map.put("bdcolor","d3adf7");
            map.put("type","1");
            map.put("creator",creater+"");

            sql = "select max(orderid) from modeTabs_"+rwmodeid;
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                int orderid = Util.getIntValue(rs.getString("max(orderid)"));
                orderid++;
                map.put("orderid",String.valueOf(orderid));
            }

            String dttablename = "";
            String dttablenvalue = "";
            for (Map.Entry<String, String> entry : map.entrySet())
            {
                String fieldname = Util.null2String(entry.getKey());
                String fieldvalue = Util.null2String(entry.getValue());
                dttablename += dttablename == "" ? fieldname : "," + fieldname;
                dttablenvalue += dttablenvalue == "" ? "'" + fieldvalue + "'" : ",'" + fieldvalue + "'";
            }
            String insertSql = "insert into modeTabs_"+rwmodeid+" ("+dttablename+") values("+dttablenvalue+")";
            bs.writeLog(insertSql);
            rs.executeUpdate(insertSql);

            sql = "select id from modeTabs_"+rwmodeid+" where tabname = '"+tabname+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                id = Util.null2String(rs.getString("id"));
            }
        }
        return id;
    }

    private List<String> getAllUserid(String id){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        List<String> idList = new ArrayList<>();

        String mainUserid = JAVATools.getmainhrmid(id);
        idList.add(mainUserid);
        String sql="select id from hrmresource where belongto = '"+mainUserid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        while(rs.next()){
            idList.add(Util.null2String(rs.getString("id")));
        }
        return idList;
    }
}
