package weaver.interfaces.htsc.sfxzdj;

import com.engine.htsc.sfxzdj.service.impl.SfxzdjServiceImpl;
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.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 SfzxdjBanJieAction 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 sql = "select * from " + tablename+ " where requestid = " + requestid;
        RecordSet rs = new RecordSet();
        RecordSet deptrs = new RecordSet();
        PropBean pb = new PropBean();
        rs.execute(sql);
        while(rs.next()){
            String mainid = rs.getString("id");
            String ngr = rs.getString("ngr");
            String hgry = rs.getString("hgry");//合规人员
            String cxjg = rs.getString("cxjg");//查询机关
            String szbm = rs.getString("szbm");
            String Sql = "select * from hrmdepartmentdefined where deptid =  "+szbm;
            deptrs.execute(Sql);
            deptrs.next();
            String code = deptrs.getString("depttypecode");
            //判断拟稿人所在部门类型
            String  cfbm ="0";
            String depttypecode = getcode(ngr);
            String sfxzdj_zbcode = pb.getPropName("sfxzdj_zbcode");
            if(sfxzdj_zbcode.indexOf(code)>-1){
                cfbm="1";

            }
            JAVATools.writelog("办结触发流程 depttypecode"+depttypecode);
            if(!(sfxzdj_zbcode.indexOf(depttypecode)>-1)){
                //判断当前处理人是否是总部，是则生成总部用印，不是分支机构
                String sfxzdj_fzworkflowid =pb.getPropName("sfxzdj_fzworkflowid");
                RecordSet deptRs = new RecordSet();
                String deptSql = "select * from HRMDEPARTMENT where departmentcode = 'ZZ001041'";
                deptRs.execute(deptSql);
                deptRs.next();
                String deptid = deptRs.getString("id");
                    if(StringUtils.isNotBlank(ngr)){
                        Map<String, String> hrm = getHrm(ngr);
                        HashMap<String, String> map = new HashMap<>();
//                        1、带出部门领导，根据hrmdepartmentdefined表中的deptid匹配主表所在部门，deptdirectors赋值部门领导审核bmldsh
//                        2、所在部门带出部门类型、部门类别，根据hrmdepartmentdefined表中的deptid匹配主表所在部门，depttypecode赋值部门类型deptTypeCode，deptscalelevelcode赋值部门类别bmlbcode
//                        5、带出私行中心，根据hrmdepartmentdefined表中的deptid匹配主表所在部门，sfsxzx赋值是否私行中心 sfsxzx
                        String deptfinedSql = "select * from hrmdepartmentdefined where  deptid = "+hrm.get("departmentid");
                        deptrs.execute(deptfinedSql);
                        JAVATools.writelog("触发分支结构用印deptfinedSql"+deptfinedSql);
                        if(deptrs.next()){

                            String deptdirectors = deptrs.getString("deptdirectors");
                            String typecode = deptrs.getString("depttypecode");
                            if(StringUtils.isNotBlank(deptrs.getString("sfsxzx"))){
                                String sfsxzx = deptrs.getString("sfsxzx");
                                map.put("sfsxzx",sfsxzx);
                            }
                            if(StringUtils.isNotBlank(deptdirectors) && !deptdirectors.contains(",")){
                                map.put("bmldsh",deptdirectors);
                            }

                            map.put("deptTypeCode",typecode);
                            String deptscalelevelcode = deptrs.getString("deptscalelevelcode");
                            if(StringUtils.isNotBlank(deptscalelevelcode)){
                                map.put("bmlbcode",deptscalelevelcode);
                            }
                        }
//                        3、文件类型带出业务主管部门，根据*uf_fzjgyysyfw*表中的wjlx匹配文件类型，wjlb匹配文件类别，
//                        ywzgbm赋值业务主管部门ywzgbm，fgsglg赋值分公司管理岗位fgsglgw，ywzgbmsfbj赋值业务主管部门负责人是否必经ywzgbmfzrsfbj，
//                        sqjh赋值授权号sqh，sfsqjh赋值是否授权简化sfsqjh，ywzgbmbjns赋值业务主管部门必经内审ywzgbmbjns，
//                        fgsbjjd赋值分公司必经节点fgsbjjd
                        String uf_fzjgyysyfw_sql = "select * from uf_fzjgyysyfw where wjlx = 93 and wjlb = 2";
                        JAVATools.writelog("触发分支结构用印uf_fzjgyysyfw_sql"+uf_fzjgyysyfw_sql);
                        deptrs.execute(uf_fzjgyysyfw_sql);
                        String fgsglg = "";
                        String ywzgbm = "";
                        if(deptrs.next()){
                            if(StringUtils.isNotBlank(deptrs.getString("ywzgbm"))){
                                map.put("ywzgbm",deptrs.getString("ywzgbm"));
                                ywzgbm= deptrs.getString("ywzgbm");
                                JAVATools.writelog("触发分支机构用印ywzgbm"+ywzgbm);
                            }
                            if(StringUtils.isNotBlank(deptrs.getString("fgsglg"))){
                                fgsglg= deptrs.getString("fgsglg");
                                map.put("fgsglgw",deptrs.getString("fgsglg"));
                            }
                            if(StringUtils.isNotBlank(deptrs.getString("ywzgbmsfbj"))){
                                map.put("ywzgbmfzrsfbj",deptrs.getString("ywzgbmsfbj"));
                            }
                            if(StringUtils.isNotBlank(deptrs.getString("sqjh"))){
                                map.put("sqh",deptrs.getString("sqjh"));
                            }
                            if(StringUtils.isNotBlank(deptrs.getString("sfsqjh"))){
                                map.put("sfsqjh",deptrs.getString("sfsqjh"));
                            }
                            if(StringUtils.isNotBlank(deptrs.getString("ywzgbmbjns"))){
                                map.put("ywzgbmbjns",deptrs.getString("ywzgbmbjns"));
                            }
                            if(StringUtils.isNotBlank(deptrs.getString("fgsbjjd"))){
                                map.put("fgsbjjd",deptrs.getString("fgsbjjd"));
                            }
                        }
//                        4、带出邮寄对象，根据uf_fzjgcysjr表中ssjg匹配所在部门，sjrxm赋值寄送对象jsdx
                        String uf_fzjgcysjr_sql = "select * from uf_fzjgcysjr where ssjg = " + hrm.get("departmentid");
                        JAVATools.writelog("触发分支结构用印uf_fzjgcysjr_sql"+uf_fzjgcysjr_sql);
                        deptrs.execute(uf_fzjgcysjr_sql);
                        if(deptrs.next() && StringUtils.isNotBlank(deptrs.getString("sjrxm"))){
                            map.put("jsdx",deptrs.getString("sjrxm"));
                        }
//                        6、分公司带出部门负责人，根据hrmdepartmentdefined表中的deptid匹配主表所属分公司 ，deptdirectors赋值部门负责人bmfzr1。（所属分公司是sql代码带出。）
                        String fgsSql = "select DECODE(de.deptTypeCode,'JGLX04',d.supdepid,'JGLX09',d.supdepid,'JGLX03',d.id) as cid from hrmdepartment d,hrmdepartmentdefined de,hrmresource h where d.id=de.deptid and h.departmentid=de.deptid and h.id= " +ngr;
                        JAVATools.writelog("触发分支结构用印fgsSql"+fgsSql);
                        deptrs.execute(fgsSql);
                        if(deptrs.next() && StringUtils.isNotBlank(deptrs.getString("cid"))){
                            String fgsfzrsql = " select * from hrmdepartmentdefined where deptid = " + deptrs.getString("cid");
                            JAVATools.writelog("触发分支结构用印fgsfzrsql"+fgsfzrsql);
                            deptrs.execute(fgsfzrsql);
                            deptrs.next();
                            if(StringUtils.isNotBlank(deptrs.getString("deptdirectors"))){
                                map.put("bmfzr1",deptrs.getString("deptdirectors"));
                            }
                        }
//                        7、分公司管理岗带出人员，根据uf_lcgwry表中的xzlc匹配选择流程，xzgw匹配分公司管理岗位，jg匹配所属机构，ry赋值分公司管理岗人员fgsglgry
                        if(StringUtils.isNotBlank(fgsglg)){
                            String uf_lcgwry_sql = "select * from uf_lcgwry where xzgw = '"+fgsglg+"' and jg ="+hrm.get("supdepid") +" and xzlc = 'fzjgyy'";
                            JAVATools.writelog("触发分支结构用印uf_lcgwry_sql"+uf_lcgwry_sql);
                            deptrs.execute(uf_lcgwry_sql);
                            if(deptrs.next() && StringUtils.isNotBlank(deptrs.getString("ry"))){
                                map.put("fgsglgry",deptrs.getString("ry"));
                            }
                        }
//                        8、业务主管部门带出部门负责人,根据hrmdepartmentdefined表中的deptid匹配主表业务主管部门，deptdirectors赋值部门负责人-业务主管部门bmfzrywzgbm
                       if(StringUtils.isNotBlank(ywzgbm)){
                           String ywzgbmSql = "select * from hrmdepartmentdefined where deptid = " + ywzgbm;
                           JAVATools.writelog("触发分支结构用印ywzgbmSql"+ywzgbmSql);
                           deptrs.execute(ywzgbmSql);
                           if(deptrs.next() && StringUtils.isNotBlank(deptrs.getString("deptdirectors"))){
                               map.put("bmfzrywzgbm",deptrs.getString("deptdirectors"));
                           }
                       }
                        // 是否外部触发sfwbcf，check框，赋值1
//                                触发来源cfly，选择框，赋值0
                        map.put("wjlb","2");
                        map.put("wjlx","93");
                        map.put("sfwbcf","1");
                        map.put("cfly","0");
                        map.put("cfbm",cfbm);//触发部门
                        map.put("sjbmsp","1");
                        map.put("sfnbsy","0");
                        map.put("sbwjbt","正文");
                        map.put("sfbh","0");
                        map.put("sfpbbh","0");
                        map.put("qzbj","#华泰签章标记符#");
                        map.put("shfs","1");
                        map.put("ldspsdfs","0");
                        map.put("ldspsdfs2","0");
                        map.put("ts1","文件类型将影响流程审批，请根据具体内容选择正确的适用范围");
                        map.put("zzyongtu","仅用于办理XX事宜");
                        map.put("sfsqjh","1");
                        map.put("xzlc","fzjgyy");
                        map.put("sfsgzxms","0");
                        map.put("sfsghgsh","0");
                        map.put("lkrqtsyq","1");
                        map.put("ts2","所有需要用印的文件不论格式请上传入用印文件，附件仅作为说明性文档供参考");
                        map.put("cfglb",deptid);
                        map.put("lclxbh","fzjgyy");
                        map.put("bt","关于协助"+cxjg+"查询的用印申请");
                        map.put("ngr",ngr);
                        map.put("szbm",hrm.get("departmentid"));
                        map.put("szjg",hrm.get("supdepid"));
                        map.put("jjcd","0");
                        map.put("lxfs",hrm.get("phone"));
                        map.put("sfzzfyjyy","1");
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        map.put("ngrq",format.format(new Date()));
                        map.put("qttzyddx",hgry);
                        map.put("gllc",requestid);
                        String s = WorkflowCreateByRequestMap(ngr,sfxzdj_fzworkflowid,"关于协助"+cxjg+"查询的用印申请","0",map);
                        JAVATools.writelog("会签部门触发流程 requestid"+s);
                        requestids = requestids+s+",";
                        //添加通知阅读人
                        SfxzdjServiceImpl sfxzdjService = new SfxzdjServiceImpl();
                        sfxzdjService.addReadingUser(requestid,ngr);

                    }
            }
                JAVATools.writelog("办结触发流程 结束");
                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;
    }
}
