package com.kingdee.shr.compensation.web.handler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.shr.compensation.CalSchemeFactory;
import com.kingdee.shr.compensation.CalSchemeInfo;
import com.kingdee.shr.compensation.CmpSchemePersonFacadeFactory;
import com.kingdee.shr.compensation.CmpSchemePersonHasFacadeFactory;
import com.kingdee.shr.compensation.app.taxCal.TaxCalInitFacadeFactory;
import com.kingdee.shr.compensation.request.ParseRequestHelper;
import com.kingdee.shr.compensation.util.CmpStrUtil;
import com.kingdee.util.StringUtils;

/**
 * 核算向导--核算员工拓展
 * @author dengzhouhong
 * 202403
 */
public class CmpPersonHasDynamicListHandlerExt extends CmpPersonHasDynamicListHandler{

	private Logger logger = Logger.getLogger(CmpPersonHasDynamicListHandlerExt.class);
	/**
	 * 批量添加员工
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 * @throws SHRWebException
	 */
	public String immediateAddPersonAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException, BOSException, EASBizException {
		logger.error("into immediateAddPersonAction...");
		Map<String, Object> res = new HashMap();  
		Context ctx = SHRContext.getInstance().getContext();
		String permItemId = ParseRequestHelper.getRequestPermItemId(request);
		String scalid = ParseRequestHelper.getParameterByRequest(request, "cmpschemeid").toString();
		logger.error("into immediateAddPersonAction...permItemId:"+permItemId+";scalid="+scalid);
		CalSchemeInfo calScheme = CalSchemeFactory.getRemoteInstance().getCalSchemeInfo(new ObjectUuidPK(scalid));
		int calschemeYear = calScheme.getPeriodYear();
		int calschemeMonth = calScheme.getPeriodMonth();  //核算月份
		String year = calschemeYear+"";
		String mouth = "";
		if(calschemeMonth < 10){
			mouth = "0"+calschemeMonth;
		}else {
			mouth = calschemeMonth+"";
		}

		int time =  2;
		time = calScheme.getCalTime();
		String isDel = (String)ParseRequestHelper.getParameterByRequest(request,"isDel");
		//将已有核算员工清空
		if(StringUtils.equals("1",isDel)){
			String hasCmpSql = "select fid from T_HR_SCmpCalTable where FCALSCHEMEID ='$1' and FPERIODYEAR = $2 and FPERIODMONTH = $3  ";
			hasCmpSql = hasCmpSql.replace("$1",scalid);
			hasCmpSql = hasCmpSql.replace("$2",year);
			hasCmpSql = hasCmpSql.replace("$3",calschemeMonth+"");
			IRowSet hasPersonData = DbUtil.executeQuery(ctx,hasCmpSql);


			if(hasPersonData!=null && hasPersonData.size() > 0){
				try {
					StringBuffer ids = new StringBuffer("");
					while(hasPersonData.next()) {
						String hasPersonId = hasPersonData.getObject("fid").toString();
						ids.append("'"+hasPersonId+"',");
					}
					String idStr =ids.substring(0,ids.length()-1);
					Map<String, Object> delTaxCalMap = (Map) TaxCalInitFacadeFactory.getLocalInstance(ctx).deleteTaxCalPerson(idStr);
					HashSet<String> succListSet = (HashSet<String>)delTaxCalMap.get("succList");
					List<String> succList = new ArrayList<String>(succListSet);
					//List<String> succList = (List)delTaxCalMap.get("succList");
					// 获取当前的用户
					UserInfo currentUserInfo = ContextUtil.getCurrentUserInfo(ctx);
					// 获取当前登录的人员ID
					String personId = "";
					if (currentUserInfo.getPerson() != null) {
						personId = currentUserInfo.getPerson().getId().toString();
					}
					if (succList.size() > 0) {
						 CmpSchemePersonHasFacadeFactory.getLocalInstance(ctx).delete(permItemId, CmpStrUtil.convertListToString(succList), scalid,false,ctx.getCaller().toString());
					}
				} catch (SQLException e) {
					throw new BOSException(e.getMessage());
				}
			}

            /*if(hasPersonData!=null){
                try {
                    while(hasPersonData.next()) {
                       String hasPersonId = hasPersonData.getObject("fid").toString();
                        Map<String, Object> delTaxCalMap = (Map) TaxCalInitFacadeFactory.getLocalInstance(ctx).deleteTaxCalPerson("'"+hasPersonId+"'");
                        List<String> succList = (List)delTaxCalMap.get("succList");
                        if (succList.size() > 0) {
                            CmpSchemePersonHasFacadeFactory.getLocalInstance(ctx).delete(permItemId, CmpStrUtil.convertListToString(succList), scalid);
                        }
                    }
                } catch (SQLException e) {
                    throw new BOSException(e.getMessage());
                }
            }*/
		}

		//执行存储过程，整理需要添加的员工数据
		//oracle 写法
		//String proSql = "/*dialect*/begin pp_jl_getsalarylist ('$1','$2',$3,'$4'); end ;";
        String proSql = "/*dialect*/call pp_jl_getsalarylist ('$1','$2',$3,'$4');";
		//sqlserver 写法
		// String proSql = "exec pp_jl_getsalarylist '$1','$2',$3,'$4'";
		proSql = proSql.replace("$1",year);
		proSql = proSql.replace("$2",mouth);
		proSql = proSql.replace("$3",time+"");
		proSql = proSql.replace("$4",scalid);
		logger.error("into immediateAddPersonAction...proSql:"+proSql);
		DbUtil.execute(ctx,proSql);
		logger.error("into immediateAddPersonAction,after ...proSql:"+proSql);
		//将整理的数据，插入核算员工列表
		IRowSet personData = getPersonData(ctx,year,mouth,time,scalid);
		List<Map> dataList = new ArrayList();
		if(personData!=null){
			try {
				while(personData.next()) {
					Map<String,Object> personMap = new HashMap();
					personMap.put("person.id", personData.getObject("fpersonid"));
					personMap.put("person.number", personData.getObject("fempnumber"));
					personMap.put("person.name", personData.getObject("fempname"));
					personMap.put("emptype.id", personData.getObject("empType"));
					personMap.put("job.id", null);
					personMap.put("position.id", personData.getObject("fpositionid"));
					personMap.put("emporgrelation.id", personData.getObject("emporgrelation"));
					personMap.put("adminorgunit.id", personData.getObject("fadminorgid"));
					personMap.put("adminorgunit.longnumber", personData.getObject("adminNumber"));
					personMap.put("cmpemporelation.id", personData.getObject("cmpemporelation"));
					personMap.put("cmpemporelation.leffectdate", personData.getObject("cmpemporeleffedt"));
					personMap.put("cmpemporelation.usedefault", 1);
					dataList.add(personMap);
				}
			} catch (SQLException e) {
				throw new BOSException(e.getMessage());
			}
		}
		CmpSchemePersonFacadeFactory.getLocalInstance(ctx)
				.addPerson(permItemId, scalid, dataList);
		res.put("message", "执行成功");
		JSONUtils.SUCCESS(res);
		return null;
	}


	protected IRowSet getPersonData(Context ctx, String year, String month, int time, String scalid) throws BOSException{
		String sql = "select \n" +
				"empType,\n" +
				"emporgrelation,\n" +
				"adminNumber,\n" +
				"cmpemporelation,\n" +
				"cmpemporeleffedt,\n" +
				"fpersonid,\n" +
				"fempnumber,\n" +
				"fempname,\n" +
				"fadminorgid,\n" +
				"fpositionid,\n" +
				"fpositionname,\n" +
				"adminorgname,\n" +
				"displayname\n" +
				"from JL_gzmd_temp where pyear='$1' and pmonth='$2' and scalid='$3'";
		sql = sql.replace("$1",year);
		sql = sql.replace("$2",month);
		sql = sql.replace("$3",scalid);

		IRowSet result = null ;
		try {
			System.out.println("-------------------------需要核算的人sql-------------------");
			System.out.println(sql);
			result =  DbUtil.executeQuery(ctx, sql);
		} catch (BOSException e) {
			throw new BOSException(e.getMessage());
		}
		return result;
	}
}
