package com.engine.htsc.payment.util;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.htsc.businessMethod.SubUnionBizUtil;
import com.engine.htsc.payment.dao.PaymentDao;
import com.engine.htsc.payment.pojo.*;
import com.engine.htsc.payment.service.BudgetCommand;
import com.engine.htsc.payment.service.BudgetService;
import com.engine.htsc.payment.service.impl.*;
import com.engine.htsc.trip.util.WeaverUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author:k1810012
 * desc:
 */
public class BizUtils {

  /**
   * cancelInvLink4Lang,重置浪潮发票关联
   */
  private void cancelInvLink4Lang(String mainId, String dtTableName, String ngrgh, String lcbh) {
    RecordSet rs = new RecordSet();
    rs.writeLog(String.format("开始重置明细表: %s; mainid:%s", dtTableName, mainId));
    HTUtil ht = new HTUtil();
    String sql = "SELECT WJID,FPHM,FPDM FROM " + dtTableName + " WHERE MAINID = ?";
    rs.executeQuery(sql, mainId);
    while (rs.next()) {
      Map<String, Object> params = new HashMap<>();
      params.put("UserCode", ngrgh);
      params.put("BillID", lcbh);
      params.put("FileID", Util.null2String(rs.getString("WJID")));
      params.put("InvoiceNum", Util.null2String(rs.getString("FPHM")));
      params.put("InvoiceCode", Util.null2String(rs.getString("FPDM")));
      String s = ht.resetImageAndBill(params);
      rs.writeLog("cancelInvLink4Lang: response:%s", JSONObject.toJSONString(s));
    }

  }

  /**
   * 取消发票关联
   */
  public void cancelInvLink(String requestId) throws Exception {
    RecordSet rs = new RecordSet();
    String tableName = getTableNameByRequestId(requestId);
    String sql = "SELECT ID,NGRGH,LCBH FROM " + tableName + " WHERE REQUESTID = ?";
    rs.executeQuery(sql, requestId);
    String ngrgh = "";
    String lcbh = "";
    String mainId = "";
    if (rs.next()) {
      ngrgh = Util.null2String(rs.getString("NGRGH"));
      lcbh = Util.null2String(rs.getString("LCBH"));
      mainId = Util.null2String(rs.getString("ID"));
    }
    rs.writeLog(String.format(" 取消发票关联, requestid:%s; lcbh:%s, ngrgh:%s", requestId, lcbh, ngrgh));
    if (StringUtils.isNotBlank(ngrgh) && StringUtils.isNotBlank(lcbh)) {
      //删除uf表中所关联的发票数据
      String delSql = "delete from UF_PJXXGL where REQUESTID=?";
      boolean b = rs.executeUpdate(delSql, requestId);
      rs.writeLog(String.format("删除uf表中所关联的发票数据: boolean:%s", b));
      //调用浪潮发票重置接口
      cancelInvLink4Lang(mainId, tableName + "_dt5", ngrgh, lcbh);
      cancelInvLink4Lang(mainId, tableName + "_dt6", ngrgh, lcbh);
      if (lcbh.contains("差旅")) {
        cancelInvLink4Lang(mainId, tableName + "_dt4", ngrgh, lcbh);
      }
    }
  }

  /**
   * 更新员工慰问流程建模页面的付款状态
   *
   * @param rid     requestId,逗号分隔,员工慰问流程rid
   * @param payCode 付款状态 fkzt, 0退回; 1,提交; 2,出纳付款完成
   */
  public static void updateStaffCodStatus(String rid, String payCode) throws Exception {
    Assert.notBlank(rid, "更新的流程id不能为空");
    Assert.notBlank(payCode, "更新的流程状态不能为空");
    Assert.isTrue("0,1,2".contains(payCode), "更新的流程状态不合法," + payCode);
    String replace = rid.replace(",", "','");
    RecordSet rs = new RecordSet();
    rs.writeLog(String.format("updateStaffCodStatus, reqeustId: %s; fkzt: %s", replace, payCode));
    String sql = "update UF_WWSQHZ set FKZT=? where REQUID in ('" + replace + "')";
    rs.executeUpdate(sql, payCode);
  }

