package com.api.htsc.businessMethod;

import com.engine.htsc.payment.enums.BudgetNodeType;
import com.engine.htsc.payment.pojo.*;
import com.engine.htsc.payment.service.impl.HeadBxBudgetCommand;
import com.engine.htsc.payment.service.impl.HeadPaymentBudgetCommand;
import com.engine.htsc.payment.util.BizUtils;
import com.engine.htsc.payment.util.PayUtil;
import org.apache.commons.collections4.CollectionUtils;
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 java.util.ArrayList;
import java.util.List;

/**
 * k1810012
 * <p>
 * 子公司
 * 联合通用报销流程
 * 工具类
 */
public class SubUnionBizUtil {

  public static final String LHTYBX = "lhtybx"; //联合通用报销 UNNUMBER

  public static final String LHTYFK = "lhtyfk"; //联合通用付款 UNNUMBER

  /**
   * 判别流程id是否属于指定流程
   * @param requestId 流程id
   * @param unNumber 流程标识
   * @return true: requestId属于unNumber流程; false则相反
   */
  public static boolean equalsTableName(String requestId, String unNumber) throws Exception {
    RecordSet rs = new RecordSet();

    String sql = "select t1.TABLENAME from workflow_bill t1\n" +
            "LEFT JOIN workflow_base t2\n" +
            "on t1.ID=t2.FORMID\n" +
            "where t2.ISVALID=1 and t2.UNNUMBER=?";
    rs.executeQuery(sql, unNumber);
    String tableName = "";
    if (rs.next()) {
      tableName = Util.null2String(rs.getString("TABLENAME"));
    }

    sql = "select t1.tablename from workflow_bill t1\n" +
            "left join workflow_base t2\n" +
            "on t1.ID=t2.FORMID\n" +
            "left join workflow_requestbase t3\n" +
            "on t2.ID=t3.WORKFLOWID\n" +
            "where t3.requestid =?";
    rs.executeQuery(sql, requestId);
    if (rs.next() && StringUtils.isNotBlank(tableName)) {
      return tableName.equalsIgnoreCase(Util.null2String(rs.getString("tablename")));
    }

    return false;

  }

  /**
   * 联合报销 核算接口参数
   *
   * @param rid 流程id
   * @param lb  核算类别
   * @param payOrder 付款单号
   * @return CostAccountDto {@link CostAccountDto}
   * @author k1810012
   */
  public static CostAccountDto generateUnionReiData(String rid, String lb, String payOrder) throws Exception {
    CostAccountDto costAccDto = new CostAccountDto();
    DepartmentComInfo dc = new DepartmentComInfo();
    ResourceComInfo rc = new ResourceComInfo();
    BizUtils bizUtils = new BizUtils();
    RecordSet rs = new RecordSet();

    String tableName = PayUtil.getTableNameByUnNumber(LHTYBX);
    String sql = String.format(
            "select t1.id,t1.ngr,t1.szbm,t1.lcbh,t1.djzs,t1.ngsj,t1.bxdd,t2.REQUESTNAME from %s t1\n" +
                    "left join workflow_requestbase t2\n" +
                    "on t1.REQUESTID=t2.REQUESTID\n" +
                    "where t1.requestid=?",
            tableName);

    //主表数据汇总
    rs.executeQuery(sql, rid);
    String mainId = ""; //明细表mainId
    if (rs.next()) {
      mainId = Util.null2String(rs.getString("id"));
      String ngr = Util.null2String(rs.getString("ngr"));
      String dept = Util.null2String(rs.getString("szbm")); //所在部门
      String requestMark = Util.null2String(rs.getString("lcbh"));
      String djzs = Util.null2String(rs.getString("djzs")); //单据张数
      String ngsj = Util.null2String(rs.getString("ngsj")) + ":00"; //数据库格式: 2021-08-06 11:45
      String requestName = Util.null2String(rs.getString("REQUESTNAME"));
      //报销地
      String bxdd=Util.null2String(rs.getString("bxdd"));

      costAccDto.setType(lb);
      costAccDto.setNgrDept(dc.getDepartmentmark(dept));
      costAccDto.setNgrDeptCode(dc.getDepartmentCode(dept));
      costAccDto.setNgrName(rc.getLastname(ngr));
      costAccDto.setRequestMark(requestMark);
      costAccDto.setRequestId(payOrder);
      costAccDto.setAttachmentNum(djzs);
      costAccDto.setLocationName("");
      costAccDto.setTitle(requestName);
      costAccDto.setCurrency("RMB");
      costAccDto.setCreateDate(ngsj);
      costAccDto.setReimbursementWay("");
      costAccDto.setPayOrderNo(payOrder);
      costAccDto.setLocationName(getLocationName(bxdd));
    }

    if ( StringUtils.isBlank(mainId) ) {
      throw new Exception(String.format("联合核算,主表sql没有取到流程编号, sql: %s; rid:%s", sql, rid));
    }

    // 会计明细: com.engine.htsc.payment.pojo.CostAccountDto.kjDetails
    List<KjDetail> kjDetails = new ArrayList<>();

    String dt12 = tableName + "_DT12";
    sql = String.format("select fysjcdbm,fysjcdr,hjkm,yskm,yskmmc,zhrmb,SY from %s where mainid=?", dt12);
    rs.executeQuery(sql, mainId);
    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"));

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

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

      KjDetail kjItem = new KjDetail();
      kjItem.setSubjectData(subject);
      kjItem.setBudgetData(budget);

      kjItem.setExpenseDeptCode(dc.getDepartmentCode(fysjcdbm));
      kjItem.setExpenseDept(dc.getDepartmentmark(fysjcdbm));
      kjItem.setExpenseBadge(rc.getWorkcode(fysjcdr));
      kjItem.setExpensePerson(rc.getLastname(fysjcdr));
      kjItem.setPriceRMB(zhrmb);
      kjItem.setMoney(zhrmb);
      kjItem.setProjectCode("");
      kjItem.setProject("");
      kjItem.setReason(sy);

      kjDetails.add(kjItem);
    }
    costAccDto.setKjDetails(kjDetails);

