package weaver.interfaces.htsc.sfxzdj;

import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.workflow.WorkflowCreateHandler;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SfzxdjhqbmAction extends BaseBean implements Action {

    @Override
    public String execute(RequestInfo requestinfo) {
        String requestids = "";
        String requestid = requestinfo.getRequestid();//请求ID
        JAVATools.writelog("会签部门触发流程action开始");
        JAVATools.writelog("会签部门触发流程 requestid"+requestid);
        String workflowid = requestinfo.getWorkflowid(); //流程ID
        String tablename = requestinfo.getRequestManager().getBillTableName();//表单名称
        JAVATools.writelog("会签部门触发流程 tablename"+tablename);
        User usr = requestinfo.getRequestManager().getUser();//获取当前操作用户对象
        JAVATools.writelog("会签部门触发流程 User"+usr.getUID());
//        String requestid = "5433436";//请求ID
//        String workflowid = requestinfo.getWorkflowid(); //流程ID
//        String tablename = "formtable_main_518";//表单名称
//        User usr = new User();
//        usr.setUid(27817);
        String sql = "select * from " + tablename+ " where requestid = " + requestid;
        RecordSet rs = new RecordSet();
        PropBean pb = new PropBean();
        rs.execute(sql);

        while(rs.next()){
            String mainid = rs.getString("id");
            String ngr = rs.getString("ngr");
            String cxjg = rs.getString("cxjg");//查询机关
//            String dt6Sql = "select * from "+tablename+"_dt6" + " where lcid = "+ requestid+" and to_char(dqczz) = "+usr.getUID();
            String dt6Sql = "select * from "+tablename+"_dt6" + " where lcid = "+ requestid;
            JAVATools.writelog("会签部门触发流程 dt6Sql"+dt6Sql);
            rs.execute(dt6Sql);

            while(rs.next()){
                String dt6Dqczz = rs.getString("dqczz");
                JAVATools.writelog("会签部门触发流程 dt6Dqczz"+dt6Dqczz);
                String dt6Zdclr = rs.getString("zdclr");
                JAVATools.writelog("会签部门触发流程 dt6Zdclr"+dt6Zdclr);
                String depttypecode = getcode(ngr);
                JAVATools.writelog("会签部门触发流程 depttypecode"+depttypecode);
                String sfxzdj_zbcode = pb.getPropName("sfxzdj_zbcode");
                JAVATools.writelog("会签部门触发流程 sfxzdj_zbcode"+sfxzdj_zbcode);
                if(sfxzdj_zbcode.indexOf(depttypecode)>-1){
                    //判断当前处理人是否是总部，是则生成总部用印，不是分支机构
                    String dt6depttypecode = getcode(dt6Dqczz);
                    JAVATools.writelog("会签部门触发流程 dt6depttypecode"+dt6depttypecode);
                    if(sfxzdj_zbcode.indexOf(dt6depttypecode)>-1){
                        String sfxzdj_zbworkflowid =pb.getPropName("sfxzdj_zbworkflowid");
                        String[] split = dt6Zdclr.split(",");
                        JAVATools.writelog("会签部门触发流程 split"+split.toString());
                        for (String id :split ) {
                            if (StringUtils.isNotBlank(id)) {
                                Map<String, String> hrm = getHrm(id);
                                JAVATools.writelog("会签部门触发流程 hrm"+hrm.toString());
                                HashMap<String, String> map = new HashMap<>();
                                map.put("bt","关于协助"+cxjg+"查询的用印申请");
                                map.put("ngr",id);
                                map.put("szbm",hrm.get("departmentid"));
                                map.put("szjg",hrm.get("supdepid"));
                                map.put("jjcd","0");
                                map.put("lxfs",hrm.get("phone"));
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                map.put("ngrq",format.format(new Date()));
                                map.put("qttzyddx",ngr);
                                WorkflowCreateHandler wfl=new WorkflowCreateHandler();
                                String s = wfl.WorkflowCreateByRequestMap(id,sfxzdj_zbworkflowid,"关于协助"+cxjg+"查询的用印申请","0",map);
                                JAVATools.writelog("会签部门触发流程 requestid"+s);
                                requestids = requestids+s+",";
                            }
                        }
                    }else{
                        String sfxzdj_fzworkflowid =pb.getPropName("sfxzdj_fzworkflowid");
                        String[] split = dt6Zdclr.split(",");
                        JAVATools.writelog("会签部门触发流程 split"+split.toString());
                        for (String id :split ) {
                            if (StringUtils.isNotBlank(id)) {
                                Map<String, String> hrm = getHrm(id);
                                JAVATools.writelog("会签部门触发流程 hrm"+hrm.toString());
                                HashMap<String, String> map = new HashMap<>();
                                map.put("bt","关于协助"+cxjg+"查询的用印申请");
                                map.put("ngr",id);
                                map.put("szbm",hrm.get("departmentid"));
                                map.put("szjg",hrm.get("supdepid"));
                                map.put("jjcd","0");
                                map.put("lxfs",hrm.get("phone"));
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                map.put("ngrq",format.format(new Date()));
                                map.put("qttzyddx",ngr);
                                WorkflowCreateHandler wfl=new WorkflowCreateHandler();
                                String s = wfl.WorkflowCreateByRequestMap(id, sfxzdj_fzworkflowid, "关于协助" + cxjg + "查询的用印申请", "0", map);
                                JAVATools.writelog("会签部门触发流程 requestid"+s);
                                requestids = requestids+s+",";
                            }
                        }
                    }

                }else {
                    JAVATools.writelog("会签部门触发流程不触发");
                    return Action.SUCCESS;
                }
                JAVATools.writelog("会签部门触发流程 dt6Dqczz"+dt6Dqczz);
                saveDt7(requestids,tablename,mainid);
            }
        }




        return Action.SUCCESS;
    }

    public void  saveDt7(String requestids,String tablename ,String mainid){
        RecordSet rs = new RecordSet();
        String[] split = requestids.split(",");
        for (String id:split) {
            //通过用印流程的requestid查询用印的数据保存到建模中
            if(StringUtils.isNotBlank(id)){
                String yySql = "select * from workflow_requestbase where  requestid = "+ id ;
                rs.execute(yySql);
                rs.next();
                String flowid = rs.getString("workflowid");
                String currentnodeid = rs.getString("currentnodeid");
                String requestname = rs.getString("requestname");
                String currentnodetype = rs.getString("currentnodetype").equals("3")?"已办结":"进行中";
                yySql = "select * from workflow_currentoperator  where nodeid = "+currentnodeid+" and requestid = "+id;
                rs.execute(yySql);
                rs.next();
                String userid = rs.getString("userid");
                String dt7Sql = "insert into " + tablename+"_dt7 (lcid,zt,lcbt,dqclr,mainid) values ('"+id+"','"+currentnodetype+"','"+requestname+"','"+userid+"','"+mainid+"')";
                rs.execute(dt7Sql);
            }




        }
    }
    public String getcode(String ngr){
        RecordSet rs = new RecordSet();
        String hrmSql = "select * from hrmresource where id = "+ngr;
        rs.execute(hrmSql);
        rs.next();
        String departmentid = rs.getString("departmentid");
        String deptSql = "select * from hrmdepartmentdefined where deptid =  "+departmentid;
        rs.execute(deptSql);
        rs.next();

        String depttypecode = rs.getString("depttypecode");
        return depttypecode;
    }
    public Map<String,String> getHrm(String ngr){
        HashMap<String, String> result = new HashMap<>();
        RecordSet rs = new RecordSet();
        String hrmSql = "select * from hrmresource where id = "+ngr;
        rs.execute(hrmSql);
        rs.next();
        String departmentid = rs.getString("departmentid");
        result.put("phone",rs.getString("mobile"));
        result.put("departmentid",departmentid);
        String deptSql = "select * from hrmdepartment where id =  "+departmentid;
        rs.execute(deptSql);
        rs.next();
        result.put("supdepid",rs.getString("supdepid"));
        return result;
    }
    /**
     *
     * @Title: WorkflowCreateByMainTableMap
     * @param @param creatorId    创建人Id
     * @param @param workflowId   流程Id
     * @param @param requestName  请求标题
     * @param @param IsNextFlow   是否提交到下一节点
     * @param @param requestMap   Map格式的主表数据<fieldname,fieldvalue>=<字段名称,字段值>
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public String WorkflowCreateByRequestMap(String creatorId ,String workflowId ,String requestName ,String IsNextFlow,Map<String,String> requestMainMap)
    {
        BaseBean bs = new BaseBean();
        bs.writeLog("-----创建流程传递的参数个数--------");
        bs.writeLog("creatorId:"+creatorId);
        bs.writeLog("workflowId:"+workflowId);
        bs.writeLog("requestName:"+requestName);
        bs.writeLog("IsNextFlow:"+IsNextFlow);

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid(creatorId);//创建人Id
        requestInfo.setWorkflowid(workflowId);//工作流Id
        requestInfo.setDescription(requestName);//请求标题
        if(!"".equals(IsNextFlow))
        {
            requestInfo.setIsNextFlow(IsNextFlow);
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, String> entry : requestMainMap.entrySet())
        {
            propertyArray[p] = new Property();
            propertyArray[p].setName(Util.null2String(entry.getKey()));
            propertyArray[p].setValue(Util.null2String(entry.getValue()));
            bs.writeLog("\r\n---p="+p+"---Key="+entry.getKey()+"---Value="+entry.getValue());
            p++;
        }
        bs.writeLog("-----创建流程传递的参数个数p="+p);
        mainTableInfo.setProperty(propertyArray);
        requestInfo.setMainTableInfo(mainTableInfo);

        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest(requestInfo);//创建请求id
            } catch (Exception e) {
                bs.writeLog("======="+e.getMessage());
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始");
            WorkflowComInfo wfcif =new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append("\r\n-----姓名:"+rscif.getLastname(rcif.getRequestCreater(requestid)));
            sbf.append("\r\n-----时间:"+rcif.getRequestCreateTime(requestid));
            sbf.append("\r\n-----创建流程:"+wfcif.getWorkflowname(workflowId));
            sbf.append("\r\n-----请求:"+rcif.getRequestname(requestid));
            sbf.append("\r\n-----请求:"+requestid);
            sbf.append("\r\n-----创建工作流记录日志结束");
            bs.writeLog(sbf.toString());
            System.out.println(""+sbf.toString());
        } catch (Exception e) {
            bs.writeLog("错误：" + e);
            System.out.println("错误：" + e);
        }
        return requestid;
    }
}
