package weaver.interfaces.htsc.payment;

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

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 差旅报销保存资金中间表
 * TODO 去掉集成把保存逻辑拆出来
 * Created on 2021/5/6.
 */
public class SaveIntoTravelAction extends SaveIntoFinanceAction implements Action {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");

    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            String requestId = Util.null2String(requestInfo.getRequestid());
            RequestManager requestManager = requestInfo.getRequestManager();
            //获取主表名
            String mainTableName = requestManager.getBillTableName();
            //拼接获取明细表名
            String detailTableName = mainTableName + "_dt10";

            if(isFZF(requestId, mainTableName)) {
                writeLog("requestId:" + requestId + " 全是非自付费用 不写资金表");
                return Action.SUCCESS;
            }

            writeLog("requestId:" + requestId + " 开始写入资金系统表,差旅报销名:" + mainTableName);
            Map<String, Object> map = getOAMainData(requestId, mainTableName);

            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()){
                return Action.SUCCESS;
            }

            innserttable(map, "OAFKZJB");
            writeLog("requestId:" + requestId + " 写入资金中间表主表完成");

            List<List<Object>> insertList = getOADetailData(requestId, mainTableName, detailTableName);
            String sqlTable = "OAFKZJBMX_OABH,OAFKZJBMX_DFDWMC,OAFKZJBMX_DFYHZH,OAFKZJBMX_DFHM,OAFKZJBMX_BXRGH," +
                    "OAFKZJBMX_DFKHH,OAFKZJBMX_DFSF,OAFKZJBMX_DFCS,OAFKZJBMX_JE,OAFKZJBMX_JSZT";
            String sqlTableE = "?,?,?,?,?,?,?,?,?,?";
            insertList(sqlTable, sqlTableE, insertList, "FinanceM", "OAFKZJBMX");
            writeLog("requestId:" + requestId + " 写入资金中间表明细表完成");
        }catch(Exception e) {
            e.printStackTrace();
            writeLog(e);
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    /**
     * 获取资金表主表数据
     * @param requestId
     * @param mainTableName
     * @return
     */
    Map<String,Object> getOAMainData(String requestId, String mainTableName) {
        RecordSet rs = new RecordSet();
        Map<String,Object> map = new HashMap<>();
        String lclx = "";
        String sqlMain ="";
        String sqlLclx = "select b.unnumber as lclx from workflow_requestbase a join workflow_base b on a.WORKFLOWID = b.id where a.REQUESTID = ?";
        rs.executeQuery(sqlLclx,requestId);
        if (rs.next()){
             lclx = Util.null2String(rs.getString("lclx"));
        }
        if("".equals(lclx)){
            return map;
        }
        if(!"clbx".equals(lclx)){
            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+"'";
        }else {
            sqlMain = " select r.id ,r.requestid,r.lcbh,r.requestId,r.szbm,r.bz,r.ngrq as 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;
    }

    /**
     * 获取资金表明细表数据
     * @param requestId
     * @param mainTableName
     * @param dtTableName
     * @return
     */
    List<List<Object>> getOADetailData(String requestId, String mainTableName, String dtTableName) {
        RecordSet rs = new RecordSet();
        List<List<Object>> insertList = new ArrayList<>();
        String sqlDetail = "  select t0.requestid,t1.lastname,d.yxzh,t1.lastname,d.khxmc,d.ss,t1.workcode, d.yxzfje,d.xjzfje,t0.lcbh " +
                           "  from "+dtTableName + " d,"+ mainTableName +" t0,hrmresource t1 where t0.id = d.mainid and d.bxr = t1.id and t0.requestid = '"+requestId+"'";
        writeLog("requestId:"+requestId+" 关联查询查询明细表sql:"+sqlDetail);
        rs.execute(sqlDetail);
        while(rs.next()) {
            List<Object> list = new ArrayList<>();
            list.add(WorkFlowNameConvertor.getEN_Lcbh(Util.null2String(rs.getString("lcbh"))));
            list.add(Util.null2String(rs.getString("lastname")));
//            list.add(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());
            list.add(Util.null2String(rs.getString("lastname")));
            list.add(Util.null2String(rs.getString("workcode")));
            list.add(Util.null2String(rs.getString("khxmc")));
            //list.add(Util.null2String(rs.getString("shzxs")));//TODO 省或直辖市
            //list.add(Util.null2String(rs.getString("cs")));//TODO 城市
            String area = Util.null2String(rs.getString("ss"));
            List<String> areaArray = cityCodeToName(area);
            if (null!=areaArray&&areaArray.size()>0){
                list.add(areaArray.get(0));
                if (areaArray.size()>1){
                    list.add(areaArray.get(1));
                }else {
                    list.add("");
                }
            }else {
                list.add("");
                list.add("");
            }
            BigDecimal b =BigDecimal.valueOf(StringUtils.isEmpty(rs.getString("yxzfje")) ? 0.00 :Double.parseDouble(rs.getString("yxzfje")));
            //b.add(BigDecimal.valueOf(StringUtils.isEmpty(rs.getString("xjzfje")) ? 0.00 :Double.parseDouble(rs.getString("xjzfje")))); //周伟说现金支付不写明细表
            list.add(b.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            list.add("0");
            //金额为0的情况不写入资金明细表 且 银行账户不为空
            if(b.compareTo(BigDecimal.ZERO)>0&&null!=rs.getString("yxzh")&&org.apache.commons.lang.StringUtils.isNotEmpty(rs.getString("yxzh"))) {
                insertList.add(list);
            }
        }
        return insertList;
    }

    /**
     * 判断是是否是非自付（非自付不写资金表）
     * @param requestId
     * @param mainTableName
     */
    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+"' )";
        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);
            writeLog("requestId:"+requestId+" 查询是否为全部非自付小计金额tempB:"+tempB);
            totalZFB = (totalZFB.add(tempB).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        writeLog("requestId:"+requestId+" 自付费用汇总金额 totalZFB:"+totalZFB);
        if(totalZFB.compareTo(BigDecimal.ZERO)==0) {
            return true;//没有自付费用
        }
        return false;
    }

}
