package com.kingdee.shr.compensation.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.lang3.ObjectUtils;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.compensation.CalSchemeInfo;
import com.kingdee.shr.compensation.app.formula.SalaryCalFunction;
import com.kingdee.shr.compensation.app.formula.data.Tools;




/**
 * 函数二开
 * @author coyle
 * 202505
 */
public class CalFunctionServiceExt extends SalaryCalFunction {



	/**
	 * 水电费取数
	 * @param type
	 * @param paramMap
	 * @param tempMap
	 * @param calScheme
	 * @param mainTableRowFilter
	 * @return
	 */
	public double getWaterOrElectPay(String type, Map paramMap, HashMap tempMap, CalSchemeInfo calScheme, String mainTableRowFilter) {
		Context ctx = Tools.getInstance().getCtx();
		String key = "getWaterOrElectPay" + calScheme.getNumber() + calScheme.getPeriodYear() + calScheme.getPeriodMonth()+type;
		Map<String, Double> dataMap = new  HashMap<String, Double>();
		String personId = paramMap.get("T_HR_SCMPCALTABLE_FPERSONID") == null ? null : paramMap.get("T_HR_SCMPCALTABLE_FPERSONID").toString();
		BigDecimal amt = BigDecimal.ZERO;
		if (personId == null) return 0.0;
		if (null == tempMap ||  ObjectUtils.isEmpty(tempMap.get(key))) {
			String sqlStr = getPerformanceDataSql(personId, mainTableRowFilter, calScheme);
			try {

				IRowSet rowSet = DbUtil.executeQuery(ctx, sqlStr);
				while (rowSet.next()) {
					String sqlPerson = rowSet.getString("cFPersonId");
					// 处理可能的null值，默认为BigDecimal.ZERO
					BigDecimal wamt = rowSet.getBigDecimal("wamt") == null ? BigDecimal.ZERO : rowSet.getBigDecimal("wamt");
					BigDecimal spwamt = rowSet.getBigDecimal("spwamt") == null ? BigDecimal.ZERO : rowSet.getBigDecimal("spwamt");
					BigDecimal eamt = rowSet.getBigDecimal("eamt") == null ? BigDecimal.ZERO : rowSet.getBigDecimal("eamt");
					BigDecimal speamt = rowSet.getBigDecimal("speamt") == null ? BigDecimal.ZERO : rowSet.getBigDecimal("speamt");

					if (StringUtils.equals("1", type)) {
						amt = wamt.add(spwamt);
					} else if (StringUtils.equals("2", type)) {
						amt = eamt.add(speamt);
					} else {
						amt = wamt.add(spwamt).add(eamt).add(speamt);
					}

					// 设置两位小数并四舍五入
					amt = amt.setScale(2, RoundingMode.HALF_UP);
					// 转换为double类型
					double amtDouble = amt.doubleValue();
					dataMap.put(sqlPerson + "_" + type, amtDouble);
				}
			} catch (BOSException | SQLException e) {
				e.printStackTrace();
			}
			tempMap.put(key, dataMap);
		}
		
		dataMap = (  Map<String, Double>) tempMap.get(key);
		return dataMap.get(personId + "_" + type) == null ? 0.00 : dataMap.get(personId + "_" + type);
	}








	/**
	 * 取数sql
	 * @param personId
	 * @param mainTableRowFilter
	 * @param calScheme
	 * @return
	 */
	private String getPerformanceDataSql(String personId, String mainTableRowFilter,  CalSchemeInfo calScheme){
		//mainTableRowFilter 格式：t_hr_scmpcaltable.fid in (select FID from T_HR_SCmpCalTable where FCalState in (1,2,3,4,5,6,7)
		//and FID in (select * from VTZD0RDVX15O2LMJ0F0TWRZ7UYW8YKVSD8D))
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("SELECT cFPersonId, ");
		sqlStr.append("       SUM(wamt)  AS wamt, ");
		sqlStr.append("       SUM(eamt)  AS eamt, ");
		sqlStr.append("       SUM(spwamt)  AS spwamt, ");
		sqlStr.append("       SUM(speamt)  AS speamt ");
		sqlStr.append("FROM ( ");

		// 第一部分：普通表数据（CT_WOE_WaterElectricity）
		sqlStr.append("    SELECT defu.cFPersonId, ");
		sqlStr.append("           defu.cfmonthWaterAmount AS wamt, ");
		sqlStr.append("           defu.cfmonthElectricityAmount AS eamt, ");
		sqlStr.append("           0 AS spwamt, ");  // 普通表无特殊字段，设为0（方便SUM）
		sqlStr.append("           0 AS speamt ");
		sqlStr.append("    FROM CT_WOE_WaterElectricity defu ");
		sqlStr.append("    WHERE ");
		if (null == mainTableRowFilter) {
			sqlStr.append("        defu.cFPersonId = '").append(personId).append("' ");
		} else {
			sqlStr.append("        defu.cFPersonId IN (SELECT FPersonId FROM t_hr_scmpcaltable ");
			sqlStr.append("                          WHERE ").append(mainTableRowFilter).append(") ");
		}
		sqlStr.append("    AND defu.CFYearMonth = '").append(calScheme.getPeriodYear()).append("-").append(String.format("%02d", calScheme.getPeriodMonth())).append("' ");
		sqlStr.append("    AND defu.fbillstate = '0' ");

		sqlStr.append("    UNION ALL ");

		// 第二部分：特殊表数据（CT_WOE_WaterElectricitySpecial）
		sqlStr.append("    SELECT special.CFPersonId, ");
		sqlStr.append("           0 AS wamt, ");  // 特殊表无普通字段，设为0（方便SUM）
		sqlStr.append("           0 AS eamt, ");
		sqlStr.append("           special.CFMonthWaterAmount AS spwamt, ");
		sqlStr.append("           special.CFelectricityTotalCost AS speamt ");
		sqlStr.append("    FROM CT_WOE_WaterElectricitySpecial special ");
		sqlStr.append("    WHERE ");
		if (null == mainTableRowFilter) {
			sqlStr.append("        special.CFPersonID = '").append(personId).append("' ");
		} else {
			sqlStr.append("        special.CFPersonID IN (SELECT FPersonId FROM t_hr_scmpcaltable ");
			sqlStr.append("                              WHERE ").append(mainTableRowFilter).append(") ");
		}
		sqlStr.append("    AND special.CFYearMonth = '").append(calScheme.getPeriodYear()).append("-").append(String.format("%02d", calScheme.getPeriodMonth())).append("' ");
		sqlStr.append("    AND special.fbillstate = '0' ");

		sqlStr.append(") combined_data ");  // 子查询别名
		sqlStr.append("GROUP BY cFPersonId ");  // 按人员ID分组汇总

		return sqlStr.toString();
	}

}
