package nccloud.web.hrwa.pubinfo.wadataexplain.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.hrwa.wadataexplain.Wadataexplain;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.PubAppTool;
import nccloud.commons.collections.CollectionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.ClientInfo;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.framework.web.convert.translate.Translator;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.ui.pattern.grid.Grid;
import nccloud.framework.web.ui.pattern.grid.GridFormulaHandler;
import nccloud.web.action.NCCAction;
import nccloud.web.utils.GridModelConvertUtils;

/**复制上一期间*/
public class WadataexplainCopyLastPeriod extends NCCAction {


	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {
		IJson json = JsonFactory.create();
	    String read = request.read();
	    String areacode = "head";
	    Map<String,Object> map = json.fromJson(read, Map.class);
	    Map<String,Object> newmap = json.fromJson(map.get("model").toString(), Map.class);
	    if(null==newmap.get("reqpara"))
	    	ExceptionUtils.wrappBusinessException("参数reqpara不能为空，请检查");
	    if(null!=newmap.get("areacode"))
	    	areacode=newmap.get("areacode").toString();
	    Map<String,Object> reqpara = json.fromJson(newmap.get("reqpara").toString(), Map.class);
	    
	    //获取上一期间
	    List<Wadataexplain> result  = getLastperiodDatas(reqpara);

		
	    
		Grid grid = (Grid) para;
		
		GridModelConvertUtils gridConvUtl = new GridModelConvertUtils();

		if(CollectionUtils.isNotEmpty(result)) {
			
			grid = gridConvUtl.toGridOpe(WadataexplainConsts.pagecode, result.stream().toArray(Wadataexplain[]::new));
		}
		
		grid.getModel().setAreacode(areacode);
		// 处理显示公式
		GridFormulaHandler gridFormulaHandler = new GridFormulaHandler(grid);
		gridFormulaHandler.handleLoadFormula();
		// 翻译器，将主键翻译成名称
		Translator translator = new Translator();
		translator.translate(grid);
		return grid;
	}

	
	/**
	 * 获取上一期间数据
	 * @param reqpara
	 * @throws BusinessException 
	 */
	private List<Wadataexplain> getLastperiodDatas(Map<String, Object> reqpara) throws BusinessException {
		// TODO Auto-generated method stub
	    String pk_org = reqpara.get("pk_org").toString();
	    String pk_wa_class = reqpara.get("pk_wa_class").toString();
	    String cyearperiod = reqpara.get("cyearperiod").toString();
	    String copyear = cyearperiod.substring(0,4);//年
		String copperiod = cyearperiod.substring(4,6);//月
	    
	    String beforeyear = copyear;  
		String beformonth =  copperiod;
		
		if("01".equals(copperiod)){
			beformonth = "12";
			beforeyear= String.valueOf(Integer.parseInt(copyear)-1);
		}else if("12".equals(copperiod) || "11".equals(copperiod)){
			beformonth = String.valueOf(Integer.parseInt(copperiod)-1);
		}else{
			beformonth = "0"+String.valueOf(Integer.parseInt(copperiod)-1);
		}
	    
		// 校验用户信息
		ClientInfo clientInfo = SessionContext.getInstance().getClientInfo();
		String userid = clientInfo.getUserid();
		
		
		StringBuffer selectSql = new StringBuffer();//上一期间薪资发放说明的所有数据
		selectSql.append("pk_wa_class = '");
		selectSql.append(pk_wa_class);
		selectSql.append("' and def1 = '");
		selectSql.append(beforeyear+beformonth);
		selectSql.append("' and nvl(dr,0)=0 ");
		
		StringBuffer thiswadataSql = new StringBuffer();//本期间薪资方案的所有数据，即所有的人员
		thiswadataSql.append(" select wa_data.pk_psndoc, wa_data.pk_wa_data");
		thiswadataSql.append(" from wa_data");
		//thiswadataSql.append(" inner join bd_psndoc on wa_data.psnid = bd_psndoc.pk_psndoc");
		thiswadataSql.append(" where wa_data.pk_wa_class = '");
		thiswadataSql.append(pk_wa_class);
		thiswadataSql.append("' and wa_data.cyearperiod = '");
		thiswadataSql.append(copyear+copperiod);
		thiswadataSql.append("' and wa_data.stopflag = 'N'");
		List<Map<String, String>> thiswadataList = (List<Map<String, String>>)ServiceLocator.find(IUAPQueryBS.class).executeQuery(thiswadataSql.toString(), new MapListProcessor());
		Map<String,String> thiswadataMap = new HashMap<String,String>();//本期间薪资方案的人员编码-薪资方案PK
		if(thiswadataList!=null && thiswadataList.size()>0){
			for(int i=0;i<thiswadataList.size();i++){
				String pk_psndoc = thiswadataList.get(i).get("pk_psndoc");
				String pk_wa_data = thiswadataList.get(i).get("pk_wa_data");
				thiswadataMap.put(pk_psndoc, pk_wa_data);
			}
		}else{
			ExceptionUtils.wrappBusinessException("本期间薪资方案没有数据，请检查");
		}
		
		//获取对照关系 
		String sql = 
			"select wa_classitem.pk_wa_classitem,wa_item.pk_wa_item\n" +
			"  from wa_classitem\n" + 
			" inner join wa_item\n" + 
			"    on wa_classitem.pk_wa_item = wa_item.pk_wa_item\n" + 
			"    where nvl(wa_classitem.dr,0)=0\n" + 
			"    and nvl(wa_item.dr,0)=0\n" + 
			"    and wa_classitem.pk_org = '"+pk_org+"'\n" + 
			"    and wa_classitem.cyear='"+beforeyear+"'\n" + 
			"    and wa_classitem.cperiod='"+beformonth+"'\n" + 
			"    and wa_classitem.pk_wa_class='"+pk_wa_class+"'\n" + 
			" order by wa_item.code";

		List<Map<String, String>> thiswadataitemList = (List<Map<String, String>>)ServiceLocator.find(IUAPQueryBS.class).executeQuery(sql.toString(), new MapListProcessor());
		Map<String,String> lastwadataitemMap = new HashMap<String,String>();
		if(thiswadataitemList!=null && thiswadataitemList.size()>0){
			for(int i=0;i<thiswadataitemList.size();i++){
				String pk_wa_classitem = thiswadataitemList.get(i).get("pk_wa_classitem");
				String pk_wa_item = thiswadataitemList.get(i).get("pk_wa_item");
				lastwadataitemMap.put(pk_wa_classitem, pk_wa_item);
			}
		}else{
			ExceptionUtils.wrappBusinessException("上一期间没有设置薪资项目，请检查");
		}
		
		
		
		
		//String cuser =  SessionContext.getInstance().getClientInfo().getUserid();
		String powersql = "select wa_itempower.pk_itempower,\n" 
		        + "       wa_classitem.pk_wa_class,\n"
				+ "       wa_classitem.pk_wa_item,\n" 
		        + "       wa_classitem.name name,\n"
				+ "       wa_classitem.pk_wa_classitem,\n" 
		        + "       wa_itempower.editflag,\n"
				+ "       wa_itempower.moduleflag,\n" 
		        + "       wa_classitem.pk_org,\n"
				+ "       wa_classitem.pk_group,\n" 
		        + "       wa_itempower.ts,\n" 
				+ "       wa_classitem.ifromflag,\n"
				+ "       wa_itempower.subject_type,\n" 
				+ "       wa_itempower.pk_subject\n" 
				+ "   from wa_classitem\n"
				+ "   inner join wa_waclass\n" 
				+ "   on wa_waclass.pk_org = wa_classitem.pk_org\n"
				+ "   and wa_waclass.pk_wa_class = wa_classitem.pk_wa_class\n"
				+ "   and wa_waclass.cyear = wa_classitem.cyear\n"
				+ "   and wa_waclass.cperiod = wa_classitem.cperiod\n" 
				+ "   inner join wa_item\n"
				+ "   on wa_classitem.pk_wa_item = wa_item.pk_wa_item\n" 
				+ "   left outer join wa_itempower\n"
				+ "   on wa_itempower.pk_wa_item = wa_classitem.pk_wa_item\n"
				+ "   and wa_itempower.pk_wa_class = wa_classitem.pk_wa_class\n"
				+ "   and wa_itempower.pk_org = wa_classitem.pk_org\n" 
				+ "   and wa_itempower.pk_subject = '"+ userid + "'"
			    +" or pk_subject in ( SELECT sur.pk_role FROM sm_user_role sur where sur.cuserid = '"
				+ userid +"')\n" 
				+ "   where wa_waclass.pk_org = '"+pk_org+"' \n"
				+ "   and wa_waclass.pk_wa_class = '"+pk_wa_class+"'\n" 
				+ "   and wa_item.mid = 'N'\n"
				+ "   and wa_itempower.editflag ='Y'";

		List<Map<String, Object>> thisclassitemList = (List<Map<String, Object>>)ServiceLocator.find(IUAPQueryBS.class).executeQuery(powersql, new MapListProcessor());
		Map<String,String> thisclassitemMap = new HashMap<String,String>();//本期间薪资方案的人员编码-薪资方案PK
		if(thisclassitemList!=null && thisclassitemList.size()>0){
			for(int i=0;i<thisclassitemList.size();i++){
				Object pk_wa_classitem = thisclassitemList.get(i).get("pk_wa_classitem");
				Object vname = thisclassitemList.get(i).get("name");
				Object iitemid =  thisclassitemList.get(i).get("pk_wa_item");
				thisclassitemMap.put(String.valueOf(iitemid), String.valueOf(pk_wa_classitem));
			}
		}else{
			ExceptionUtils.wrappBusinessException("本期间没有可用的薪资发放项目或该操作人员无可用项目权限，请检查"); 
		}
		
		List<Wadataexplain> vos = (List<Wadataexplain>) ServiceLocator.find(IUAPQueryBS.class).retrieveByClause(Wadataexplain.class, selectSql.toString());
		List<Wadataexplain> volist = new ArrayList<Wadataexplain>();		
		if(CollectionUtils.isNotEmpty(vos)) {
			
			vos.forEach(vo->{
				String pk_psndoc = vo.getPk_psndoc();
				String pk_wa_classitem = vo.getPk_wa_classitem();
				String itemid = lastwadataitemMap.get(pk_wa_classitem);//先根据对照，把itemid拿出来 
				String thiswaitem = thisclassitemMap.get(itemid);//根据itemid拿出最新的waitem
				if(thiswadataMap.containsKey(pk_psndoc)&&!PubAppTool.isNull(thiswaitem)) {
					vo.setCreationtime(new UFDateTime());
					vo.setCreator(userid);
					vo.setCyear(copyear);
					vo.setCperiod(copperiod);
					vo.setDef1(copyear+copperiod);
					vo.setStatus(VOStatus.NEW);
					vo.setPk_wa_data_explain(null);
					vo.setPk_wa_classitem(thiswaitem);
					vo.setIscommit(UFBoolean.FALSE);
					vo.setIsquote(UFBoolean.FALSE);
					vo.setModifiedtime(null);
					vo.setModifier(null);
					volist.add(vo);
				}
				
			});
		}
		
		return volist;
	}

	@Override
	protected Class getParaClass() {
		return Grid.class;
	}
	
	
}
