package weaver.interfaces.htsc.payment;

import com.engine.integration.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class SaveIntoSettlePaymentAction extends BaseBean implements Action{
    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = Util.null2String(requestInfo.getRequestid());//流程请求ID
        String lcbh ="";//业务流程编号
        RequestManager requestManager = requestInfo.getRequestManager();
        //获取主表名
        String tableName = requestManager.getBillTableName();
//        String tableNameT = JAVATools.getMaintable(requestid);
        //拼接获取明细表名
        String tableNameDt = tableName + "_dt11";

        JAVATools.SetCmdwritelog("写入资金系统表","主表为"+tableName);
        RecordSet rs = new RecordSet();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        try {
            String sqlMain = "select r.id ,r.requestid,r.lcbh,r.requestId,r.szbm,r.bz,r.ngrq,r.ngr ,d.DEPARTMENTNAME,d.DEPARTMENTCODE,s.LASTNAME,s.workcode " +
                    "from " + tableName +" r,hrmdepartment d,hrmresource s where r.szbm = d.id and s.id = r.ngr  and REQUESTID = "+requestid+"";
            rs.execute(sqlMain);
            JAVATools.SetCmdwritelog("查询" + tableName + "语句:" + sqlMain);
            if(rs.next()){
                Map<String,Object> map = new HashMap<>();
                String mainId = Util.null2String(rs.getString("id"));
                map.put("OAFKZJB_OAID", Util.null2String(rs.getString("lcbh")));
                lcbh = Util.null2String(rs.getString("lcbh"));
                map.put("OAFKZJB_OABH", WorkFlowNameConvertor.getEN_Lcbh(Util.null2String(rs.getString("lcbh"))));
                map.put("OAFKZJB_ZDDW", Util.null2String(rs.getString("DEPARTMENTCODE")));
                map.put("OAFKZJB_DWBH", Util.null2String(rs.getString("DEPARTMENTCODE")));
                map.put("OAFKZJB_FKBMMC",Util.null2String(rs.getString("DEPARTMENTNAME")));
                map.put("OAFKZJB_BZ",Util.null2String(rs.getString("bz")));
                String timeStr = Util.null2String(rs.getString("ngrq"));
                timeStr = timeStr + ":00";
                String[] timeStrs = timeStr.split(" ");
                String[] dataStrs = timeStrs[0].split("-");
                map.put("OAFKZJB_SQRQ",dataStrs[0]+dataStrs[1]+dataStrs[2]);
                map.put("OAFKZJB_SQSJ",timeStrs[1]);
                map.put("OAFKZJB_JSZT","0");
                //拟稿人
                map.put("OAFKZJB_SQR",Util.null2String(rs.getString("LASTNAME")));
                //拟稿人工号
                map.put("OAFKZJB_SQRGH",Util.null2String(rs.getString("workcode")));
                String date = sdf.format(new Date());
                String[] newDates = date.split(" ");
                map.put("OAFKZJB_BJRQ",newDates[0]);
                map.put("OAFKZJB_BJSJ",newDates[1]);
                innserttable(map,"OAFKZJB");
                String sqlDetail = "select d.skdw,d.yxzh,d.khx,d.ss,d.dfkje,d.yxzfje from "+tableNameDt+" d where mainid = "+mainId+" and d.yxzh is not null and d.yxzfje !=0 and d.yxzfje !=0.00";
                JAVATools.SetCmdwritelog("查询" + tableNameDt + "语句:" + sqlDetail);
                rs.execute(sqlDetail);
                List<List<Object>> insertList = new ArrayList<>();
                while (rs.next()){
                    List<Object> list = new ArrayList<>();
                    HashMap detailMap = new HashMap();
//                    detailMap.put("OAFKZJBMX_OABH",requestid);
                    list.add(WorkFlowNameConvertor.getEN_Lcbh(lcbh));
                    //对skdw 进行格式化处理去除<br>
                    String skdw = Util.null2String(rs.getString("skdw")).replace("<br>","");
                    skdw = skdw.replace("&nbsp;","");
//                    detailMap.put("OAFKZJBMX_DFDWMC",Util.null2String(rs.getString("skdw")));
                    list.add(skdw);
//                    detailMap.put("OAFKZJBMX_DFYHZH",Util.null2String(rs.getString("yxzh")));
                    String regEx="[^(0-9)]";
                    Pattern p = Pattern.compile(regEx);
                    Matcher m = p.matcher(Util.null2String(rs.getString("yxzh")));
                    list.add(m.replaceAll("").trim());
//                    detailMap.put("OAFKZJBMX_DFHM",Util.null2String(rs.getString("yxzh")));
                    list.add(skdw);
//                    detailMap.put("OAFKZJBMX_BXRGH","");
                    list.add("");
//                    detailMap.put("OAFKZJBMX_DFKHH",Util.null2String(rs.getString("khxmc")));
                    list.add(Util.null2String(rs.getString("khx")));
                    String area = Util.null2String(rs.getString("ss"));
                    List<String> areaArray = cityCodeToName(area);
                    if (null!=areaArray&&areaArray.size()>0){
//                        detailMap.put("OAFKZJBMX_DFSF",areaArray.get(0));
                        list.add(areaArray.get(0));
                        if (areaArray.size()>1){
//                            detailMap.put("OAFKZJBMX_DFCS",areaArray.get(1));
                            list.add(areaArray.get(1));
                        }else {
                            list.add("");
                        }
                    }else {
                        list.add("");
                        list.add("");
                    }
//                    detailMap.put("OAFKZJBMX_JE",Util.null2String(rs.getString("dfkje")));
                    list.add(Util.null2String(rs.getString("yxzfje")));
//                    detailMap.put("OAFKZJBMX_DJZT","0");
                    list.add("0");
//                    detailMap.put("OAFKZJBMX_JSZT","0");
                    list.add("0");
//                    innserttable(detailMap,"OAFKZJBMX");
                    list.add(Util.null2String(rs.getString("bz")));
                    insertList.add(list);
                }

                String sqlTable = "OAFKZJBMX_OABH,OAFKZJBMX_DFDWMC,OAFKZJBMX_DFYHZH,OAFKZJBMX_DFHM,OAFKZJBMX_BXRGH," +
                        "OAFKZJBMX_DFKHH,OAFKZJBMX_DFSF,OAFKZJBMX_DFCS,OAFKZJBMX_JE,OAFKZJBMX_DJZT,OAFKZJBMX_JSZT,OAFKZJBMX_YHBZ";
                String sqlTableE = "?,?,?,?,?,?,?,?,?,?,?,?";
                insertList(sqlTable,sqlTableE,insertList,"FinanceM","OAFKZJBMX");

            }

        } catch (Exception e) {
            e.printStackTrace();
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    //批量插入表单，切换数据源
    public boolean insertList(String sqlTableS,String sqlTableE,List<List<Object>> insertList,String sqlData,String tablename){
        boolean flag = true;
        try {
            RecordSet rs = new RecordSet();
            JAVATools.SetCmdwritelog("新表插入:", "表名" + tablename + "数据源为" + sqlData);
            JAVATools.SetCmdwritelog("sql:" + String.format("insert into %s (" + sqlTableS + ") values(" + sqlTableE + ") ", tablename));
            JAVATools.SetCmdwritelog("数据:" + insertList);
            //批量插入并切换数据源
            flag = rs.executeBatchSql(String.format("insert into %s (" + sqlTableS + ") values(" + sqlTableE + ") ", tablename), insertList, sqlData);
        }catch (Exception exo){
            flag=false;
            exo.printStackTrace();
            new BaseBean().writeLog("插入明细表失败:"+exo.getMessage());
        }
        return flag;
    }

    //插入表
    public static boolean innserttable(Map<String,Object> mapvalue, String tablename){
        boolean flag=true;
        String dttablename="";
        String dttablenvalue="";
        List<String> list=new ArrayList<>();
        JAVATools.SetCmdwritelog("新表插入:","表名"+tablename);
        for (Map.Entry<String, Object> entry : mapvalue.entrySet())
        {
            String fieldname = Util.null2String(entry.getKey());
            String fieldvalue = Util.null2String(entry.getValue());
            JAVATools.SetCmdwritelog(" key: "+fieldname+" value:"+fieldvalue);
            dttablename += dttablename == "" ? fieldname : "," + fieldname;
            //dttablenvalue += dttablenvalue == "" ? "'" + fieldvalue + "'" : ",'" + fieldvalue + "'";
            //dttablenvalue += dttablenvalue == "" ? "?" : ",?";
//            list.add(Lengthmax(fieldvalue.replace("\r\n",""),150));
            dttablenvalue += dttablenvalue == "" ? "'"+Lengthmax(fieldvalue.replace("\r\n",""),150)+"'" : ",'"+Lengthmax(fieldvalue.replace("\r\n",""),150)+"'";
        }
        String sql = "insert into "+tablename+"("+dttablename+") values("+dttablenvalue+")";
        JAVATools.SetCmdwritelog(" sql: "+sql);
        JAVATools.SetCmdwritelog(" sql: "+list.toString());
        try {
            RecordSetDataSource rsdM = new RecordSetDataSource("FinanceM");
            flag = rsdM.execute(sql);
//            rsdM.executeQueryWithDatasource(sql,null,new Object[]{list});
        }catch (Exception exo){
            flag=false;
            exo.printStackTrace();
            new BaseBean().writeLog("插入明细表失败:"+exo.getMessage());
        }
        return flag;
    }

    public static String Lengthmax(String value,Integer sum){
        if("".equals(value)) return "";
        if(value.length()>sum){
            value=value.substring(0,sum-1);
        }
        return  value;
    }

    public static List<String> cityCodeToName(String code){
        RecordSet rs = new RecordSet();
        List<String> resultList = new ArrayList<>();
        if (StringUtils.isBlank(code)){
            return resultList;
        }
        String[] desInfo = code.split(",");
        String ids = Arrays.stream(desInfo).map(s -> "\'" + s +"\'").collect(Collectors.joining(","));
        String sql = "select name from uf_city where code in (" + ids + ") order by instr('" + code + "',code)";
        rs.executeQuery(sql);
        while (rs.next()){
            resultList.add(rs.getString("name"));
        }
        return resultList;
    }

}
