package weaver.interfaces.htsc.payment;

import com.alibaba.fastjson.JSON;
import com.engine.htsc.payment.enums.Sequences;
import com.engine.htsc.payment.util.CoWfUtil;
import com.engine.htsc.payment.util.PayUtil;
import org.apache.commons.lang3.StringUtils;

import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;

import weaver.hrm.resource.ResourceComInfo;
import com.weaver.general.BaseBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 建模中间表uf_yfkmiddle定时刷新
 * 预付款流程表formtable_main_213,
 * 自动创建流程
 */
public class AdvancePaymentJob extends weaver.interfaces.schedule.BaseCronJob {
    private Log log = LogFactory.getLog(this.getClass());


    @Override
    public void execute() {
        PropBean pp = new PropBean();
        String yskmPre = pp.getPropName("YFKFYQRaccountTreeId");
        String hjkmPre = pp.getPropName("YFKKJRaccountTreeId");
        log.info("定时任务自动创建流程开始======");
        RecordSetTrans rst = new RecordSetTrans();
        RecordSet rs = new RecordSet();
        RecordSet rsdetail = new RecordSet();
        try{
            rst.setAutoCommit(false);
            PropBean pb = new PropBean();
            //流水号
            int number = -1;
            String workflowId = pb.getPropName("YFKQR_WORKFLOWID");
            String tableName = "formtable_main_";
            //获取预付款流程表名
            rs.executeQuery("select formid from workflow_base where id = ?",workflowId);
            if (rs.next()){
                int formid = Math.abs(Util.getIntValue(rs.getString("formid")));
                tableName = tableName + formid;
                log.info("预付款流程表名=="+tableName);
            }else {
                log.info("获取预付款流程表名失败==");
                return;
            }
            String IsNextFlow = "1"; //1提交到下一节点，0不提交
            //1.遍历建模中间表 sfcf 1未触发
            rs.executeQuery("select a.id,a.zzfptjr,a.reqid,a.lcbh,a.ngr,a.bt,a.szbm,a.jjcd,a.jjyy,a.lxfs," +
                    " a.ngsj,a.xjhjmx,a.ngrfyhj,a.fyhjsp,a.ggfyqtfy,a.fkxx,a.fzjgcwjl, " +
                    " (select wm_concat_old(b.skdw) from uf_yfkmiddle_dt11 b where a.id = b.mainid) " +
                    " as skdw from uf_yfkmiddle a where (a.sfcf = 1 or a.sfcf is null) and a.sffkqr = 1");
            while (rs.next()) {
                log.info("建模存在未触发的数据数据");
                Map<String,String> requestMainMap = new HashMap<String,String>();
                Integer uf_id = Util.getIntValue(rs.getString("id"));
                String requestid = Util.null2String(rs.getString("reqid"));
                String lcbh = Util.null2String(rs.getString("lcbh"));
                String ngr = Util.null2String(rs.getString("ngr"));
                String bt = Util.null2String(rs.getString("bt"));
                String szbm = Util.null2String(rs.getString("szbm"));
                String jjcd = Util.null2String(rs.getString("jjcd"));
                String jjyy = Util.null2String(rs.getString("jjyy"));
                String lxfs = Util.null2String(rs.getString("lxfs"));
                String ngsj = Util.null2String(rs.getString("ngsj"));
                String xjhjmx = Util.null2String(rs.getString("xjhjmx"));
                String ngrfyhj = Util.null2String(rs.getString("ngrfyhj"));
                String fyhjsp = Util.null2String(rs.getString("fyhjsp"));
                String skdw = Util.null2String(rs.getString("skdw"));
                String ggfyqtfy = Util.null2String(rs.getString("ggfyqtfy"));
                String fkxx = Util.null2String(rs.getString("fkxx"));
                String fzjgcwjl = Util.null2String(rs.getString("fzjgcwjl"));
                String zzfptjr = Util.null2String(rs.getString("zzfptjr"));
                String requestName = lcbh + bt + "的预付款费用确认";
                String bz = "收款方： "+skdw;
                log.info("预付款流程确认标题=="+requestName);

                //生成流程编号
//                int formModeId = PayUtil.getFormModeIdByCubeName("uf_fklcbh");
////                StringBuilder mark = new StringBuilder(); // 流程编码
////                String workflowName = "";
////                String unNumber = "";
////
////                rsdetail.executeQuery("select workflowname,unnumber from workflow_base where id=?",workflowId);
////                if (rsdetail.next()){
////                    workflowName = Util.null2String(rsdetail.getString("workflowname"));
////                    unNumber = Util.null2String(rsdetail.getString("unnumber"));
////                }
////                log.info("==流程名称和唯一编码=="+workflowName+"==="+unNumber);
////                String modeUuid = "";
////                LocalDateTime localDateTime = LocalDateTime.now();
////                String date = localDateTime.format(DateTimeFormatter.ofPattern("yyyyMM"));
////                rsdetail.executeQuery("select id,lsh,modeuuid from uf_fklcbh where ny = ? and" +
////                        " lclx = ?",date,unNumber);
////                if (rsdetail.next()){
////                    if (number == -1){
////                        number = Util.getIntValue(rsdetail.getString("lsh")) + 1;
////                    }else {
////                        number = number + 1;
////                    }
////
////                    int id = Util.getIntValue((rsdetail.getString("id")));
////                    modeUuid = Util.null2String(rsdetail.getString("modeuuid"));
////
////                    rst.executeUpdate("update uf_fklcbh set lsh = ? where id = ?",number,id);
////                    mark = new StringBuilder(number + "");
////                    while(mark.length() < 6){
////                        mark.insert(0,"0");
////                    }
////                    mark = new StringBuilder(workflowName + date + mark);
////                }else {
////                    String createDate = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
////                    String createTime = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
////                    //插入
////                    String insertSql = "insert into uf_fklcbh" +
////                            "(FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME,MODEUUID,LSH,NY,LCLX) \n" +
////                            "values(?,?,?,?,?,?,?,?,?)";
////                    String uuid = UUID.randomUUID().toString();
////                    modeUuid = uuid;
////                    rst.executeUpdate(insertSql, formModeId, ngr, 0, createDate, createTime, uuid, "1", date, unNumber);
////                    mark = new StringBuilder(workflowName + date + "000001");
////                }
//                log.info("==流程编号=="+mark);
//
//
//                //权限重构
//                int dataId = PayUtil.getDataIdByUUID(modeUuid);
//                ModeRightInfo modeRightInfo = new ModeRightInfo();
//                modeRightInfo.editModeDataShare(1, formModeId, dataId);
                
//                预付款流程
                String mark = CoWfUtil.getRequestMarkByUnNumber("zbyfkfyqr", Sequences.NET_REI_WORKFLOW_SEQ_ZB);

                requestMainMap.put("zzfptjr",zzfptjr);
                requestMainMap.put("ngr",ngr);
                requestMainMap.put("glyfklc",requestid);
                requestMainMap.put("szbm",szbm);
                requestMainMap.put("jjcd",jjcd);
                requestMainMap.put("jjyy",jjyy);
                requestMainMap.put("lxfs",lxfs);
                requestMainMap.put("ngsj",ngsj);
                requestMainMap.put("xjhjmx",xjhjmx);
                requestMainMap.put("ngrfyhj",ngrfyhj);
                requestMainMap.put("fyhjsp",fyhjsp);
                requestMainMap.put("ggfyqtfy",ggfyqtfy);
                requestMainMap.put("bz",bz);
                requestMainMap.put("spjg","0");
                requestMainMap.put("fkxx",fkxx);
                requestMainMap.put("fzjgcwjl",fzjgcwjl);
                requestMainMap.put("lcbh",mark.toString());
                requestMainMap = removeNullValue(requestMainMap);
                log.info("预付款流程生成过滤后参数=="+ JSON.toJSONString(requestMainMap));
                //2.自动创建流程获取requestid
                int requestid_main_213 = Util.getIntValue(WorkflowCreateByRequestMap(ngr,workflowId,requestName,IsNextFlow,requestMainMap));
                log.info("预付款流程确认自动生成requestid=="+requestid_main_213);
                if (requestid_main_213 > 0) {
                    Integer form_id = null;
                    rsdetail.executeQuery("select id from "+tableName+" where requestid = ?",requestid_main_213);
                    if (rsdetail.next()){
                        form_id = Util.getIntValue(rsdetail.getString("id"));
                    }

                    //1.更新流程编号
                    log.info("requestid=="+requestid_main_213+"==lcbh:"+mark.toString());
                    rst.executeUpdate("update workflow_requestbase set requestmark = ? where requestid = ? ",mark.toString(),requestid_main_213);


                    //3.更新预付款流程的明细表（采用批量插入更新方法）只执行一次
                    String tableName_detail_eight = tableName + "_dt8";
                    String detail_eight_sql = "insert into "+tableName_detail_eight+" (mainid,bhsje,sj,jshjje,sy,fysjcdbm,sl,yskm,slz,htbh,cys,yskmid) " +
                            " select  "+form_id+",bhsje,sj,jshjje,sy,fysjcdbm,sl,yskm,slz,htbh,cys,'"+yskmPre+"_'||yskm from uf_yfkmiddle_dt8 where mainid = "+uf_id+"";
                    log.info("批量插入sql明细表8=="+detail_eight_sql);
                    rst.executeUpdate(detail_eight_sql);

                    String tableName_detail_nine = tableName + "_dt9";
                    String detail_nine_sql = "insert into "+tableName_detail_nine+" (mainid,rmbje,htbh,sy,bz,hl,wbje,yskm,fysjcdbm,cys,yskmid) " +
                            " select  "+form_id+",rmbje,htbh,sy,bz,hl,wbje,yskm,fysjcdbm,cys,'"+yskmPre+"_'||yskm from uf_yfkmiddle_dt9 where mainid = "+uf_id+"";
                    log.info("批量插入sql明细表9=="+detail_nine_sql);
                    rst.executeUpdate(detail_nine_sql);

                    String tableName_detail_eleven = tableName + "_dt11";
                    String detail_eleven_sql = "insert into "+tableName_detail_eleven+" (mainid,skdw,yxzh,khx,ss,yxzfje,xjzfje,dfkje,lsjl,khxmc) " +
                            " select  "+form_id+",skdw,yxzh,khx,ss,yxzfje,xjzfje,dfkje,lsjl,khxmc from uf_yfkmiddle_dt11 where mainid = "+uf_id+"";
                    log.info("批量插入sql明细表11=="+detail_eleven_sql);
                    rst.executeUpdate(detail_eleven_sql);

                    String tableName_detail_twelve = tableName + "_dt12";
                    String detail_twelve_sql = "insert into "+tableName_detail_twelve+" (mainid,fysjcdbm,je,sjbz,zhrmb,hjkm,hl,hjkmid,yskmmc,yskm) " +
                            " select "+form_id+",fysjcdbm,je,sjbz,zhrmb,hjkm,hl,'"+hjkmPre+"_'||hjkm,yskmmc,yskm from uf_yfkmiddle_dt12 where mainid = "+uf_id+"";
                    log.info("批量插入sql明细表12=="+detail_twelve_sql);
                    rst.executeUpdate(detail_twelve_sql);


                    //4.更新建模中间表表示该条数据已完成新建流程
                    rst.executeUpdate("update uf_yfkmiddle set sfcf = 0 where reqid = ?",requestid);
                    log.info("AdvancePaymentJob==预付款流程自动创建成功==");


                }
            }
            log.info("==建模中间表未存在需要自动触发的流程===");
            rst.commit();
        }catch (Exception e){
            rst.rollback();
            log.info("预付款流程自动创建失败");
            e.printStackTrace();
        }

    }

    /**
     * 移除map中的空值数据
     * @param map
     * @return
     */
    public static Map<String,String> removeNullValue(Map<String,String> map){
        Map<String,String> newMap = new HashMap<String,String>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if(value!=null && !"".equals(value)){
                newMap.put(key,value);
            }
        }
        return newMap;
    }


    /**
     *
     * @Title: 自动创建流程
     * @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 static String WorkflowCreateByRequestMap(String creatorId,String workflowId,
                                                    String requestName,String IsNextFlow,
                                                    Map<String,String> requestMainMap) {
        BaseBean bs = new BaseBean();
        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;
    }
}
