package weaver.interfaces.htxc.tycgrwd.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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购任务单数据写入老oa的PurchaseImplements表
 */
public class SavePurchaseImplementsForCtrtAction2 extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = Util.null2String(requestInfo.getRequestid());
        RequestManager requestManager = requestInfo.getRequestManager();
        PropBean pr = new PropBean();
        //跳转用的url
        String url =pr.getPropName("OAHOST") + "spa/workflow/static4form/index.html?#/main/workflow/req?requestid="+requestid;
        JAVATools.SetCmdwritelog("-------跳转用的url-------"+ url);
        //获取主表名
        String tableName = requestManager.getBillTableName();
        JAVATools.SetCmdwritelog("采购任务单信息写入老oa系统表","主表为"+tableName);
        //获取父流程requestid
        String parentCode = getParentCode(tableName,requestid);
        //拼接获取明细表名
        String tableNameDt5 = tableName+ "_dt5";


        RecordSet rs = new RecordSet();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        try {
            String sqlMain = "select r.id,r.requestid,r.lcbh " + "from " + tableName + " r where r.requestid = " + requestid;
            rs.execute(sqlMain);
            JAVATools.SetCmdwritelog("查询" + tableName + "语句:" + sqlMain);
            JAVATools.SetCmdwritelog("查询结果" + rs.toString());

            String workFlowNum = "";
            String workFlowNumber = "";
            if(rs.next()){
                workFlowNum = Util.null2String(rs.getString("lcbh"));
                workFlowNumber = Util.null2String(rs.getString("requestid"));
            }

            //获取流程标题
            String sqlTitle = "select r.requestname from workflow_requestbase r where r.requestid= " + requestid;
            rs.execute(sqlTitle);
            String workFlowTitle = "";
            if(rs.next()){
                workFlowTitle = Util.null2String(rs.getString("requestname"));
            }
            //获取明细表数据
            String sqlDetail = "select t1.cgdbh as cgdbh,t1.appid as appid,t1.workFlowContents as workFlowContents from " + tableNameDt5 + " t1, " + tableName + " t2 where t2.id = t1.mainid and t2.requestid= " + requestid ;
            rs.execute(sqlDetail);
            String cgdbh = "";
            while (rs.next()){
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("workFlowName","PurchaseImplement");
                map.put("workFlowNum",workFlowNum);
                map.put("workFlowNumber",workFlowNumber);
                map.put("levelType","3");
                map.put("parentCode",parentCode);
                map.put("workFlowTitle",workFlowTitle);
                map.put("status","0");
                map.put("url",url);
                map.put("purchaseNum", Util.null2String(rs.getString("cgdbh")));
                map.put("purchaseAppId", Util.null2String(rs.getString("appid")));
                map.put("workFlowContents", Util.null2String(rs.getString("workFlowContents")));
                innserttable(map,"T_PURCHASE_IMPLEMENTS");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Action.FAILURE_AND_CONTINUE;
        }
        return  Action.SUCCESS;
    }

    // 从采购任务单获取回传给老oa的parentCode
    public String  getParentCode(String tablename,String requestid){
        String parentCode = "";
        RecordSet rs = new RecordSet();
        String itcglc = "";
        try {
            String sql = "select r.itcglc " + "from " + tablename + " r where r.requestid = " + requestid;
            JAVATools.SetCmdwritelog("--------查询itlxsq和itcglc的sql=" + sql);
            rs.execute(sql);
            if(rs.next()){
                itcglc = Util.null2String(rs.getString("itcglc"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if("".equals(itcglc) || null == itcglc){
            JAVATools.SetCmdwritelog("--------ecology数据库中itcglc的数据为空");
        }else {
            boolean status = itcglc.contains("requestid=");
            if(status){
                String str1=itcglc.substring(0, itcglc.indexOf("requestid="));
                String str2=itcglc.substring(str1.length()+10, itcglc.length());
                if(str2.contains("&")){
                    parentCode=str2.substring(0,str2.indexOf("&"));
                }else{
                    parentCode=str2.substring(0,str2.indexOf("\""));
                }
            }
        }
        return parentCode;
    }

    //插入表
    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)+"'";
            dttablenvalue += dttablenvalue == "" ? "'"+ fieldvalue +"'" : ",'" + fieldvalue +"'";
        }
        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;
    }
}
