package com.engine.htsc.payment.service.impl;

import com.engine.core.impl.Service;
import com.engine.htsc.payment.dao.BudgetDao;
import com.engine.htsc.payment.service.BudgetService;
import com.engine.htsc.payment.util.PayUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * @author K1810012
 * 预算 业务实现
 */
public class BudgetServiceImpl extends Service implements BudgetService {

  private final Log log = LogFactory.getLog(PaymentServiceImpl.class.getName());
  private final BudgetDao budgetDao = new BudgetDao();
  private final PropBean pp = new PropBean();

  @Override
  public boolean doBudgetMiddleTable(String requestMark, String billStatus, String fbizdate, String budgetKmTable, String mainTable, boolean isIt) {
    log.info("付款流程,预算中间表更新\n  @requestMark=" + requestMark + ",billStatus=" + billStatus +
            ",budgetKmTable=" + budgetKmTable + "@");
    if (StringUtils.isBlank(requestMark) || StringUtils.isBlank(billStatus) || StringUtils.isBlank(budgetKmTable)) {
      log.info("更新失败,原因:流程编号或单据状态为空");
      return false;
    }
    try {
      //预算中间表外部数据源
      String budgetTableName = pp.getPropName("BudgetTableName");
      String nameIsExist = budgetDao.fNameIsExist(budgetTableName, requestMark);
      log.info("预算数据是否存在sql @" + nameIsExist + "@");
      RecordSetDataSource rsd = new RecordSetDataSource("BudgetRecords");
      rsd.execute(nameIsExist);
      if (rsd.next() && StringUtils.isNotBlank(requestMark)) {
        String deleteAll = String.format("delete from %s where FNAME='%s'",
                budgetTableName, requestMark);
        rsd.executeUpdateWithDatasource(deleteAll, "BudgetRecords");
        insertBudgetMiddleTable(requestMark, billStatus,fbizdate, budgetKmTable, mainTable, isIt, rsd);
        //				updateBudgetMiddleTable(requestMark, billStatus, budgetKmTable, mainTable, isIt, rsd);
      } else {
        insertBudgetMiddleTable(requestMark, billStatus,fbizdate, budgetKmTable, mainTable, isIt, rsd);
      }
      return true;
    } catch (Exception e) {
      log.info("更新失败,原因: catch exception: " + e);
      return false;
    }
  }

  //预算更新 在
  @Override
  public boolean dobugetModeUpdateYs(String requestId, String tableName) {
    log.info("付款流程修改建模状态！！！requestId:" + requestId + "tablename:" + tableName);
    if (StringUtils.isBlank(requestId) || StringUtils.isBlank(tableName)) {
      log.info("更新失败,原因:流程编号或单据状态为空");
      return false;
    }
    try {
      String sql = "update " + tableName + " set  tbdlcyszt=0 where requestid='" + requestId + "'";
      RecordSet rs = new RecordSet();
      return rs.execute(sql);
      //预算中间表外部数据源
		/*	String budgetTableName = pp.getPropName("BudgetTableName");
			String nameIsExist = budgetDao.fNameIsExist(budgetTableName, requestMark);
			log.info("预算数据是否存在sql @" + nameIsExist + "@");

			RecordSetDataSource rsd = new RecordSetDataSource("BudgetRecords");
			rsd.execute(nameIsExist);
			if (rsd.next()) {
				updateBudgetMiddleTable(requestMark, billStatus, budgetKmTable, mainTable, isIt, rsd);
			} else {
				insertBudgetMiddleTable(requestMark, billStatus, budgetKmTable, mainTable, isIt, rsd);
			}
				*/


    } catch (Exception e) {
      log.info("更新失败,原因: catch exception: " + e);
      return false;
    }
  }

