package weaver.interfaces.htxc.tycgrwd.action;

import org.joda.time.DateTime;
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.*;

/**
 *采购任务单数据写入老oa的T_PURCHASE_PUBLICITY表
 */
public class SavePurchasePublicityAction extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = Util.null2String(requestInfo.getRequestid());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RequestManager requestManager = requestInfo.getRequestManager();
        //获取主表名
        String tableName = requestManager.getBillTableName();
        //拼接获取明细表名
        String tableNameDt5 = tableName+ "_dt5";
        RecordSet rs = new RecordSet();
        try {
            String lastname = "";
            String lxfs = "";
            String xmmczw = "";
            String lcbh = "";
            String sjhxsyjm = "";
//            String a = DateUtil.getNowDateTimeStr();
            Date a = new Date();
            JAVATools.SetCmdwritelog("当前时间--------"+a);
            String startTime = sdf.format(a);
            DateTime dateTime = new DateTime();
            DateTime dateTime1  =dateTime.plusDays(10); //10天后
            String endTime = dateTime1.toString("yyyy-MM-dd HH:mm:ss");

            //查询主表
            String sqlMain = "select t1.lastname,t2.lxfs,t2.xmmczw,t2.lcbh,t2.sjhxsyjm from hrmresource t1, " + tableName + " t2 where t1.id = t2.ngr and t2.requestid= " + requestid;
            rs.execute(sqlMain);
            JAVATools.SetCmdwritelog("查询" + tableName + "语句:" + sqlMain);
            JAVATools.SetCmdwritelog("查询结果" + rs.toString());

            if(rs.next()){
                lastname = Util.null2String(rs.getString("lastname"));
                lxfs = Util.null2String(rs.getString("lxfs"));
                xmmczw = Util.null2String(rs.getString("xmmczw"));
                lcbh = Util.null2String(rs.getString("lcbh"));
                sjhxsyjm = Util.null2String(rs.getString("sjhxsyjm"));
            }

            //查出该环境cgfs为单一来源的value
            String selectCGFS = findSelectCGFS(tableNameDt5);
            //查出该环境sjhxsyjm为否的value
            String selectsjhxsyjm = findSelectSJHXSYJM(tableName);

            boolean flag = false;
            if(selectsjhxsyjm!=null&&!"".equals(selectsjhxsyjm)&&sjhxsyjm!=null&&!"".equals(sjhxsyjm)){
                if(sjhxsyjm.equals(selectsjhxsyjm)){
                    flag = true;
                }

            }
            //查询明细表
            String sqlDetail = "select t1.cgdbh,t1.cgnr,t1.ysje,t1.gys,t1.cgsqgssm,t1.cgfs from " + tableNameDt5 + " t1, " + tableName + " t2 where t1.mainid = t2.id and t2.requestid= " + requestid;
            rs.execute(sqlDetail);
            while(rs.next()){
                if(selectCGFS!=null && !"".equals(selectCGFS)){
                    if(flag && Double.parseDouble(Util.null2String(rs.getString("ysje")))>=500000 && selectCGFS.equals(Util.null2String(rs.getString("cgfs")))){
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("workFlowNumPub",lcbh);
                        map.put("purchaseNumPub", Util.null2String(rs.getString("cgdbh")));
                        map.put("projectNamePub",xmmczw);
                        map.put("purchaseContentPub", Util.null2String(rs.getString("cgnr")));
                        map.put("budgetPub", Util.null2String(rs.getString("ysje")));
                        map.put("supplierPub", Util.null2String(rs.getString("gys")));
                        map.put("beforehandPublicityPub", Util.null2String(rs.getString("cgsqgssm")));
                        map.put("startTimePub",startTime);
                        map.put("endTimePub",endTime);
                        map.put("drafterNamePub",lastname);
                        map.put("drafterTelPub",lxfs);
                        String purchaseNumPub = Util.null2String(rs.getString("cgdbh"));
                        innserttable(map,"T_PURCHASE_PUBLICITY",purchaseNumPub);
                    }
                }else {
                    return "workflow_selectitem表中未查询到与" + tableNameDt5 +"匹配的采购方式";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return  Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    //插入表
    public static boolean innserttable(Map<String,Object> mapvalue, String tablename, String purchaseNumPub){
        boolean exist = false;//查询是否已经插入老oa表
        boolean flag  = false;
        String sql1 = "select workFlowNumPub from " + tablename + " where purchaseNumPub = '" + purchaseNumPub + "'";
        try {
            RecordSetDataSource rsdM = new RecordSetDataSource("FinanceM");
            rsdM.execute(sql1);
            if (rsdM.next()){
                exist = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if (exist == false){ //未插入的采购明细才执行插入
            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;
            }
            //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;
    }

    public String findSelectCGFS(String tableNameDt5) {
        RecordSet rs = new RecordSet();
        String selectvalue = "";
        try {
            String sql = "select t1.selectvalue from workflow_selectitem t1,workflow_billfield t2 where t2.detailtable='" + tableNameDt5 + "' and t2.fieldname='cgfs' and t2.id=t1.fieldid and t1.selectname='单一来源' ";
            rs.execute(sql);
            JAVATools.SetCmdwritelog("findSelectCGFS------------"+sql);
            if(rs.next()){
                selectvalue = Util.null2String(rs.getString("selectvalue"));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return selectvalue;
    }

    public String findSelectSJHXSYJM(String tableName) {
        RecordSet rs = new RecordSet();
        String selectvalue = "";
        try {
            String sql = "select t1.selectvalue from workflow_selectitem t1,workflow_billfield t2,workflow_bill t3 where t2.billid=t3.id and t2.fieldname='sjhxsyjm' and t1.selectname='否' and t1.fieldid=t2.id and t3.tablename='" + tableName + "'";
            rs.execute(sql);
            if(rs.next()){
                selectvalue = Util.null2String(rs.getString("selectvalue"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return selectvalue;
    }
}
