package nc.ui.hr.baod_orders.action;

import java.awt.event.ActionEvent;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.format.DateTimeFormatter;

import com.alibaba.fastjson.JSONObject;

import nc.bs.framework.common.NCLocator;
import nc.hr.utils.SpecialDataUtil;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.UIRefPane;
import nc.ui.pubapp.uif2app.actions.AbstractReferenceAction;
import nc.ui.uif2.NCAction;
import nc.ui.uif2.editor.BillForm;
import nc.ui.uif2.model.AbstractAppModel;
import nc.ui.uif2.model.AbstractUIAppModel;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
public class CalculationAction extends NCAction{

	private static final long serialVersionUID = 4674049033067277460L;
	private AbstractUIAppModel model;
	public BillForm editor;
	
	private IUAPQueryBS bs = NCLocator.getInstance().lookup(IUAPQueryBS.class);
	private SimpleDateFormat inputFormat = new  SimpleDateFormat("yyyy-MM");
	private SimpleDateFormat sdf = new  SimpleDateFormat("yyyy-MM-dd");
	private SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
	
	public CalculationAction() {
		this.setCode("calculationAction");
		this.setBtnName("计算");
	}
	
	public BillForm getEditor() {
		return editor;
	}

	public void setEditor(BillForm editor) {
		this.editor = editor;
	}
	
	public AbstractUIAppModel getModel() {
		return this.model;
	}

	public void setModel(AbstractUIAppModel model) {
		this.model = model;
		this.model.addAppEventListener(this);
	}
	