  @Override
  public boolean insertBudgetMiddleTable(String requestMark, String billStatus,String fbizdate, String budgetKmTable, String mainTable, boolean isIt, RecordSetDataSource rsd) throws Exception {
    log.info("预算信息不存在，执行更新方法 insertBudgetMiddleTable\n @requestMark=" + requestMark + ",billStatus=" + billStatus + "@");
    Map<String, Object> budgetBody = getBudgetBody(requestMark, mainTable, budgetKmTable, isIt);
    List<Object> mainInfo = (List<Object>) budgetBody.get("main"); //主表数据
    List<List<Object>> dtInfo = (List<List<Object>>) budgetBody.get("dt"); //预算数据
    if (dtInfo.size() == 0) {
      log.info("插入预算表中止,因为科目信息为空");
      return false;
    }
    DateTimeFormatter dfOnlyYear = DateTimeFormatter.ofPattern("yyyy"); //年
    DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //当前操作时间
    try {
      String budgetTableName = new PropBean().getPropName("BudgetTableName");
      for (List<Object> singleValue : dtInfo) {
        List<Object> insertValues = new ArrayList<>();
        insertValues.add(billStatus);
        insertValues.addAll(mainInfo);
        insertValues.add(dfOnlyYear.format(LocalDateTime.now()));
        if(StringUtils.isNotEmpty(fbizdate)){
          insertValues.add(fbizdate);
        } else {
          insertValues.add(dfDateTime.format(LocalDateTime.now()));
        }
        insertValues.addAll(singleValue);
//				String budgetTableName = "T_BUD_BUDGETRECORDS";
        String insert = budgetDao.insertMiddleTable(budgetTableName);
        RecordSet recordSet = new RecordSet();
        recordSet.executeUpdateWithDatasource(insert, "BudgetRecords", insertValues);
      }
      return true;
    } catch (Exception e) {
      log.info("insertBudgetMiddleTable异常, [" + e + "]");
      return false;
    }
  }

  @Override
  public boolean updateBudgetMiddleTable(String requestMark, String billStatus, String budgetKmTable, String mainTable, boolean isIt, RecordSetDataSource rsd) throws Exception {
    log.info("预算信息已存在，执行更新方法 updateBudgetMiddleTable \n @requestMark=" + requestMark + ",billStatus=" + billStatus + "@");
    Map<String, Object> budgetBody = getBudgetBody(requestMark, mainTable, budgetKmTable, isIt);
    List<Object> mainInfo = (List<Object>) budgetBody.get("main"); //主表数据
    List<List<Object>> dtInfo = (List<List<Object>>) budgetBody.get("dt"); //预算数据
    if (dtInfo.size() == 0) {
      log.info("插入预算表中止,因为科目信息为空");
      return false;
    }
    DateTimeFormatter dfOnlyYear = DateTimeFormatter.ofPattern("yyyy"); //年
    DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //当前操作时间
    RecordSet rs = new RecordSet();
    try {
      for (List<Object> singleValue : dtInfo) {
        List<Object> insertValues = new ArrayList<>();
        insertValues.add(billStatus);
//				insertValues.add("0");
        insertValues.add(dfOnlyYear.format(LocalDateTime.now()));
        insertValues.add(dfDateTime.format(LocalDateTime.now()));
        insertValues.addAll(singleValue.subList(2, 8));
        insertValues.add(singleValue.get(0));
        insertValues.add(mainInfo.get(0));
        String budgetTableName = new PropBean().getPropName("BudgetTableName");
//				String budgetTableName = "T_BUD_BUDGETRECORDS";
        String update = budgetDao.updateMiddleTable(budgetTableName);
        RecordSet recordSet = new RecordSet();
        recordSet.executeUpdateWithDatasource(update, "BudgetRecords", insertValues);
      }
      return true;
    } catch (Exception e) {
      log.info("insertBudgetMiddleTable异常, [" + e + "]");
      return false;
    }
  }