  /**
   * sql查询代码标准化
   */
  public static Map<String, String> select2Map(String sql) {
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql);
    String[] columnName = rs.getColumnName();
    Map<String, String> maps = new HashMap<>();
    if (rs.next()) {
      for (String col : columnName) {
        maps.put(col.toLowerCase(), Util.null2String(rs.getString(col)));
      }
    }
    return maps;
  }

  public String getUtf8String(String str) {
    if (str != null && str.length() > 0) {
      String needEncodeCode = "ISO-8859-1";
      try {
        if (Charset.forName(needEncodeCode).newEncoder().canEncode(str)) {
          str = new String(str.getBytes(needEncodeCode), "UTF-8");
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    return str;
  }

  /**
   * 根据付款类型获取预算command
   *
   * @param lb 流程类别
   * @return BudgetCommand
   */
  public static BudgetCommand getBudgetCommentByLb(String lb) throws Exception {

    if ("0".equals(lb) || "2".equals(lb) || "1".equals(lb) || "3".equals(lb)) {
      return new HeadPaymentBudgetCommand();
    } else if ("9".equals(lb)) {
      return new HeadBxBudgetCommand();
    } else if ("10".equals(lb)) {
      return new HeadClBxBudgetCommand();
    } else if ("4".equals(lb)) {
      return new SettlePaymentCommand();
    }else {
      new BaseBean().writeLog("lb为空");
      throw new Exception("建模付款类型没有维护");
    }
  }

  /**
   * saveLog {@link WbLog}
   *
   * @param wbLog 日志表记录
   */
  public static void saveLog(WbLog wbLog) throws Exception {
    RecordSet rs = new RecordSet();
    try {
      rs.executeUpdate("insert into UF_WBLOG (REQUESTNO, OPERATOR, RESULT, TIME, URL, METHOD, REQUEST, RESPONSE, IP)\n" +
              "values (?,?,?,?,?,?,?,?,?)", wbLog.toList());
    } catch (Exception e) {
      throw new Exception("更新日志表失败:" + e.getMessage());
    }
  }

  /**
   * 更新预算记录表
   *
   * @param requestNo   流程id
   * @param billStatus  当前状态
   * @param budgetParam 请求参数
   * @param itFlag      标志为it流程  0或者空 不是it流程; 1 是it流程
   * @throws Exception sql异常
   */
  public void refreshBudgetRecord(String requestNo, String billStatus, String budgetParam, String itFlag) throws Exception {
    RecordSet rs = new RecordSet();
    rs.executeQuery("select count(*) n from UF_YSJLB where itflag=? and LCID=?", itFlag, requestNo);
    String n = "0";
    if (rs.next()) {
      n = rs.getString("n");
    }
    if ("0".equals(n)) {
      DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
      List<Object> listToSave = new ArrayList<>();
      listToSave.add(requestNo);
      listToSave.add(budgetParam);
      listToSave.add(billStatus);
      listToSave.add(df.format(LocalDateTime.now()));
      listToSave.add(itFlag);
      String sql = "INSERT INTO UF_YSJLB (LCID,YSQQCS,DQYSZT,DQSJ,ITFLAG) VALUES (?,?,?,?,?)";
      rs.executeUpdate(sql, listToSave);
    } else {
      List<Object> listToUpdate = new ArrayList<>();
      listToUpdate.add(budgetParam);
      listToUpdate.add(billStatus);
      listToUpdate.add(requestNo);
      listToUpdate.add(itFlag);
      String sql = "UPDATE UF_YSJLB SET YSQQCS = ?,DQYSZT=? WHERE LCID=? and ITFLAG=?";
      rs.executeUpdate(sql, listToUpdate);
    }

  }

  public <T> Map<String, Object> convertDtoToMap(T t) {
    Map<String, Object> dataMap = new HashMap<>();
    String jsonText = JSON.toJSONString(t);
    dataMap.put("data", jsonText);
    return dataMap;
  }

  public boolean updateBudgetMidTable(String requestNo, String billStatus) throws Exception {
    RecordSet rs = new RecordSet();
    try {
      String tableName = getTableNameByRequestId(requestNo);
      String sql = "select FKXX,LCBH,FKLX from " + tableName + " where REQUESTID=" + requestNo;
      rs.executeQuery(sql);
      String bz = "0";
      String lx = "";
      String title = "";
      if (rs.next()) {
        bz = rs.getString("FKXX");
        lx = rs.getString("FKLX");
        title = rs.getString("LCBH");
      }
      String yskmTable = "";
      if (!"1".equals(bz)) {
        yskmTable = tableName + "_DT8";
      } else {
        yskmTable = tableName + "_DT9";
      }
      boolean isItFlag = false;
      if ("1".equals(lx)) {
        isItFlag = true;
      }
      BudgetService bds = new BudgetServiceImpl();
      return bds.doBudgetMiddleTable(title, billStatus,null, yskmTable, tableName, isItFlag);
    } catch (Exception e) {
      rs.writeLog("\n 更新预算中间表出现异常 \n");
      rs.writeLog("catch: " + e.getMessage());
      e.printStackTrace();
      return false;
    }
  }

  public String getTableNameByRequestId(String requestId) {
    RecordSet rs = new RecordSet();
    rs.execute("select t1.tablename from workflow_bill t1,workflow_base t2,workflow_requestbase t3 \n where t1.id =t2.formid and t2.id = t3.workflowid and t3.requestid = " +
            requestId);
    String table = "";
    if (rs.next()) {
      table = Util.null2String(rs.getString("tablename"));
    }
    return table;
  }

  public void log(String message) {
    BaseBean log = new BaseBean();
    String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
    int lineNumber = Thread.currentThread().getStackTrace()[1].getLineNumber();
    String logFormat = "\n" +
            "%s@[%d] >>>\n" +
            "%s";
    log.writeLog(String.format(logFormat, methodName, lineNumber, message));
  }

  /**
   * 生成付款核算接口
   *
   * @param rid 流程id
   * @param lb  核算参数字段 lb
   * @return 核算参数
   */
  public CostAccountDto generateCommonPayData(String rid, String lb) throws Exception {
    RecordSet rs = new RecordSet();
    try {
      DepartmentComInfo dc = new DepartmentComInfo();
      ResourceComInfo rc = new ResourceComInfo();
      PaymentDao pd = new PaymentDao();
      String workFlowTableName = getTableNameByRequestId(rid);

      String baseInfo = "SELECT t1.SFQDZ,t1.ywht,t1.fklx,t1.NGR,t1.SZBM,t1.LCBH,t1.REQUESTID,t1.DJZS,t1.LCBT,t1.NGSJ,t2.REQUESTNAME,t2.REQUESTID\n" +
              "FROM " + workFlowTableName + " t1\n" +
              "LEFT OUTER JOIN WORKFLOW_REQUESTBASE t2 on t1.REQUESTID=t2.REQUESTID\n" +
              "WHERE t1.REQUESTID=?";
      rs.executeQuery(baseInfo, rid);
      CostAccountDto costAccountDto = new CostAccountDto();
      if (rs.next()) {
        String ngr = Util.null2String(rs.getString("NGR"));
        String bm = Util.null2String(rs.getString("SZBM")); //部门
        String requestMark = Util.null2String(rs.getString("LCBH"));
        String fjzs = Util.null2String(rs.getString("DJZS")); //附件张数
        String ngrq = Util.null2String(rs.getString("NGSJ")); //拟稿日期
        String requestName = Util.null2String(rs.getString("REQUESTNAME"));
        String ywht = Util.null2String(rs.getString("ywht")); //有无合同
        String SFQDZ = Util.null2String(rs.getString("SFQDZ")); //有无合同

        costAccountDto.setElectronicBill(SFQDZ);
        costAccountDto.setType(lb); //总部付款费用核算
        costAccountDto.setBz2("0");
        costAccountDto.setNgrDept(dc.getDepartmentmark(bm));
        costAccountDto.setNgrDeptCode(dc.getDepartmentCode(bm));
        costAccountDto.setNgrName(rc.getWorkcode(ngr));
        costAccountDto.setRequestMark(requestMark);
        costAccountDto.setRequestId(requestMark); //djid传流程编码,流程id总部不需要
        costAccountDto.setAttachmentNum(fjzs);
        costAccountDto.setLocationName("");
        costAccountDto.setTitle(requestName);
        costAccountDto.setCurrency("RMB");
        costAccountDto.setCreateDate(ngrq);
        costAccountDto.setReimbursementWay("");
        costAccountDto.setPayOrderNo(requestMark); //总部付款付款单号直接传流程编码
      }

      //获取支付明细(dt11)
      String getPayInfoFromDt11 = pd.getPayInfoFromDt11(workFlowTableName, rid);
      List<PayDetail> payDetailList = new ArrayList<>();
      rs.executeQuery(getPayInfoFromDt11);
      while (rs.next()) {
        PayDetail payDetail = new PayDetail();
        String payByBank = Util.null2String(rs.getString("YXZFJE"));
        String payByCash = Util.null2String(rs.getString("XJZFJE"));
        String bankName = Util.null2String(rs.getString("KHXMC"));
        String bankAccount = Util.null2String(rs.getString("YXZH"));
        String SKDW = Util.null2String(rs.getString("SKDW"));
        payDetail.setPayByBank(payByBank);
        payDetail.setPayByCash(payByCash);
        payDetail.setBankName(bankName);
        payDetail.setBankAccount(bankAccount);
        payDetail.setEmployeeDept("");
        payDetail.setEmployeeName("");
        payDetail.setPayee(SKDW);
        payDetailList.add(payDetail);
      }
      costAccountDto.setPayDetails(payDetailList);

      //获取预算明细
      String subjectInfoFromDt8AndDt12 = pd.getSubjectInfoFromDt8AndDt12(workFlowTableName, rid);
      List<KjDetail> kjDetailList = new ArrayList<>();
      rs.executeQuery(subjectInfoFromDt8AndDt12);
      while (rs.next()) {
        KjDetail kjDetail = new KjDetail();
        BudgetData budgetData = new BudgetData(); //预算科目
        SubjectData subjectData = new SubjectData(); //会计科目
        String fysjcdbm = Util.null2String(rs.getString("FYSJCDBM")); //费用承担部门
        String je = Util.null2String(rs.getString("JE"));
        String zhrmb = Util.null2String(rs.getString("ZHRMB"));
        String sy = Util.null2String(rs.getString("SY"));
        String hjkmmc = Util.null2String("");
        String hjkmbm = Util.null2String(rs.getString("HJKM"));
        subjectData.setItemCode(hjkmbm);
        subjectData.setItemName(hjkmmc);
        String dyyskm = Util.null2String(rs.getString("YSKM"));
        String dyysmc = Util.null2String(rs.getString("YSKMMC"));
        budgetData.setRelationCode(hjkmbm);
        budgetData.setItemCode(dyyskm);
        budgetData.setItemName(dyysmc);
        kjDetail.setExpenseDeptCode(dc.getDepartmentCode(fysjcdbm));
        kjDetail.setExpenseDept(dc.getDepartmentmark(fysjcdbm));
        kjDetail.setExpenseBadge("");
        kjDetail.setExpensePerson("");
        kjDetail.setSubjectData(subjectData);
        kjDetail.setBudgetData(budgetData);
        kjDetail.setPriceRMB(zhrmb);
        kjDetail.setMoney(zhrmb);
        kjDetail.setProjectCode("");
        kjDetail.setProject("");
        kjDetail.setReason(sy);
        kjDetailList.add(kjDetail);
      }
      costAccountDto.setKjDetails(kjDetailList);
      //HTO-11640查询主表，当付款流程中字段“先付款后发票”选项为“是”时，接口字段“SFYFP”传值“Y”，
      // “先付款后发票”选项为“否”时，接口字段“SFYFP”传值“N”；
      //针对托收业务通用付款,资管通用付款,紫金通用付款,子公司通用付款
      if(SubUnionBizUtil.equalsTableName(rid, "fyft")|| SubUnionBizUtil.equalsTableName(rid, "zgtyfk")
              ||SubUnionBizUtil.equalsTableName(rid, "zjtyfk") ||SubUnionBizUtil.equalsTableName(rid, "zgstyfk")){
        RecordSet sqlFindYfp = new RecordSet();
        String sqlNew = "select sfxfkhtgfp from "+workFlowTableName+" where requestid = "+rid;
        sqlFindYfp.execute(sqlNew);
        if (sqlFindYfp.next()){
          String sfxfkhtgfp = Util.null2String(sqlFindYfp.getString("sfxfkhtgfp"));
          if ("0".equals(sfxfkhtgfp)){
            //当付款流程中字段“先付款后发票”选项为“是”时，接口字段“SFYFP”传值“Y”
            costAccountDto.setSFYFP("Y");
          }else{
            //“先付款后发票”选项为“否”时，接口字段“SFYFP”传值“N”；
            costAccountDto.setSFYFP("N");
          }
        }
      }
      return costAccountDto;
    } catch (Exception e) {
      rs.writeLog("error," + e.getMessage());
      throw new Exception("生成核算数据错误，requestId：" + rid);
    }
  }

  /**
   * 生成报销核算接口参数
   *
   * @param requestid 流程id
   * @param wftype    lb 调用核算的类型 {@link com.engine.htsc.payment.enums.HsType}
   * @return CostAccountDto
   * @author wan
   */
  public CostAccountDto generateCommonReimbData(String requestid, String wftype) {
    CostAccountDto costAccDto = new CostAccountDto();
    RecordSet rs = new RecordSet();
    String tablename = getTableNameByRequestId(requestid);
    rs.executeQuery(" select SFQDZ,id,ngr,szbm,lcbh,djzs,ngsj from " + tablename + " where requestid=? ", new Object[]{requestid});
    if (rs.next()) {
      try {
        String id = Util.null2String(rs.getString("id"));
        String ngr = Util.null2String(rs.getString("ngr"));
        String szbm = Util.null2String(rs.getString("szbm"));
        String lcbh = Util.null2String(rs.getString("lcbh"));
        String djzs = Util.null2String(rs.getString("djzs"));
        String ngsj = Util.null2String(rs.getString("ngsj")) + ":00";
        String sfqdz = Util.null2String(rs.getString("SFQDZ"));

        DepartmentComInfo deptComInfo = new DepartmentComInfo();
        String szbmmc = deptComInfo.getDepartmentName(szbm);
        String szbmbm = deptComInfo.getDepartmentCode(szbm);

        ResourceComInfo resourceComInfo = new ResourceComInfo();
        String ngrmc = resourceComInfo.getWorkcode(ngr);

        rs.executeQuery(" select requestname from workflow_requestbase where requestid=? ", new Object[]{requestid});
        rs.next();
        String requestname = Util.null2String(rs.getString("requestname"));

        costAccDto.setElectronicBill(sfqdz);
        costAccDto.setType(wftype);
        costAccDto.setNgrDept(szbmmc);
        costAccDto.setNgrDeptCode(szbmbm);
        costAccDto.setNgrName(ngrmc);
        costAccDto.setRequestMark(lcbh);
        costAccDto.setRequestId(lcbh);
        costAccDto.setAttachmentNum(djzs);
        costAccDto.setLocationName("");
        costAccDto.setTitle(requestname);
        costAccDto.setCurrency("RMB");
        costAccDto.setCreateDate(ngsj);
        costAccDto.setReimbursementWay("");
        costAccDto.setPayOrderNo(lcbh);

        List kjdtList = new ArrayList();
        String dt12Sql = " select fysjcdbm,fysjcdr,hjkm,yskm,yskmmc,zhrmb,SY from " + tablename + "_dt12 where mainid=? ";
        rs.executeQuery(dt12Sql, new Object[]{id});
        while (rs.next()) {
          String fysjcdbm = Util.null2String(rs.getString("fysjcdbm"));
          String fysjcdr = Util.null2String(rs.getString("fysjcdr"));
          String hjkm = Util.null2String(rs.getString("hjkm"));
          String yskm = Util.null2String(rs.getString("yskm"));
          String yskmmc = Util.null2String(rs.getString("yskmmc"));
          String zhrmb = Util.null2String(rs.getString("zhrmb"));
          String sy = Util.null2String(rs.getString("SY"));

          String fysjcdbmbm = deptComInfo.getDepartmentCode(fysjcdbm);
          String fysjcdbmmc = deptComInfo.getDepartmentName(fysjcdbm);
          String fysjcdrbh = resourceComInfo.getWorkcode(fysjcdr);
          String fysjcdrmc = resourceComInfo.getLastname(fysjcdr);

          KjDetail kjitem = new KjDetail();
          kjitem.setExpenseDeptCode(fysjcdbmbm);
          kjitem.setExpenseDept(fysjcdbmmc);
          kjitem.setExpenseBadge(fysjcdrbh);
          kjitem.setExpensePerson(fysjcdrmc);

          SubjectData subject = new SubjectData();
          subject.setItemCode(hjkm);
          subject.setItemName(getKjkmmc(hjkm));
          kjitem.setSubjectData(subject);

          BudgetData budget = new BudgetData();
          budget.setRelationCode(hjkm);
          budget.setItemCode(yskm);
          budget.setItemName(yskmmc);
          kjitem.setBudgetData(budget);

          kjitem.setPriceRMB(zhrmb);
          kjitem.setMoney(zhrmb);
          kjitem.setProjectCode("");
          kjitem.setProject("");
          kjitem.setReason(sy);

          kjdtList.add(kjitem);
        }
        costAccDto.setKjDetails(kjdtList);

        List zfdtList = new ArrayList();
        String dt11Sql = " select yxzfje,xjzfje,khxmc,yxzh,bm,ygxm from " + tablename + "_dt11 where mainid=? ";
        rs.executeQuery(dt11Sql, new Object[]{id});
        while (rs.next()) {
          String yxzfje = Util.null2String(rs.getString("yxzfje"));
          String xjzfje = Util.null2String(rs.getString("xjzfje"));
          String khxmc = Util.null2String(rs.getString("khxmc"));
          String yxzh = Util.null2String(rs.getString("yxzh"));
          String bm = Util.null2String(rs.getString("bm"));
          String ygxm = Util.null2String(rs.getString("ygxm"));

          String bmmc = deptComInfo.getDepartmentName(bm);
          String ygxmmc = resourceComInfo.getLastname(ygxm);
          String ygxmwk = resourceComInfo.getWorkcode(ygxm);

          PayDetail payitem = new PayDetail();
          payitem.setPayByBank(yxzfje);
          payitem.setPayByCash(xjzfje);
          payitem.setBankName(khxmc);
          payitem.setBankAccount(yxzh);
          payitem.setEmployeeDept(bmmc);
          payitem.setEmployeeName(ygxmmc);
          payitem.setEmployeeBadge(ygxmwk);

          zfdtList.add(payitem);

        }
        costAccDto.setPayDetails(zfdtList);


      } catch (Exception e) {
        e.printStackTrace();
      }


    }

    return costAccDto;
  }


  /**
   * 生成紫金核算参数
   *
   * @param requestid 流程id
   * @param wftype    lb 调用核算的类型
   * @return CostAccountDto
   * @author wan
   */
  public CostAccountDto ZjCommonReimbData(String requestid, String wftype) {
    CostAccountDto costAccDto = new CostAccountDto();
    RecordSet rs = new RecordSet();
    String tablename = getTableNameByRequestId(requestid);
    rs.executeQuery(" select id,ngr,szbm,lcbh,djzs,ngsj from " + tablename + " where requestid=? ", new Object[]{requestid});
    if (rs.next()) {
      try {
        String id = Util.null2String(rs.getString("id"));
        String ngr = Util.null2String(rs.getString("ngr"));
        String szbm = Util.null2String(rs.getString("szbm"));
        String lcbh = Util.null2String(rs.getString("lcbh"));
        String djzs = Util.null2String(rs.getString("djzs"));
        String ngsj = Util.null2String(rs.getString("ngsj")) + ":00";

        DepartmentComInfo deptComInfo = new DepartmentComInfo();
        String szbmmc = deptComInfo.getDepartmentName(szbm);
        String szbmbm = deptComInfo.getDepartmentCode(szbm);

        ResourceComInfo resourceComInfo = new ResourceComInfo();
        String ngrmc = resourceComInfo.getWorkcode(ngr);

        rs.executeQuery(" select requestname from workflow_requestbase where requestid=? ", new Object[]{requestid});
        rs.next();
        String requestname = Util.null2String(rs.getString("requestname"));

        costAccDto.setType(wftype);
        costAccDto.setNgrDept(szbmmc);
        costAccDto.setNgrDeptCode(szbmbm);
        costAccDto.setNgrName(ngrmc);
        costAccDto.setRequestMark(lcbh);
        costAccDto.setRequestId(lcbh);
        costAccDto.setAttachmentNum(djzs);
        costAccDto.setLocationName("");
        costAccDto.setTitle(requestname);
        costAccDto.setCurrency("RMB");
        costAccDto.setCreateDate(ngsj);
        costAccDto.setReimbursementWay("");
        costAccDto.setPayOrderNo(lcbh);

        List kjdtList = new ArrayList();
        String dt12Sql = " select fysjcdbm,fysjcdr,hjkm,yskm,yskmmc,zhrmb,SY from " + tablename + "_dt12 where mainid=? ";
        rs.executeQuery(dt12Sql, new Object[]{id});
        while (rs.next()) {
         // String fysjcdbm = Util.null2String(rs.getString("fysjcdbm"));
          String fysjcdr = Util.null2String(rs.getString("fysjcdr"));
          String hjkm = Util.null2String(rs.getString("hjkm"));
          String yskm = Util.null2String(rs.getString("yskm"));
          String yskmmc = Util.null2String(rs.getString("yskmmc"));
          String zhrmb = Util.null2String(rs.getString("zhrmb"));
          String sy = Util.null2String(rs.getString("SY"));
          String fysjcdbmmc ="";
          String fysjcdrbh = "";
          String fysjcdrmc = "";

          String fysjcdbmbm = Util.null2String(rs.getString("fysjcdbm"));
          Map<String,String> map=getzjdeptname(fysjcdbmbm);
         if(map.size()>0){
           fysjcdbmmc=Util.null2String(map.get("bmmc"));
           fysjcdrbh=Util.null2String(map.get("bmfzrid"));
           fysjcdrmc=Util.null2String(map.get("bmfzr"));
         }


          KjDetail kjitem = new KjDetail();
          kjitem.setExpenseDeptCode(fysjcdbmbm);
          kjitem.setExpenseDept(fysjcdbmmc);
          kjitem.setExpenseBadge(fysjcdrbh);
          kjitem.setExpensePerson(fysjcdrmc);

          SubjectData subject = new SubjectData();
          subject.setItemCode(hjkm);
          subject.setItemName(getKjkmmc(hjkm));
          kjitem.setSubjectData(subject);

          BudgetData budget = new BudgetData();
          budget.setRelationCode(hjkm);
          budget.setItemCode(yskm);
          budget.setItemName(yskmmc);
          kjitem.setBudgetData(budget);

          kjitem.setPriceRMB(zhrmb);
          kjitem.setMoney(zhrmb);
          kjitem.setProjectCode("");
          kjitem.setProject("");
          kjitem.setReason(sy);

          kjdtList.add(kjitem);
        }
        costAccDto.setKjDetails(kjdtList);

        List zfdtList = new ArrayList();
        String dt11Sql = " select yxzfje,xjzfje,khxmc,yxzh,bm,ygxm from " + tablename + "_dt11 where mainid=? ";
        rs.executeQuery(dt11Sql, new Object[]{id});
        while (rs.next()) {
          String yxzfje = Util.null2String(rs.getString("yxzfje"));
          String xjzfje = Util.null2String(rs.getString("xjzfje"));
          String khxmc = Util.null2String(rs.getString("khxmc"));
          String yxzh = Util.null2String(rs.getString("yxzh"));
          String bm = Util.null2String(rs.getString("bm"));
          String ygxm = Util.null2String(rs.getString("ygxm"));

          String bmmc = deptComInfo.getDepartmentName(bm);
          String ygxmmc = resourceComInfo.getLastname(ygxm);
          String ygxmwk = resourceComInfo.getWorkcode(ygxm);

          PayDetail payitem = new PayDetail();
          payitem.setPayByBank(yxzfje);
          payitem.setPayByCash(xjzfje);
          payitem.setBankName(khxmc);
          payitem.setBankAccount(yxzh);
          payitem.setEmployeeDept(bmmc);
          payitem.setEmployeeName(ygxmmc);
          payitem.setEmployeeBadge(ygxmwk);

          zfdtList.add(payitem);

        }
        costAccDto.setPayDetails(zfdtList);


      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return costAccDto;
  }
  public Map<String,String> getzjdeptname(String value){
    Map<String,String> map=new HashMap();
    if("".equals(value)){
      return map;
    }

    RecordSet rs=new RecordSet();
    String sql="  select BMBH,BMMC,BMFZR,BMFZRID from uf_zjbmb  where bmbh=?";
    rs.executeQuery(sql, new Object[]{value});
    if(rs.getCounts()<=0){
      return map;
    }
    if(rs.next()){
      map.put("bmbh",Util.null2String(rs.getString("BMMC")));
      map.put("bmmc",Util.null2String(rs.getString("BMMC")));
      map.put("bmfzr",Util.null2String(rs.getString("BMFZR")));
      map.put("bmfzrid",Util.null2String(rs.getString("BMFZRID")));
    }
    return map;
  }

  /**
   * 生成差旅核算参数
   *
   * @param requestid 流程id
   * @param wftype    lb 调用核算的类型
   * @return CostAccountDto
   * @author wan
   */
  public CostAccountDto generateTravelReimbData(String requestid, String wftype) {
    CostAccountDto costAccDto = new CostAccountDto();
    RecordSet rs = new RecordSet();
    PropBean pb = new PropBean();
    String tablename = getTableNameByRequestId(requestid);
    rs.executeQuery(" select SFQDZ,id,ngr,szbm,lcbh,djzs,ngsj from " + tablename + " where requestid=? ", new Object[]{requestid});
    if (rs.next()) {
      try {
        String id = Util.null2String(rs.getString("id"));
        String ngr = Util.null2String(rs.getString("ngr"));
        String szbm = Util.null2String(rs.getString("szbm"));
        String lcbh = Util.null2String(rs.getString("lcbh"));
        String djzs = Util.null2String(rs.getString("djzs"));
        String ngsj = Util.null2String(rs.getString("ngsj")) + ":00";
        String sfqdz = Util.null2String(rs.getString("SFQDZ"));

        DepartmentComInfo deptComInfo = new DepartmentComInfo();
        String szbmmc = deptComInfo.getDepartmentName(szbm);
        String szbmbm = deptComInfo.getDepartmentCode(szbm);

        ResourceComInfo resourceComInfo = new ResourceComInfo();
        String ngrmc = resourceComInfo.getWorkcode(ngr);

        rs.executeQuery(" select requestname from workflow_requestbase where requestid=? ", new Object[]{requestid});
        rs.next();
        String requestname = Util.null2String(rs.getString("requestname"));

        costAccDto.setElectronicBill(sfqdz);
        costAccDto.setType(wftype);
        costAccDto.setNgrDept(szbmmc);
        costAccDto.setNgrDeptCode(szbmbm);
        costAccDto.setNgrName(ngrmc);
        costAccDto.setRequestMark(lcbh);
        costAccDto.setRequestId(lcbh);
        costAccDto.setAttachmentNum(djzs);
        costAccDto.setLocationName("");
        costAccDto.setTitle(requestname);
        costAccDto.setCurrency("RMB");
        costAccDto.setCreateDate(ngsj);
        costAccDto.setReimbursementWay("");
        costAccDto.setPayOrderNo(lcbh);

        List kjdtList = new ArrayList();
        String dt12Sql = " select fycdbm,fycdr,hjkm,zhrmb  from " + tablename + "_dt11 where mainid=? ";
        rs.executeQuery(dt12Sql, new Object[]{id});
        while (rs.next()) {
          String fycdbm = Util.null2String(rs.getString("fycdbm"));
          String fycdr = Util.null2String(rs.getString("fycdr"));
          String hjkm = Util.null2String(rs.getString("hjkm"));
          if (!"".equals(hjkm)) {
            hjkm = hjkm.split("_")[1];
          }
          String zhrmb = Util.null2String(rs.getString("zhrmb"));

          String fysjcdbmbm = deptComInfo.getDepartmentCode(fycdbm);
          String fysjcdbmmc = deptComInfo.getDepartmentName(fycdbm);
          String fysjcdrbh = resourceComInfo.getWorkcode(fycdr);
          String fysjcdrmc = resourceComInfo.getLastname(fycdr);

          KjDetail kjitem = new KjDetail();
          kjitem.setExpenseDeptCode(fysjcdbmbm);
          kjitem.setExpenseDept(fysjcdbmmc);
          kjitem.setExpenseBadge(fysjcdrbh);
          kjitem.setExpensePerson(fysjcdrmc);

          SubjectData subject = new SubjectData();
          subject.setItemCode(hjkm);
          subject.setItemName(getKjkmmc(hjkm));
          kjitem.setSubjectData(subject);

          BudgetData budget = new BudgetData();
          budget.setRelationCode(hjkm);
          String yskmbm = pb.getPropName(hjkm);
          budget.setItemCode(yskmbm);
          budget.setItemName(getYskmmc(yskmbm));
          kjitem.setBudgetData(budget);

          kjitem.setPriceRMB(zhrmb);
          kjitem.setMoney(zhrmb);
          kjitem.setProjectCode("");
          kjitem.setProject("");
          kjitem.setReason("");

          kjdtList.add(kjitem);
        }
        costAccDto.setKjDetails(kjdtList);

        List zfdtList = new ArrayList();
        String dt11Sql = " select yxzfje,xjzfje,khx,yxzh,bm,bxr from " + tablename + "_dt10 where mainid=? ";
        rs.executeQuery(dt11Sql, new Object[]{id});
        while (rs.next()) {
          String yxzfje = Util.null2String(rs.getString("yxzfje"));
          String xjzfje = Util.null2String(rs.getString("xjzfje"));
          String khxmc = Util.null2String(rs.getString("khx"));
          String yxzh = Util.null2String(rs.getString("yxzh"));
          String bm = Util.null2String(rs.getString("bm"));
          String ygxm = Util.null2String(rs.getString("bxr"));

          String bmmc = deptComInfo.getDepartmentName(bm);
          String ygxmmc = resourceComInfo.getLastname(ygxm);
          String ygxmwk = resourceComInfo.getWorkcode(ygxm);

          PayDetail payitem = new PayDetail();
          payitem.setPayByBank(yxzfje);
          payitem.setPayByCash(xjzfje);
          payitem.setBankName(khxmc);
          payitem.setBankAccount(yxzh);
          payitem.setEmployeeDept(bmmc);
          payitem.setEmployeeName(ygxmmc);
          payitem.setEmployeeBadge(ygxmwk);

          zfdtList.add(payitem);

        }
        costAccDto.setPayDetails(zfdtList);


      } catch (Exception e) {
        e.printStackTrace();
      }

    }

    return costAccDto;
  }

  /**
   * 根据会计科目编码查询会计科目名称
   *
   * @param kjkmbm
   * @return
   */
  public String getKjkmmc(String kjkmbm) {
    String kjkmmc = "";
    RecordSet rs = new RecordSet();
    rs.executeQuery(" select hjkmmc from uf_kjkmpz where hjkmbm=? ", new Object[]{kjkmbm});
    if (rs.next()) {
      kjkmmc = Util.null2String(rs.getString("hjkmmc"));
    }
    return kjkmmc;
  }

  /**
   * 根据预算科目编码查询预算科目名称
   *
   * @param yskmbm
   * @return
   */
  public String getYskmmc(String yskmbm) {
    String yskmmc = "";
    RecordSet rs = new RecordSet();
    rs.executeQuery(" select yskmmc from uf_kmpz where yskmbm=? ", new Object[]{yskmbm});
    if (rs.next()) {
      yskmmc = Util.null2String(rs.getString("yskmmc"));
    }
    return yskmmc;
  }

  /**
   * 查询是否为it或付款
   *
   * @param requestId 流程id
   * @return true : 通用付款
   * false: it付款
   */
  public static boolean whetherItOrTy(String requestId) throws Exception {
    RecordSet rs = new RecordSet();
    String tableName = WeaverUtil.getTableNameByRequestId(requestId, rs);
    rs.executeQuery("select sfitfy from " + tableName + " where REQUESTID=" + requestId);
    String sfitfy = "";
    if (rs.next()) {
      sfitfy = Util.null2String(rs.getString("sfitfy"));
    }
    return "0".equals(sfitfy); // 0是通用付款
  }

  /**
   * 查询是否为it或付款
   *
   * @param requestId 流程id
   * @return true : 通用付款
   * false: it付款
   */
  public static boolean whetherItOrTy(String requestId, String tableName) throws Exception {
    RecordSet rs = new RecordSet();
    rs.executeQuery("select sfitfy from " + tableName + " where REQUESTID=" + requestId);
    String sfitfy = "";
    if (rs.next()) {
      sfitfy = Util.null2String(rs.getString("sfitfy"));
    }
    return "0".equals(sfitfy);
  }

  /**
   * 是否为总部差旅
   *
   * @param id 出纳付款建模id
   * @return t 是; f 否
   */
  public static boolean isCl(String id) throws Exception {
    RecordSet rs = new RecordSet();
    rs.executeQuery("select REQUESTMARK from WORKFLOW_REQUESTBASE t1\n" +
            "left join UF_ZBFK t2\n" +
            "on t1.REQUESTID=t2.REQUTID\n" +
            "where t2.ID=?", id);
    String title = "";
    if (rs.next()) {
      title = Util.null2String(rs.getString("REQUESTMARK"));
    }

    if ("".equals(title)) {
      throw new Exception(String.format("建模id:%s 未维护流程编号", id));
    }

    return title.contains("总部差旅报销");

  }

}