	@Override
	public void doAction(ActionEvent e) throws Exception {
		//停止编辑
		editor.getBillCardPanel().stopEditing();
		//校验必填项
		editor.getBillCardPanel().dataNotNullValidate();
		// 获取当前员工号主键
		String clerkcode = (String) editor.getBillCardPanel().getHeadItem("clerkcode").getValueObject();
		//本次保底周期内请假工作天数
		UFDouble leave_days = new UFDouble(editor.getBillCardPanel().getHeadItem("leave_days").getValueObject().toString());
		//本次保底周期内完成工作天数
		UFDouble work_days = new UFDouble(editor.getBillCardPanel().getHeadItem("work_days").getValueObject().toString());
		//保底合同周期计薪天数
		UFDouble def9 = new UFDouble(editor.getBillCardPanel().getHeadItem("def9").getValueObject().toString());
 		//原保底金额万元
		UFDouble amountBefore = new UFDouble(editor.getBillCardPanel().getHeadItem("def11").getValueObject().toString());
		//保底编辑后金额
		UFDouble amountAfter =  (UFDouble) editor.getBillCardPanel().getHeadItem("bdamount").getValueObject();
		if(amountAfter.compareTo(amountBefore) == 1) {
			ExceptionUtils.wrappBusinessException("不可大于系统登记的保底金额");
		}

		//本次保底周期内工作日天数占比
	 	UFDouble days_ratio = new UFDouble(UFDouble.ZERO_DBL);
		//请假工作天数参与保底计算方案
		String scheme =  (String) editor.getBillCardPanel().getHeadItem("scheme").getValueObject();
		//本次保底金额(按工作天数折算）
		UFDouble this_amount = new  UFDouble(UFDouble.ZERO_DBL);
		//本次保底周期内工作日天数占比=IF(本次保底周期内请假工作天数（含带薪假期）<22,IF(选择请假工作天数参与保底计算方案=1,
		//(本次保底周期内请假工作天数（含带薪假期）+本次保底周期内完成工作天数)/保底合同周期计薪天数,本次保底周期内完成工作天数/保底合同周期计薪天数),本次保底周期内完成工作天数/保底合同周期计薪天数)
		if (leave_days.compareTo(new UFDouble(22)) == -1) {
			if ("1".equals(scheme)) {
				days_ratio = (leave_days.add(work_days)).div(def9);
			} else {
				days_ratio = work_days.div(def9);
			}
		} else {
			days_ratio = work_days.div(def9);
		}
		//本次保底金额(按工作天数折算） =IF(本次保底周期内请假工作天数（含带薪假期）<23,保底金额（元/年）*本次保底周期内工作日天数占比*(261-work_days)/261,保底金额（元/年）*本次保底周期内工作日天数占比
		//if (leave_days.compareTo(new UFDouble(23)) == -1) {
		//	this_amount = amountAfter.multiply(days_ratio).multiply((worksky.sub(work_days))).div(261);
		//}else {
			this_amount = amountAfter.multiply(days_ratio);
		//}
		
		editor.getBillCardPanel().setHeadItem("this_amount", this_amount);
		//转换成百分比保留一位小数
		DecimalFormat df = new DecimalFormat("0.0");
		String result = df.format(days_ratio.multiply(100).doubleValue());
		editor.getBillCardPanel().setHeadItem("days_ratio",result+"%");
		//已发薪资固定收入（月薪）
		UFDouble yfmonthly_pay = new UFDouble(UFDouble.ZERO_DBL);
		//待发薪资固定收入（月薪）
		UFDouble attrname = new UFDouble(UFDouble.ZERO_DBL);
		//本次保底开始周期
		UFDate start_cycle = (UFDate) editor.getBillCardPanel().getHeadItem("start_cycle").getValueObject();
		Date start_cycles = sdf.parse(start_cycle.toString());
		//本次保底截止周期
		UFDate finish_cycle = (UFDate) editor.getBillCardPanel().getHeadItem("finish_cycle").getValueObject();
		Date finish_cycles = sdf.parse(finish_cycle.toString());

		//获取2022年以外薪资数据
		List<Map<String,String>> salaryListMap = getSalary(clerkcode,SpecialDataUtil.getDateIntervalsql("N",start_cycles, finish_cycles));
		List<Map<String, String>> yearSalaryListMap = getYearSalary(clerkcode,SpecialDataUtil.getDateIntervalsql("Y",start_cycles, finish_cycles));
		//将两个薪资数据组合成一个
		for (int i = 0; i < yearSalaryListMap.size(); i++) {
			salaryListMap.add(yearSalaryListMap.get(i));
		}
		//获取2022年薪资数据
		for (int i = 0; i < salaryListMap.size(); i++) {
			Map<String,String> map = new HashMap<String,String>();
			map = salaryListMap.get(i);
			JSONObject jsonObject = null;
			
			if(formatter.format(start_cycles).equals(map.get("wa_period"))) {
				//判断开始日期是否满月,不满按照那个月的实际工作时间/整月的工作时间*金额汇总
				if(start_cycle.getDay()!= 1) {
					//判断开始结束日期是否同年同月，Y结束日期=本次保底截止周期   N结束日期=本月最后一天
					if(start_cycle.getYear() == finish_cycle.getYear() && start_cycle.getMonth() == finish_cycle.getMonth()) {
						jsonObject = SpecialDataUtil.getWorkDaysn(start_cycles, finish_cycles, clerkcode);
					}else {
						Calendar cal = Calendar.getInstance();  
					    cal.setTime(start_cycles);
					    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));  
					    Date lastDayOfMonth = cal.getTime();  
					    jsonObject = SpecialDataUtil.getWorkDaysn(start_cycles, lastDayOfMonth, clerkcode);
					}
					
					JSONObject data = jsonObject.getJSONObject("data");
					UFDouble thiswork_days = new UFDouble(data.getString("workday"));
					UFDouble beginday = new UFDouble(data.getString("beginday"));
					yfmonthly_pay = yfmonthly_pay.add(thiswork_days.div(beginday).multiply(new UFDouble(String.valueOf(map.get("amount")))));
					continue;
				}
			}
			if(formatter.format(finish_cycles).equals(map.get("wa_period"))) {
				UFDouble salary = new UFDouble(String.valueOf(map.get("amount")));
				//判断截止日期是否满月,不满按照那个月的实际工作时间/整月的工作时间*金额汇总
				if(finish_cycle.getDay() != finish_cycle.getDaysMonth()) {
					//判断开始结束日期是否同年同月，Y开始日期=本次保底开始周期   N开始日期=本月第一天
					if(start_cycle.getYear() == finish_cycle.getYear() && start_cycle.getMonth() == finish_cycle.getMonth()) {
						jsonObject = SpecialDataUtil.getWorkDaysn(start_cycles, finish_cycles, clerkcode);	
					}else {
						//设置对应月份的第一天
						Calendar cal = Calendar.getInstance();    
						cal.setTime(finish_cycles);
						cal.set(Calendar.DAY_OF_MONTH, 1); 
						Date firstDayOfMonth = cal.getTime(); 
						jsonObject = SpecialDataUtil.getWorkDaysn(firstDayOfMonth, finish_cycles, clerkcode);	
					}
					
					JSONObject data = jsonObject.getJSONObject("data");
					UFDouble thiswork_days = new UFDouble(data.getString("workday"));
					UFDouble endday = new UFDouble(data.getString("endday"));
					UFDouble beginday = new UFDouble(data.getString("beginday"));
					//endday等于0表示开始日期和截止日期为同一年同一月，本次保底已发薪资为0,不等于除以截止日期的工作日得出待发薪资
					if(endday.compareTo(UFDouble.ZERO_DBL) == 0) {
						attrname = thiswork_days.div(beginday).multiply(salary);
					}
				}else {
					attrname = salary;
				}
				continue;
			}
		
			
			//到这表示为开始周期-截止周期中间月份，开始日期和结束日期对应对接月份第一天和月份最后一天
//			if(!formatter.format(start_cycles).equals(map.get("wa_period")) && !formatter.format(finish_cycles).equals(map.get("wa_period"))) {
				 Date wa_period = formatter.parse(map.get("wa_period"));  
				//设置对应月份的第一天
				Calendar cal = Calendar.getInstance();    
				cal.setTime(wa_period);
				cal.set(Calendar.DAY_OF_MONTH, 1); 
				Date firstDayOfMonth = cal.getTime(); 
				