  /**
   * 获取插入表中的数据
   *
   * @param requestMark 流程编号
   * @return map
   */
  private Map<String, Object> getBudgetBody(String requestMark, String main, String budgetKmTable, boolean isItFlag) throws Exception {
    Map<String, Object> res = new HashMap<>();
    log.info("付款流程表名: @" + main + "@");
    log.info("付款预算表名: @" + budgetKmTable + "@");
    RecordSet rs = new RecordSet();
    RecordSet rs1 = new RecordSet();
    String mainInfo = budgetDao.mainInfo(main, requestMark);
    rs.executeQuery(mainInfo);
    List<Object> mainValues = new ArrayList<>();
    String mainId = ""; //主副表关联id
    if (rs.next()) {
      mainValues.add(requestMark);
      mainValues.add(Util.null2String(rs.getString("REQUESTNAME"))); //流程编码
      mainValues.add(Util.null2String(rs.getString("LASTNAME"))); //拟稿人名称
      //mainValues.add(Util.null2String(rs.getString("DEPARTMENTCODE"))); //华泰部门code
      mainId = Util.null2String(rs.getString("ID"));
    }
    log.info("主表数据: @" + mainValues + "@");
    res.put("main", mainValues);

    String budgetKmTableInfo = budgetDao.budgetKmTableInfo(budgetKmTable, mainId, isItFlag);
    DepartmentComInfo dc = new DepartmentComInfo();
    rs.executeQuery(budgetKmTableInfo);
    List<List<Object>> allDtValues = new ArrayList<>(); //所有明细科目数据 add dtValues 单行明细科目数据
    while (rs.next()) {
      List<Object> dtValues = new ArrayList<>(); //单行明细科目数据
      String yskm = Util.null2String(rs.getString("YSKM")); //科目
      dtValues.add(yskm); //二级预算科目
      dtValues.add(PayUtil.superBudgetSubject(yskm)); //一级预算科目
      if (budgetKmTable.toLowerCase().contains("dt8")) {
        String FYSJCDBM = Util.null2String(rs.getString("FYSJCDBM"));
        String JSHJJE = Util.null2String(rs.getString("JSHJJE"));
        String BHSJE = Util.null2String(rs.getString("BHSJE"));
        String SJ = Util.null2String(rs.getString("SJ"));
        String CYS = Util.null2String(rs.getString("CYS"));
        String PROJECTCODE = Util.null2String(rs.getString("PROJECTCODE"));
        String XMMC = Util.null2String(rs.getString("XMMC"));
        if ("".equals(JSHJJE)) {
          dtValues.add(0.00); // 价税合计金额
        } else {
          dtValues.add(Double.parseDouble(JSHJJE)); // 价税合计金额
        }
        if ("".equals(BHSJE)) {
          dtValues.add(0.00); // 未税金额
        } else {
          dtValues.add(Double.parseDouble(BHSJE)); // 未税金额
        }

        if ("".equals(SJ)) {
          dtValues.add(0.00); //税金
        } else {
          dtValues.add(Double.parseDouble(SJ)); //税金
        }
        dtValues.add(0.00); // 实际报销金额
        dtValues.add(0.00); // 差旅标准金额
        dtValues.add(PayUtil.overWeight(CYS)); // 是否超标
        String isItPay = "否";
        rs1.executeQuery(budgetDao.isItPay(main, requestMark));
        if (rs1.next()) {
          if ("1".equals(Util.null2String(rs1.getString("FKLX")))) {
            isItPay = "是";
          }
        }
        dtValues.add(isItPay);
        dtValues.add(PROJECTCODE); // it项目编码
        dtValues.add(XMMC); // it项目名称
        dtValues.add(dc.getDepartmentCode(FYSJCDBM)); //取明细实际费用承担部门
      } else {
        String FYSJCDBM = Util.null2String(rs.getString("FYSJCDBM"));
        String JSHJJE = Util.null2String(rs.getString("rmbje")); // 人民币金额
        String PROJECTCODE = "";
        String XMMC = "";
        if ("".equals(JSHJJE)) {
          dtValues.add(0.00); // 价税合计金额
          dtValues.add(0.00); // 未税金额
        } else {
          dtValues.add(Double.parseDouble(JSHJJE)); // 价税合计金额
          dtValues.add(Double.parseDouble(JSHJJE)); // 未税金额
        }
        String CYS = Util.null2String(rs.getString("CYS"));
        dtValues.add(0.00); //税金
        dtValues.add(0.00); // 实际报销金额
        dtValues.add(0.00); // 差旅标准金额
        dtValues.add(PayUtil.overWeight(CYS)); // 是否超标
        dtValues.add("否");
        dtValues.add(PROJECTCODE); // it项目编码
        dtValues.add(XMMC); // it项目名称
        dtValues.add(dc.getDepartmentCode(FYSJCDBM)); //取明细实际费用承担部门

      }
      log.info("dtValues = " + dtValues);
      allDtValues.add(dtValues);
    }
    log.info("预算表数据" + budgetKmTable + "  @" + allDtValues + "@");
    res.put("dt", allDtValues);
    return res;
  }


}
