package com.engine.htsc.branchpayment.utils;

import com.api.htsc.businessMethod.SubUnionBizUtil;
import com.engine.htsc.branchpayment.pojo.UfCash;
import com.engine.htsc.payment.dao.PaymentDao;
import com.engine.htsc.payment.pojo.*;
import com.engine.htsc.payment.util.BizUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 分支机构工具类
 */
public class BranchBizUtil {

  //分支机构出纳表
  public static final String FZJG = "UF_FZJGFK";
  //子公司
  public static final String ZGS = "UF_ZGSFK";

  /**
   * 获取建模表里的数据
   */
  public List<UfCash> getUfCashList(String ids, String uf) {
    RecordSet rs = new RecordSet();
    String idJoin = String.join("','", Arrays.asList(ids.split(",")));
    rs.executeQuery("select ID,FKLX,REQUTID,LCBH,FKZT,tbdlcyszt from " + uf + " where REQUTID in ('" + idJoin + "')");
    List<UfCash> lists = new ArrayList<>();
    while (rs.next()) {
      UfCash ufCash = new UfCash();
      ufCash.setId(Util.null2String(rs.getString("ID")));
      ufCash.setType(Util.null2String(rs.getString("FKLX")));
      ufCash.setRid(Util.null2String(rs.getString("REQUTID")));
      ufCash.setrMark(Util.null2String(rs.getString("LCBH")));
      ufCash.setFkzt(Util.null2String(rs.getString("FKZT")));
      ufCash.setTbdlcyszt(Util.null2String(rs.getString("tbdlcyszt")));
      lists.add(ufCash);
    }
    return lists;
  }

  /**
   * 更新建模预算状态
   */
  public void updateBudgetStatus(String id, String discard, String uf) {
    RecordSetTrans rst = new RecordSetTrans();
    rst.setAutoCommit(false);
    try {
      if ("1".equals(discard)) {
        rst.executeUpdate("update " + uf + " set TBDLCYSZT=0 where ID=?", id);
      } else if ("-1".equals(discard)) {
        rst.executeUpdate("update " + uf + " set TBDLCYSZT=2,tbdlczt=2,fkzt=2 where ID=?", id);
      }
      rst.executeUpdate("update " + uf + " set FKZT=0 where TBDLCZT=0 and id =?", id);
      rst.commit();
    } catch (Exception e) {
      rst.rollback();
      rst.writeLog("error:" + e.getMessage());
    }
  }

  /**
   * 更新建模核算状态
   */
  public void updateCostStatus(String id, String rid, String uf) {
    RecordSetTrans rst = new RecordSetTrans();
    rst.setAutoCommit(false);
    try {
      rst.executeUpdate("update " + uf + " set TBDLCZT=0 where ID=?", id);
      rst.executeUpdate("update " + uf + " set FKZT=0 where TBDLCYSZT=0 and id =?", id);
      rst.executeUpdate("update UF_YFKMIDDLE set SFFKQR=1 where REQID=?", rid);
      //更新
      rst.commit();
    } catch (Exception e) {
      rst.rollback();
      rst.writeLog("error:" + e.getMessage());
    }
  }

  /**
   * 更新建模手动付款状态
   */
  public String updateManualPaymentStatus(String rids, String uf) {
    RecordSetTrans rst = new RecordSetTrans();
    rst.writeLog("====更新手动付款状态@" + rids);
    if ("".equals(rids)) {
      return "请勾选相关流程进行状态更改";
    }
    try {
      String sqlCondition = String.join("','", rids.split(","));
      rst.setAutoCommit(false);
      rst.executeQuery("SELECT REQUTID,FKZT,LCBH FROM " + uf + " WHERE REQUTID IN ('" + sqlCondition + "')");
      List<String> notin = new ArrayList<>();
      List<String> in = new ArrayList<>();
      while (rst.next()) {
        String fkzt = Util.null2String(rst.getString("FKZT"));
        String requtid = Util.null2String(rst.getString("REQUTID"));
        String lcbh = Util.null2String(rst.getString("LCBH"));
        if ("2".equals(fkzt)) {
          notin.add(lcbh);
        } else {
          in.add(requtid);
        }
      }
      rst.executeUpdate("update " + uf + " set FKFS=1,FKZT=0 where REQUTID in('" + String.join("','", in) + "')");
      rst.commit();
      return "更新手动付款状态成功(注:流程编号为 "+String.join(",", notin)+" 已废弃,无法手动付款)";
    } catch (Exception e) {
      rst.rollback();
      rst.writeLog("====更新手动付款状态失败,出现异常@" + e.getMessage());
      e.printStackTrace();
      return "更新手动付款状态出现异常";
    }
  }

  /**
   * 生成付款核算接口(分支)
   *
   * @param rid 流程id
   * @param lb  核算参数字段 lb
   * @return 核算参数
   */
  public CostAccountDto generateCommonPayData(String rid, String lb) throws Exception {
    RecordSet rs = new RecordSet();
    BizUtils bizUtils = new BizUtils();
    try {
      DepartmentComInfo dc = new DepartmentComInfo();
      ResourceComInfo rc = new ResourceComInfo();
      PaymentDao pd = new PaymentDao();
      String workFlowTableName = bizUtils.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, "fzjgtyfk")){
        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 rid 流程id
   * @param lb  lb 调用核算的类型
   * @return CostAccountDto
   * @author wan
   */
  public CostAccountDto generateTravelReimbData(String rid, String lb) {
    CostAccountDto costAccDto = new CostAccountDto();
    RecordSet rs = new RecordSet();
    PropBean pb = new PropBean();
    BizUtils bizUtils = new BizUtils();
    String tablename = bizUtils.getTableNameByRequestId(rid);
    rs.executeQuery("select SFQDZ,id,ngr,szbm,lcbh,djzs,ngsj from " + tablename + " where requestid=? ",
        rid);
    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=? ",
            rid);
        rs.next();
        String requestname = Util.null2String(rs.getString("requestname"));

        costAccDto.setElectronicBill(SFQDZ);
        costAccDto.setType(lb);
        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<KjDetail> kjdtList = new ArrayList<>();
        String dt12Sql = " select fycdbm,ccr,hjkm,zhrmb  from " + tablename + "_dt11 where mainid=? ";
        rs.executeQuery(dt12Sql, id);
        while (rs.next()) {
          String fycdbm = Util.null2String(rs.getString("fycdbm"));
          String fycdr = Util.null2String(rs.getString("ccr"));
          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(bizUtils.getKjkmmc(hjkm));
          kjitem.setSubjectData(subject);

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

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

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

        List<PayDetail> zfdtList = new ArrayList<>();
        String dt11Sql = " select yxzfje,xjzfje,khxmc,yxzh,bm,ccr from " + tablename + "_dt10 where mainid=? ";
        rs.executeQuery(dt11Sql, 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("ccr"));

          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;
  }
}