    if ( CollectionUtils.isEmpty(costAccDto.getKjDetails()) ) {
      throw new Exception(String.format("联合核算,明细12 sql没有取到会计数据, sql: %s; mainId:%s", sql, mainId));
    }

    //支付明细: com.engine.htsc.payment.pojo.CostAccountDto.payDetails
    List<PayDetail> payDetails = new ArrayList<>();

    String dt11 = tableName + "_DT11";
    sql = String.format("select yxzfje,xjzfje,khxmc,yxzh,bm,ygxm from %s where mainid=?", dt11);
    rs.executeQuery(sql, mainId);
    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"));

      PayDetail payItem = new PayDetail();
      payItem.setPayByBank(yxzfje);
      payItem.setPayByCash(xjzfje);
      payItem.setBankName(khxmc);
      payItem.setBankAccount(yxzh);
      payItem.setEmployeeDept(dc.getDepartmentmark(bm));
      payItem.setEmployeeName(rc.getLastname(ygxm));
      payItem.setEmployeeBadge(rc.getWorkcode(ygxm));

      payDetails.add(payItem);

    }
    costAccDto.setPayDetails(payDetails);

    if ( CollectionUtils.isEmpty(costAccDto.getPayDetails()) ) {
      throw new Exception(String.format("联合核算,明细11 sql没有取到支付数据, sql: %s; mainId:%s", sql, mainId));
    }

    return costAccDto;
  }

  private static String getLocationName(String locationId){
    switch (locationId){
      case "0":
        return "深圳";
      case "1":
        return "上海";
      case "2":
        return "北京";
      case "3":
        return "南京";
      default:
        return "未知:"+locationId;
    }
  }

  /**
   * 联合报销 预算算接口调用
   *
   * @param requestId 流程id
   * @param status 预算状态
   * @author k1810012
   */
  public static String doBudgetCommit4Union(String requestId, String status) {
    HeadBxBudgetCommand command = new HeadBxBudgetCommand();
    try {
      if (BudgetNodeType.REJECT.getValue().equalsIgnoreCase(status)) {
        String reject = command.reject(requestId);
        //废弃后更新发票关联关系: uf_pjxxgl 浪潮
        BizUtils bizUtils = new BizUtils();
        bizUtils.cancelInvLink(requestId);
        return reject;
      } else if (BudgetNodeType.FINISH.getValue().equalsIgnoreCase(status)) {
        return command.finish(requestId);
      } else {
        return "预算状态错误";
      }
    } catch (Exception e) {
      new BaseBean().writeLog("doBudgetCommit4Union 预算接口调用异常: " + e.getMessage());
      return "预算失败";
    }
  }

  /**
   * 联合付款 预算算接口调用
   *
   * @param requestId 流程id
   * @param status 预算状态
   * @author k1810012
   */
  public static String doBudgetCommit4UnionFk(String requestId, String status) {
    HeadPaymentBudgetCommand command = new HeadPaymentBudgetCommand();
    try {
      if (BudgetNodeType.REJECT.getValue().equalsIgnoreCase(status)) {
        String reject = command.reject(requestId);
        //废弃后更新发票关联关系: uf_pjxxgl 浪潮
        BizUtils bizUtils = new BizUtils();
        bizUtils.cancelInvLink(requestId);
        return reject;
      } else if (BudgetNodeType.FINISH.getValue().equalsIgnoreCase(status)) {
        return command.finish(requestId);
      } else {
        return "预算状态错误";
      }
    } catch (Exception e) {
      new BaseBean().writeLog("doBudgetCommit4UnionFk 预算接口调用异常: " + e.getMessage());
      return "预算失败";
    }
  }
}
