package weaver.interfaces.htsc.yfkqrlc;

import com.alibaba.fastjson.JSON;
import com.engine.htsc.payment.enums.Sequences;
import com.engine.htsc.payment.util.CoWfUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


public class CreatewfAction extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        writeLog("================== check in ===================");
        String back = FAILURE_AND_CONTINUE;
        BaseBean bb = new BaseBean();
        PropBean pp = new PropBean();
        RecordSet rs = new RecordSet();
        RecordSet rsdetail = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();
        try {
            String requestid = requestInfo.getRequestid();
            String tsywMainTableName = getMainTableName(requestid);
            Map<String, Object> mainData = mainData(requestInfo);
            if ("0".equals(Util.null2String(mainData.get("sfxfkhtgfp")))) {
                String ngr = Util.null2String(mainData.get("ngr"));
                boolean isHeader = isHeader(ngr);
                String workflowId = pp.getPropName("YFKQR_WORKFLOWID");
                String treeId = pp.getPropName("YFKFYQRaccountTreeId");
                writeLog("================获取的预算科目前缀============"+treeId);
                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;
                    writeLog("预付款流程表名==" + tableName);
                } else {
                    writeLog("获取预付款流程表名失败==");
                    back = FAILURE_AND_CONTINUE;
                }
                String IsNextFlow = "1"; //1提交到下一节点，0不提交
                String mark = CoWfUtil.getRequestMarkByUnNumber("zbyfkfyqr", Sequences.NET_REI_WORKFLOW_SEQ_ZB);
                String lcbh = Util.null2String(mainData.get("lcbh"));
                String requestName = lcbh + "的预付款费用确认";
                String skdw = getSkdw(requestid);
                String bz = "收款方： " + skdw;
                writeLog("预付款流程确认标题==" + requestName);
                String ngsj = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                writeLog("获取的当前时间是：" + ngsj);
                Map<String, String> requestMainMap = new HashMap<String, String>();
                requestMainMap.put("ngr", ngr);
                requestMainMap.put("glyfklc", requestid);
                requestMainMap.put("szbm", Util.null2String(mainData.get("szbm")));
                requestMainMap.put("jjcd", Util.null2String(mainData.get("jjcd")));
                requestMainMap.put("jjyy", Util.null2String(mainData.get("jjyy")));
                requestMainMap.put("lxfs", Util.null2String(mainData.get("lxfs")));
                requestMainMap.put("ngsj", ngsj);
                requestMainMap.put("xjhjmx", Util.null2String(mainData.get("xjhjmx")));
//                requestMainMap.put("ngrfyhj", Util.null2String(mainData.get("ngbmfyhj")));//总部给这个字段
                if (isHeader){
                    requestMainMap.put("fyhjsp", Util.null2String(mainData.get("fyhj")));//总部给这个字段
                }else {
                    requestMainMap.put("fyhjsp", Util.null2String(mainData.get("cwzxhj")));//分支  fyhjsp-----cwzxhj
                }
                requestMainMap.put("ggfyqtfy", "1");
                requestMainMap.put("bz", bz);
                requestMainMap.put("spjg", "0");
                requestMainMap.put("fkxx", Util.null2String(mainData.get("fkxx")));
                //预付款流程的分支机构财务经理对应托收业务的什么字段
                if (!isHeader){
                    //分支机构才赋值
                    requestMainMap.put("fzjgcwjl", Util.null2String(mainData.get("cwzxjl")));
                }
                requestMainMap.put("lcbh", mark.toString());
                requestMainMap = removeNullValue(requestMainMap);
                writeLog("预付款流程生成过滤后参数==" + JSON.toJSONString(requestMainMap));
                //2.自动创建流程获取requestid
                int requestid_main_213 = Util.getIntValue(WorkflowCreateByRequestMap(ngr, workflowId, requestName, IsNextFlow, requestMainMap));
                writeLog("预付款流程确认自动生成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.更新流程编号
                    writeLog("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,cys,yskmid) " +
                            " select " + form_id + ",bhsje,sj,jshjje,sy,fysjcdbm,sl,yskm,slz,cys,concat('"+treeId+"_',yskm) as yskmid from " + tsywMainTableName + "_dt8 where mainid = (select id from " + tsywMainTableName + " where requestid = '" + requestid + "')";
                    writeLog("即将执行明细表8更新语句");
                    writeLog("其中数据select语句是：" + "select " + form_id + ",bhsje,sj,jshjje,sy,fysjcdbm,sl,yskm,slz,cys,concat('"+treeId+"_',yskm) as yskmid from " + tsywMainTableName + "_dt8 where mainid = (select id from " + tsywMainTableName + " where requestid = '" + requestid + "')");
                    writeLog("整体更新明细表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,sy,bz,hl,wbje,yskm,fysjcdbm,cys,yskmid) " +
                            " select " + form_id + ",rmbje,sy,bz,hl,wbje,yskm,fysjcdbm,cys,concat('"+treeId+"_',yskm) as yskmid from " + tsywMainTableName + "_dt9 where mainid = (select id from " + tsywMainTableName + " where requestid = '" + requestid + "')";
                    writeLog("批量插入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 " + tsywMainTableName + "_dt11 where mainid = (select id from " + tsywMainTableName + " where requestid = '" + requestid + "')";
                    writeLog("批量插入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,hjkmid,yskmmc,yskm from " + tsywMainTableName + "_dt12 where mainid = (select id from " + tsywMainTableName + " where requestid = '" + requestid + "')";
                    writeLog("批量插入sql明细表12==" + detail_twelve_sql);
                    rst.executeUpdate(detail_twelve_sql);

                    //4.更新建模中间表表示该条数据已完成新建流程
                    rst.executeUpdate("update " + tsywMainTableName + " set sfcfyfklc = 1 where requestid = ?", requestid);
                    writeLog("托收业务sfcfyfklc字段更新成功==");

                }
                writeLog("==CreatewfAction==预付款流程自动创建成功=====");
                rst.commit();
                back = SUCCESS;
            } else {
                writeLog("不要触发与付款流程");
                back = SUCCESS;
            }

        } catch (Exception e) {
            back = FAILURE_AND_CONTINUE;
            rst.rollback();
            requestInfo.getRequestManager().setMessagecontent("流程流转异常：预付款流程自动创建失败");
            writeLog("预付款流程自动创建失败");
            e.printStackTrace();
        }
        return back;
    }


    /*
     * 获取主表数据
     * */
    private static Map<String, Object> mainData(RequestInfo requestInfo) {
        Map<String, Object> mainTableDataMap = new HashMap();
        Property[] property = requestInfo.getMainTableInfo().getProperty();
        for (int i = 0; i < property.length; i++) {
            mainTableDataMap.put(property[i].getName().toLowerCase(), Util.null2String(property[i].getValue()));
        }
        return mainTableDataMap;
    }

    /*
     * 获取收款单位
     * */
    private String getSkdw(String requestId) {
        String skdw = "";
        String tsywTableName = "";
        BaseBean bb = new BaseBean();
        writeLog("进入收款单位获取方法");
        RecordSet rs = new RecordSet();
        String sql = "";
        sql = "select tablename from workflow_base a,workflow_bill b,workflow_requestbase c where a.formid=b.id and a.id=c.workflowid and c.requestid='" + requestId + "'";
        writeLog("即将执行获取托收业务主表名的sql:" + sql);
        rs.executeQuery(sql);
        if (rs.next()) {
            tsywTableName = rs.getString("tablename");
        }
        writeLog("获取的托收业务主表名是：" + tsywTableName);
        sql = "select wm_concat_old(skdw) as skdw from " + tsywTableName + "_dt11 where mainid = (select id from " + tsywTableName + " where requestid = '" + requestId + "')";
        writeLog("即将执行获取收款单位的sql是：" + sql);
        rs.executeQuery(sql);
        if (rs.next()) {
            skdw = rs.getString("skdw");
        }
        writeLog("返回的收款单位是：" + skdw);
        return skdw;
    }

    /**
     * @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
     * @Title: 自动创建流程
     */
    public static String WorkflowCreateByRequestMap(String creatorId, String workflowId,
                                                    String requestName, String IsNextFlow,
                                                    Map<String, String> requestMainMap) {
        com.weaver.general.BaseBean bs = new com.weaver.general.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());
            bs.writeLog("" + sbf.toString());
        } catch (Exception e) {
            bs.writeLog("错误：" + e);
            bs.writeLog("错误：" + e);
        }
        return requestid;
    }

    /**
     * 移除map中的空值数据
     *
     * @param map
     * @return
     */
    private 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;
    }

    /*
     * 根据requestid获取对应的主表名
     * */
    private String getMainTableName(String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select tablename from workflow_base a,workflow_bill b,workflow_requestbase c where a.formid=b.id and a.id=c.workflowid and c.requestid='" + requestid + "'");
        if (rs.next()) {
            return rs.getString("tablename");
        } else {
            return "";
        }
    }

    /*
    * 根据人员ID判断所在机构是否是总部
    * */
    public boolean isHeader(String id){
        boolean back ;
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        String sql = "select depttypecode from hrmdepartmentdefined where DEPTID = (select DEPARTMENTID from hrmresource where id = '"+id+"')";
        rs.executeQuery(sql);
        if (rs.next()){
            back = "JGLX01".equals(Util.null2String(rs.getString("depttypecode")));
        }else {
            back = false;
        }
        return back;
    }
}
