package weaver.interfaces.htsc.itlxlc.action;

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.htsc.comInfo.PropBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * it立项和it采购数据写入老oa的PurchaseImplements表
 */
public class SavePurchaseImplementsForCtrtAction extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = Util.null2String(requestInfo.getRequestid());
        //因为采购和立项都调用这个action，所以查询unnmber用来区分
        String unnumber = getUnNumber(requestid);
        //如果是IT采购流程，必须获取一下parentCode

        PropBean pr = new PropBean();
        //跳转用的url
        String url =pr.getPropName("OAHOST") + "spa/workflow/static4form/index.html?#/main/workflow/req?requestid="+requestid;
        JAVATools.SetCmdwritelog("-------跳转用的url-------"+ url);

        RequestManager requestManager = requestInfo.getRequestManager();
        //获取主表名
        String tableName = requestManager.getBillTableName();
        JAVATools.SetCmdwritelog("-------IT采购申请的表名-------"+ url);
        String parentCode = "";
        if("itcgsq".equals(unnumber)){
            parentCode = getParentCodeForITCG(tableName,requestid);
        }

        RecordSet rs = new RecordSet();
        try {
            String sqlMain = "select r.id,r.requestid,r.lcbh,r.lcbt " + "from " + tableName + " r where r.requestid = " + requestid;
            rs.execute(sqlMain);
            JAVATools.SetCmdwritelog("查询" + tableName + "语句:" + sqlMain);
            JAVATools.SetCmdwritelog("查询结果" + rs.toString());
            if(rs.next()){
                if("itlxsq".equals(unnumber)){ //IT立项申请
                    Map<String,Object> map = new HashMap<>();
                    map.put("workFlowName","HTITProjectApply");
                    map.put("workFlowNum",Util.null2String(rs.getString("lcbh")));
                    map.put("workFlowNumber",Util.null2String(rs.getString("requestid")));
                    map.put("levelType","1");
                    map.put("parentCode","");
                    map.put("workFlowTitle",Util.null2String(rs.getString("lcbt")));
                    map.put("status","0");
                    map.put("url",url);
                    innserttable(map,"T_PURCHASE_IMPLEMENTS");
                }else if("itcgsq".equals(unnumber)){ //IT采购申请
                    Map<String,Object> map = new HashMap<>();
                    map.put("workFlowName","Purchase");
                    map.put("workFlowNum",Util.null2String(rs.getString("lcbh")));
                    map.put("workFlowNumber",Util.null2String(rs.getString("requestid")));
                    map.put("levelType","2");
                    map.put("parentCode",parentCode);
                    map.put("workFlowTitle",Util.null2String(rs.getString("lcbt")));
                    map.put("status","0");
                    map.put("url",url);
                    innserttable(map,"T_PURCHASE_IMPLEMENTS");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    //插入表
    public static boolean innserttable(Map<String,Object> mapvalue, String tablename){
        String sqlMaxid = "select max(id) as id from " + tablename;
        String id = "";
        try {
            RecordSetDataSource rsdM = new RecordSetDataSource("FinanceM");
            rsdM.execute(sqlMaxid);
            if(rsdM.next()){
                id =Util.null2String(rsdM.getString("id"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        int idi = -1;
        if(id!=""){
            idi = Integer.parseInt(id) + 1;
        }

        boolean flag=true;
        //1
        String dttablename="";
        //2
        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 == "" ? "'"+Lengthmax(fieldvalue.replace("\r\n",""),150)+"'" : ",'"+Lengthmax(fieldvalue.replace("\r\n",""),150)+"'";
        }

        String sql = "insert into "+tablename+"(id,"+dttablename+") values("+idi+","+dttablenvalue+")";
        JAVATools.SetCmdwritelog(" sql: "+sql);
        try {
            RecordSetDataSource rsdM = new RecordSetDataSource("FinanceM");
            flag = rsdM.execute(sql);
        }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;
    }



    // 通过requestid辨别来自立项还是采购
    public String getUnNumber(String requestid){
        RecordSet rs = new RecordSet();
        String unnumber = "";
        try {
            String sql = "select t1.unnumber from workflow_base t1 ,workflow_requestbase t2 where  t1.id = t2.workflowid and t2.requestid = " + requestid;
            rs.execute(sql);
            JAVATools.SetCmdwritelog("--------查询unnumber的sql=" + sql);
            JAVATools.SetCmdwritelog("--------查询unnumber的结果=" + rs.toString());
            if(rs.next()){
                unnumber = Util.null2String(rs.getString("unnumber"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return unnumber;
    }


    // 为it采购流程获取回传给老oa的parentCode
    public String  getParentCodeForITCG(String tablename,String requestid){
        RecordSet rs = new RecordSet();
        //IT采购申请的ltlxsq字段
        String itlxsq = "";
        //IT立项申请的编号（老oa的是workflownumber,新oa的是requestid）
        String parentCode = "";
        try {
            String sql = "select r.itlxsq " + "from " + tablename + " r where r.requestid = " + requestid;
            JAVATools.SetCmdwritelog("--------查询itlxsq的sql=" + sql);
            rs.execute(sql);
            JAVATools.SetCmdwritelog("--------查询itlxsq的结果=" + rs.toString());
            if(rs.next()){
                itlxsq = Util.null2String(rs.getString("itlxsq"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //处理itlxsq取出parentCode
        if("".equals(itlxsq) || null == itlxsq){
            JAVATools.SetCmdwritelog("--------ecology数据库中itlxsq的数据为空");
        }else {
            boolean status1 = itlxsq.contains("workFlowName=");
            boolean status2 = itlxsq.contains("requestid=");
            if(status1){
                String str1=itlxsq.substring(0, itlxsq.indexOf("workFlowNumber="));
                String str2=itlxsq.substring(str1.length()+15, itlxsq.length());
                parentCode=str2.substring(0,str2.indexOf("&"));
                JAVATools.SetCmdwritelog("--------老oa发起IT立项：来自老oa的workflownumber--------" + parentCode);
            }else if(status2){
                String str1=itlxsq.substring(0, itlxsq.indexOf("requestid="));
                String str2=itlxsq.substring(str1.length()+10, itlxsq.length());
                if(str2.contains("&")){
                    parentCode=str2.substring(0,str2.indexOf("&"));
                }else{
                    parentCode=str2.substring(0,str2.indexOf("\""));
                }
                JAVATools.SetCmdwritelog("--------新oa发起IT立项：来自新oa的requestid--------" + parentCode);
            }else{
                JAVATools.SetCmdwritelog("--------itlxsq中未找到来自老oa的workflownumber或来自新oa的requestid");
            }
        }
        return parentCode;

    }
}