				Calendar cals = Calendar.getInstance();  
				cals.setTime(wa_period);  
				cals.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));  
			    Date lastDayOfMonth = cals.getTime(); 
//				jsonObject = SpecialDataUtil.getWorkDaysn(firstDayOfMonth, lastDayOfMonth, clerkcode);
//				JSONObject data = jsonObject.getJSONObject("data");
//				UFDouble thiswork_days = new UFDouble(data.getString("workday"));
//				UFDouble beginday = new UFDouble(data.getString("beginday"));
//				yfmonthly_pay = yfmonthly_pay.add(thiswork_days.div(beginday).multiply(salaryDispose(map)));
				yfmonthly_pay = yfmonthly_pay.add(new UFDouble(String.valueOf(map.get("amount"))));
//			}
		}
		
		
		editor.getBillCardPanel().setHeadItem("yfmonthly_pay", yfmonthly_pay);
		//已发奖金工作开始日期
		UFDate  def7 = (UFDate) editor.getBillCardPanel().getHeadItem("def7").getValueObject();
		Date def7s = sdf.parse(def7.toString());
		//已发奖金工作结束日期
		UFDate def8 = (UFDate) editor.getBillCardPanel().getHeadItem("def8").getValueObject();
		Date def8s = sdf.parse(def8.toString());
		//奖金期间
		UIRefPane ref = (UIRefPane)editor.getBillCardPanel().getHeadItem("def6").getComponent();
		String[] def6s = ref.getRefPKs();
		//奖金工作开始日期对应实际工作天数
		UFDouble workDay = new UFDouble(SpecialDataUtil.getWorkDaysn(def7s, def8s, clerkcode).getJSONObject("data").getString("workday"));
		//本次保底周期内实际工作天数-奖金工作周期和保底周期有交集的工作天数
		UFDouble practicalWorkDay = new UFDouble(SpecialDataUtil.DateIntersection(start_cycles, finish_cycles, def7s, def8s, clerkcode));
		//换算
		UFDouble vchangerate = new UFDouble(UFDouble.ZERO_DBL);
		
		//奖金工作开始日期对应实际工作天数如果等于0天，换算率默认0
		if(workDay.compareTo(vchangerate) != 0){
			vchangerate = practicalWorkDay.div(workDay);
		}
		 
		Map<String,UFDouble> paidBonusMap = getpaidBonus(clerkcode, def6s,vchangerate);
		//已发薪资设计奖金
		UFDouble yfdesign_bonus = paidBonusMap.get("designbonus");
		//已发薪资市场费
		UFDouble yfmarket_bonus = paidBonusMap.get("marketbonus");
		//已发薪资本期所级管理团队奖金（含本期已发放管理预发奖金，含本期所级缓发奖金）
		UFDouble yfteam_bonus = paidBonusMap.get("thismanagebonus");
		//已发薪资本期已发放管理预发奖金
		UFDouble yfpredict_bonus = paidBonusMap.get("yfpredict_bonus");
		//已发薪资大客户经理服务费
		UFDouble yfservice_charge = paidBonusMap.get("servicebonus");
		//已发薪资管理费补贴奖金合计
		UFDouble yfbonus_total = paidBonusMap.get("awardsbonus");
		//已发薪资二线职能管理奖金
		UFDouble yfmanage_bonus = new UFDouble(getManageBonus(clerkcode,def7s, def8s));
		
		editor.getBillCardPanel().setHeadItem("yfdesign_bonus", yfdesign_bonus);
		
		editor.getBillCardPanel().setHeadItem("yfmarket_bonus", yfmarket_bonus);
		
		editor.getBillCardPanel().setHeadItem("yfteam_bonus", yfteam_bonus);
		
		editor.getBillCardPanel().setHeadItem("yfpredict_bonus", yfpredict_bonus);
		
		editor.getBillCardPanel().setHeadItem("yfservice_charge", yfservice_charge);
		
		editor.getBillCardPanel().setHeadItem("yfbonus_total", yfbonus_total);
		
		editor.getBillCardPanel().setHeadItem("yfmanage_bonus", vchangerate.multiply(yfmanage_bonus));
		Map<Object,Object> Compensationmap = getPendingBonus(clerkcode, inputFormat.format(finish_cycles));
		//待发薪资设计奖金
		UFDouble dfdesign_bonus = new UFDouble(String.valueOf(Compensationmap.get("designbonus")));
		//待发薪资市场费
		UFDouble dfmarket_bonus = new UFDouble(String.valueOf(Compensationmap.get("marketbonus")));
		//待发薪资本期所级管理团队奖金（含本期已发放管理预发奖金，含本期所级缓发奖金）
		UFDouble dfteam_bonus = new UFDouble(String.valueOf(Compensationmap.get("thismanagebonus")));
		//待发薪资大客户经理服务费
		UFDouble dfservice_charge = new UFDouble(String.valueOf(Compensationmap.get("servicebonus")));
		//待发薪资管理费补贴奖金合计
		UFDouble dfbonus_total = new UFDouble(String.valueOf(Compensationmap.get("awardsbonus")));
		//待发薪资二线职能管理奖金
		UFDouble dfmanage_bonus = (UFDouble) editor.getBillCardPanel().getHeadItem("dfmanage_bonus").getValueObject();
		editor.getBillCardPanel().setHeadItem("attrname", attrname);
		
		editor.getBillCardPanel().setHeadItem("dfdesign_bonus", dfdesign_bonus);
   	 
		editor.getBillCardPanel().setHeadItem("dfmarket_bonus", dfmarket_bonus);
   	 	
		editor.getBillCardPanel().setHeadItem("dfteam_bonus", dfteam_bonus);
   	 	
		editor.getBillCardPanel().setHeadItem("dfservice_charge", dfservice_charge);
   	 	
		editor.getBillCardPanel().setHeadItem("dfbonus_total", dfbonus_total);
		
		
		//本次保底补贴金额
		UFDouble subsidy_mount = this_amount.sub(yfmonthly_pay).sub(yfdesign_bonus).sub(yfmarket_bonus)
				.sub(yfteam_bonus).sub(yfpredict_bonus).sub(yfservice_charge).sub(yfbonus_total).sub(yfmanage_bonus)
				.sub(attrname).sub(dfdesign_bonus).sub(dfmarket_bonus).sub(dfteam_bonus).sub(dfservice_charge).sub(dfbonus_total).sub(dfmanage_bonus);
		editor.getBillCardPanel().setHeadItem("subsidy_mount",subsidy_mount);
		//本保底周期内收入合计
		UFDouble income_total = yfmonthly_pay.add(yfdesign_bonus).add(yfmarket_bonus)
				.add(yfteam_bonus).add(yfpredict_bonus).add(yfservice_charge).add(yfbonus_total).add(yfmanage_bonus)
				.add(attrname).add(dfdesign_bonus).add(dfmarket_bonus).add(dfteam_bonus).add(dfservice_charge).add(dfbonus_total).add(dfmanage_bonus).add(subsidy_mount);
		editor.getBillCardPanel().setHeadItem("income_total",income_total);
		//本次待发放薪资金额合计
		UFDouble mount_total = dfdesign_bonus.add(dfmarket_bonus).add(dfteam_bonus).add(dfbonus_total).add(dfmanage_bonus);
		editor.getBillCardPanel().setHeadItem("mount_total",mount_total);
		MessageDialog.showHintDlg(null, "提示", "计算完成！");
	}
	//查询人员对应薪资
	public List<Map<String,String>> getSalary(String clerkcode,String salarysql) throws BusinessException{
		   StringBuffer sql = new StringBuffer();
		   sql.append("select ");
		   sql.append("\"基本工资\" +");
		   sql.append("\"预发设计费\" +");
		   sql.append("\"岗位补贴\" +");
		   sql.append("\"资质补贴\"+");
		   sql.append("\"预发待扣\" +");
		   sql.append("\"病假扣款（扣公司补贴）\" +");
		   sql.append("\"病假扣款（扣基本工资）\" +");
		   sql.append("\"病假扣款（扣预发待扣）\" +");
		   sql.append("\"病假扣款（扣预发奖金）\" +");
		   sql.append("\"产假扣款（扣公司补贴）\" +");
		   sql.append("\"产假扣款（扣基本工资）\" +");
		   sql.append("\"产假扣款（扣预发待扣）\" +");
		   sql.append("\"产假扣款（扣预发奖金）\" +");
		   sql.append("\"事假扣款（扣公司补贴）\" as amount,");
		   sql.append("WA_PERIOD");
		   sql.append(" from");
		   sql.append(" v_classify_salary_0410 where pk_psndoc ='"+clerkcode+"' ");
		   sql.append(" and WA_PERIOD"+salarysql);
		return  (List<Map<String, String>>) bs.executeQuery(sql.toString(), new MapListProcessor());
	   }
	   
	   
	 //查询人员对应薪资-只限于2022年
	   public List<Map<String,String>> getYearSalary(String clerkcode,String salarysql) throws BusinessException{
		   StringBuffer sql = new StringBuffer();
		   sql.append("SELECT");
		   sql.append(" TO_CHAR( query_year_month, 'YYYYMM' ) AS WA_PERIOD,");
		   sql.append(" sum( amount ) AS amount ");
		   sql.append(" FROM");
		   sql.append(" EMPLOYEE_SALARY_PRIM2023");
		   sql.append(" WHERE");
		   sql.append(" EMPLOYEE_NAME = (select name from bd_psndoc where pk_psndoc ='"+clerkcode+"')");
		   sql.append(" AND TO_CHAR( query_year_month, 'YYYYMM' )"+salarysql);
		   sql.append(" AND cost_category <> '其他公司管理费用'");
		   sql.append(" GROUP BY TO_CHAR( query_year_month, 'YYYYMM' )");
		   return  (List<Map<String, String>>) bs.executeQuery(sql.toString(), new MapListProcessor());
	   }
	   
	   //查询人员对应本次待发薪资奖金信息
	   public Map<Object,Object> getPendingBonus(String clerkcode,String bonusperiod) throws BusinessException{
		   String sql = "SELECT designbonus,marketbonus,thismanagebonus,servicebonus,awardsbonus FROM THSJ.v_nc_bdbcfzx@THSJ_PM_DBLINK where psndoc_id ='"+clerkcode+"' "
		   		+ "and bonusperiod ='"+bonusperiod+"-01' and isgranted ='N'";
		   Map<Object, Object> pendingBonus = (Map<Object, Object>) bs.executeQuery(sql.toString(), new MapProcessor());
		   if(pendingBonus == null) {
			   Map<Object, Object> map = new HashMap<Object, Object>();
			   map.put("designbonus", 0);
			   map.put("marketbonus", 0);
			   map.put("thismanagebonus", 0);
			   map.put("servicebonus", 0);
			   map.put("awardsbonus", 0);
			   pendingBonus = map;
		   }
	   		return pendingBonus;
	   }
	   
	   //查询已发奖金并折算
	   public Map<String,UFDouble> getpaidBonus(String clerkcode,String[] def6s,UFDouble vchangerate) throws BusinessException {
		   //设计奖金
		   UFDouble designbonus = new UFDouble(UFDouble.ZERO_DBL);
		   //市场费
		   UFDouble marketbonus = new UFDouble(UFDouble.ZERO_DBL);
		   //本期所级管理团队奖金(含本期已发放管理预发奖金，含本期所级缓发奖金)
		   UFDouble thismanagebonus = new UFDouble(UFDouble.ZERO_DBL);
		   //本期已发放管理预发奖金
		   UFDouble yfpredict_bonus  = new UFDouble(UFDouble.ZERO_DBL);
		   //大客户经理服务费
		   UFDouble servicebonus = new UFDouble(UFDouble.ZERO_DBL);
		   //管理费补贴一线人员奖金
		   UFDouble awardsbonus = new UFDouble(UFDouble.ZERO_DBL);
		   
		   StringBuffer defdocsql = new StringBuffer();
		   defdocsql.append("SELECT");
		   defdocsql.append(" code");
		   defdocsql.append(" FROM");
		   defdocsql.append(" bd_defdoc");
		   defdocsql.append(" WHERE");
		   defdocsql.append(" pk_defdoclist = ( SELECT pk_defdoclist FROM bd_defdoclist WHERE code = 'HR0030')");
		   defdocsql.append(" AND pk_defdoc IN (");
		   for (int i = 0; i < def6s.length; i++) {
			   if(i == def6s.length-1) {
				   defdocsql.append("'"+def6s[i]+"')");
				}else {
					defdocsql.append("'"+def6s[i]+"',");
				}
		   }
		   List<String> defdiclist = (List<String>) bs.executeQuery(defdocsql.toString(), new ColumnListProcessor());
		   StringBuffer sql = new StringBuffer();
		   sql.append("SELECT");
		   sql.append("	bonusperiod,");
		   sql.append(" designbonus,");
		   sql.append("	marketbonus,");
		   sql.append(" thismanagebonus,");
		   sql.append(" servicebonus,");
		   sql.append(" awardsbonus");
		   sql.append(" FROM");
		   //sql.append(" v_nc_bdbcfzx");
		   sql.append(" THSJ.v_nc_bdbcfzx @THSJ_PM_DBLINK");
		   sql.append(" WHERE");
		   sql.append(" psndoc_id = '"+clerkcode+"'");
		   sql.append(" AND bonusperiod IN (");
		   for (int i = 0; i < defdiclist.size(); i++) {
			   if(i == defdiclist.size()-1) {
				   sql.append("'"+defdiclist.get(i)+"-01')");
				}else {
					sql.append("'"+defdiclist.get(i)+"-01',");
				}
		   }
		   sql.append(" AND isgranted = 'Y'");
		   List<Map<String, String>> listmap = (List<Map<String, String>>) bs.executeQuery(sql.toString(), new MapListProcessor());
		   
		   
		   for (int i = 0; i < defdiclist.size(); i++) {
			   String bonusperiod = defdiclist.get(i)+"-01";
			   for (int j = 0; j < listmap.size(); j++) {
				   Map<String,String> map = listmap.get(j);
				   if(bonusperiod.equals(map.get("bonusperiod"))) {
					   UFDouble designmoney = new UFDouble(String.valueOf(map.get("designbonus")));
					   UFDouble marketmoney = new UFDouble(String.valueOf(map.get("marketbonus")));
					   UFDouble thismanagemoney = new UFDouble(String.valueOf(map.get("thismanagebonus")));
					   UFDouble servicemoney = new UFDouble(String.valueOf(map.get("servicebonus")));
					   UFDouble awardsnmoney = new UFDouble(String.valueOf(map.get("awardsbonus")));
					   designbonus = designbonus.add(vchangerate.multiply(designmoney));
					   marketbonus = marketbonus.add(vchangerate.multiply(marketmoney));
					   thismanagebonus = thismanagebonus.add(vchangerate.multiply(thismanagemoney));
					   servicebonus = servicebonus.add(vchangerate.multiply(servicemoney));
					   awardsbonus = awardsbonus.add(vchangerate.multiply(awardsnmoney));
					   break;
				   }
			   }
		   }
		   
		   //查询本期已发放管理预发奖金
		   StringBuffer sqlpaymoney = new StringBuffer();
		   sqlpaymoney.append("SELECT");
		   sqlpaymoney.append(" costpaydate,");
		   sqlpaymoney.append(" paymoney");
		   sqlpaymoney.append("	FROM");
		   sqlpaymoney.append(" THSJ.v_nc_bdbcyfdk @THSJ_PM_DBLINK");
		   sqlpaymoney.append(" WHERE");
		   sqlpaymoney.append(" psndoc_id = '"+clerkcode+"'");
		   //sqlpaymoney.append(" psndoc_id = '0001A110000000009T6K'");
		   sqlpaymoney.append(" AND costpaydate IN (");
		   for (int i = 0; i < defdiclist.size(); i++) {
			   if(i == defdiclist.size()-1) {
				   sqlpaymoney.append("'"+defdiclist.get(i)+"')");
				}else {
					sqlpaymoney.append("'"+defdiclist.get(i)+"',");
				}
		   }
		   List<Map<String, String>> bdbcyfdklistmap = (List<Map<String, String>>) bs.executeQuery(sqlpaymoney.toString(), new MapListProcessor());
		   for (int i = 0; i < defdiclist.size(); i++) {
			   String bonusperiod = defdiclist.get(i);
			   for (int j = 0; j < bdbcyfdklistmap.size(); j++) {
				   Map<String,String> map = bdbcyfdklistmap.get(j);
				   if(bonusperiod.equals(map.get("costpaydate"))) {
					   UFDouble paymoney = new UFDouble(String.valueOf(map.get("paymoney")));
					   yfpredict_bonus = yfpredict_bonus.add(vchangerate.multiply(paymoney));
					   break;
				   }
			   }
		   }
		   
		   
		   
		   Map<String,UFDouble> paidBonusMap = new HashMap<String,UFDouble>();
		   paidBonusMap.put("designbonus", designbonus);
		   paidBonusMap.put("marketbonus", marketbonus);
		   paidBonusMap.put("thismanagebonus", thismanagebonus);
		   //本期已发放管理预发奖金因为负数
		   paidBonusMap.put("yfpredict_bonus", yfpredict_bonus.multiply(-1));
		   paidBonusMap.put("servicebonus", servicebonus);
		   paidBonusMap.put("awardsbonus", awardsbonus);
		   return paidBonusMap;
	   }
	   
	   //查询人员对应的二线职能管理奖金
	   public String getManageBonus(String pk_id,Date begindate,Date enddate)throws BusinessException{
		   String orgname = (String) editor.getBillCardPanel().getHeadItem("def1").getValueObject();
		   String deptname = (String) editor.getBillCardPanel().getHeadItem("deptname").getValueObject();
		   String postname = (String) editor.getBillCardPanel().getHeadItem("postname").getValueObject();
		   StringBuffer sql = new StringBuffer();
		   sql.append("select sum(function_bonus) as function_bonus from th_bonus where vdef1 in (select clerkcode from hi_psnjob where pk_psndoc ='"+pk_id+"') and dr = 0");
		   if(orgname != null) {
			   sql.append(" and cost_corp ='"+orgname+"'");
		   }else {
			   sql.append(" and cost_corp is  null");
		   }
		   if(deptname != null) {
			   sql.append(" and cost_dept = '"+deptname+"'");
		   }else {
			   sql.append(" and cost_dept is  null");
		   }
		   if(postname != null) {
			   sql.append(" and postname = '"+postname+"'");
		   }else {
			   sql.append(" and postname is  null");
		   }
		   sql.append(" and (workcycle_begin <= '"+sdf.format(enddate)+"' AND workcycle_end >= '"+sdf.format(begindate)+"')");
		   Object function_bonus = (Object) bs.executeQuery(sql.toString(), new ColumnProcessor());
		   if(function_bonus == null) {
			   function_bonus = "0";
		   }
		   return function_bonus.toString();
	   }
}
