package com.engine.htsc.lhclbx.dao;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.integration.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.payment.WorkFlowNameConvertor;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

public class LhclDataRecoverCMD extends AbstractCommonCommand<Map<String, Object>> {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    @Override
    public BizLogContext getLogContext() {
        return null;
    }


    public LhclDataRecoverCMD(User user, Map<String, Object> params) {
        this.user = user;
        this.params = params;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> back = new HashMap<>();
        List<Map<String,String>> mapList = new ArrayList<>();
        Map<String,String> res = new HashMap<>();
        BaseBean bb = new BaseBean();
        String lclx = "fzjgclbx";
        String tablename =  getTableName(lclx);
        if ("".equals(tablename)){
            return back;
        }
        bb.writeLog("=======================YdbxModeDataCMD============================");
        String requestids = Util.null2String(params.get("requestids"));
        String[] requestarr = requestids.split(",");
        for (int i = 0; i < requestarr.length; i++) {
            //判断是否全自付
            if(isFZF(requestarr[i], tablename)) {
                writeLog("requestId:" + requestarr[i] + " 全是非自付费用 不写资金表");
                continue;
            }
            writeLog("requestId:" + requestarr[i] + " 开始写入资金系统表,差旅报销名:" + tablename);
            Map<String, Object> map = getOAMainData(requestarr[i], tablename);
            RecordSetDataSource rsdM = new RecordSetDataSource("FinanceM");
            String str = "select * from OAFKZJB t where t.OAFKZJB_OAID = '" + map.get("OAFKZJB_OAID") + "'";
            rsdM.execute(str);
            if(rsdM.next()){
                continue;
            }
            String result = innserttable(map, "OAFKZJB");
            writeLog("requestId:" + requestarr[i] + " 写入资金中间表主表完成");
            if(!StringUtils.isBlank(result)){
                res.put(requestarr[i] ,result);
            }
            mapList.add(res);
        }
        back.put("result",mapList);
        return back;
    }

    /**
     * 获取表名
     * @param lclx
     * @return
     */
    public static String getTableName(String lclx){
        RecordSet rs = new RecordSet();
        String sql = "select t2.tablename from workflow_base t1,workflow_bill t2 where t1.formid = t2.id and  t1.UNNUMBER = ? and ISVALID = '1'";
        rs.executeQuery(sql,lclx);
        if(rs.next()){
            return Util.null2String(rs.getString("tablename"));
        }else {
            return "";
        }
    }

    /**
     * 获取资金表主表数据
     * @param requestId
     * @param mainTableName
     * @return
     */
    Map<String,Object> getOAMainData(String requestId, String mainTableName) {
        RecordSet rs = new RecordSet();
        Map<String,Object> map = new HashMap<>();
        String sqlMain ="";
        sqlMain = " select r.id ,r.requestid,r.lcbh,r.requestId,r.szbm,r.bz,r.ngsj,r.ngr ,d.DEPARTMENTNAME,d.DEPARTMENTCODE,s.LASTNAME,s.workcode " +
                    " from "+mainTableName+" r,hrmdepartment d,hrmresource s where r.szbm = d.id and s.id = r.ngr  and REQUESTID = '"+requestId+"'";
        writeLog("requestId:"+requestId+" 关联查询查询主表sql:"+sqlMain);
        rs.execute(sqlMain);
        if(rs.next()){
            String mainId = Util.null2String(rs.getString("id"));
            map.put("OAFKZJB_OAID", 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("ngsj"));
            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]);
        }
        return map;
    }


    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 String innserttable(Map<String,Object> mapvalue, String tablename){
        boolean flag=true;
        String result = "";
        try {
        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 == "" ? "'"+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());

            RecordSetDataSource rsdM = new RecordSetDataSource("FinanceM");
            flag = rsdM.execute(sql);
//            rsdM.executeQueryWithDatasource(sql,null,new Object[]{list});
        }catch (Exception exo){
            flag=false;
            exo.printStackTrace();
            result = exo.getMessage();
            new BaseBean().writeLog("插入明细表失败:"+exo.getMessage());
        }
        return result;
    }


    /**
     * 判断是否全自付
     * @param requestId
     * @param mainTableName
     * @return
     */
    public boolean isFZF (String requestId, String mainTableName) {
        RecordSet rs = new RecordSet();
        String querySql = " select t.xj from "+mainTableName+"_dt12 t where t.mainid in ( select id from "+mainTableName+"  t where t.requestid = '"+requestId+"' )";
        rs.writeLog("requestId:"+requestId+" 查询是否为全部非自付SQL:"+querySql);
        BigDecimal totalZFB = new BigDecimal("0.00");
        rs.executeQuery(querySql);
        while(rs.next()) {
            BigDecimal tempB = (new BigDecimal(StringUtils.isEmpty(rs.getString("xj")) ? 0.00 :Double.parseDouble(rs.getString("xj")))).setScale(2, BigDecimal.ROUND_HALF_UP);
            rs.writeLog("requestId:"+requestId+" 查询是否为全部非自付小计金额tempB:"+tempB);
            totalZFB = (totalZFB.add(tempB).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        rs.writeLog("requestId:"+requestId+" 自付费用汇总金额 totalZFB:"+totalZFB);
        if(totalZFB.compareTo(BigDecimal.ZERO)==0) {
            return true;//没有自付费用
        }
        return false;
    }
}
