package nccloud.web.hrhi.psndoc.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.mozilla.javascript.edu.emory.mathcs.backport.java.util.Collections;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import nc.itf.hi.IPsndocTrainService;
import nc.vo.hi.psndoc.TrainVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pub.lang.UFLiteralDate;
import nc.vo.uif2.LoginContext;
import nccloud.base.exception.ExceptionUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.web.hr.pub.HRCommonAction;
import nccloud.web.hr.pub.HRNccUtils;
import nccloud.web.uapbd.commons.web.ParamUtils;

public class TrainImportInDBAction extends HRCommonAction {

	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {
		ParamUtils param = new ParamUtils(request);
	    LoginContext loginContext = HRNccUtils.getLoginContext(param);
	    
	    List list = param.getList("datas", null);
	    if (null == list || list.isEmpty()) {
	      ExceptionUtils.wrapBusinessException("没有可导入的数据");
	    }
	    
	    TrainVO[] trainVOs = new TrainVO[list.size()];
	    Set<String> set = new HashSet<String>();
	    for (int i = 0; i < list.size(); i++) {
	        JSONObject obj = JSON.parseObject(JSON.toJSONString(list.get(i)));
	        TrainVO vo = new TrainVO();
	        vo.setPk_psndoc(obj.getString("pk_psndoc"));
	        vo.setAct_name(obj.getString("act_name"));
	        if (StringUtils.isNotBlank(obj.getString("begindate"))) {
	        	vo.setBegindate(new UFLiteralDate(obj.getString("begindate")));
	        }
	        if (StringUtils.isNotBlank(obj.getString("enddate"))) {
	        	vo.setEnddate(new UFLiteralDate(obj.getString("enddate")));
	        }
	        vo.setTra_type(obj.getString("tra_type"));
	        vo.setTra_mode(obj.getString("tra_mode"));
	        vo.setTraim(obj.getString("traim"));
	        vo.setTra_content(obj.getString("tra_content"));
	        vo.setTrm_location(obj.getString("trm_location"));
	        if(StringUtils.isNotBlank(obj.getString("tra_time"))) {
	        	vo.setTra_time(new UFDouble(obj.getString("tra_time")));
	        }
	        if(StringUtils.isNotBlank(obj.getString("tra_cost"))) {
	        	vo.setTra_cost(new UFDouble(obj.getString("tra_cost")));
	        }
	        vo.setContcode(obj.getString("contcode"));
	        vo.setTrm_certif_code(obj.getString("trm_certif_code"));
	        vo.setTrm_certif_name(obj.getString("trm_certif_name"));
	        if (StringUtils.isNotBlank(obj.getString("certificate_date"))) {
	        	vo.setCertificate_date(new UFLiteralDate(obj.getString("certificate_date")));
	        }
	        vo.setCertificate_unit(obj.getString("certificate_unit"));
	        vo.setSource_type(obj.getInteger("source_type"));
	        if (StringUtils.isNotBlank(obj.getString("signon_dt"))) {
	        	vo.setSignon_dt(new UFLiteralDate(obj.getString("signon_dt")));
	        }
	        vo.setTaketrm_method(obj.getInteger("taketrm_method"));
	        vo.setEntrepreneur(obj.getString("entrepreneur"));
	        vo.setAssist_unit(obj.getString("assist_unit"));
	        vo.setPurveyor(obj.getString("purveyor"));
	        if (StringUtils.isNotBlank(obj.getString("isallduty"))) {
	        	vo.setIsallduty(new UFBoolean(obj.getBoolean(("isallduty"))));
	        }
	        vo.setAbsence_count(obj.getInteger("absence_count"));
	        if(StringUtils.isNotBlank(obj.getString("ass_result"))) {
	        	vo.setAss_result(new UFDouble(obj.getString("ass_result")));
	        }
	        vo.setAss_option(obj.getString("ass_option"));
	        vo.setMemo(obj.getString("memo"));
	        vo.setAct_code(obj.getString("act_code"));
	        
	        vo.setPk_group(loginContext.getPk_group());
	        vo.setPk_org(loginContext.getPk_org());
	        vo.setPsnCode(obj.getString("psnCode"));
	        vo.setPsnName(obj.getString("psnName"));
	        String[] names = vo.getAttributeNames();
	        for(String key : names) {
	        	if(key.contains("glbdef")) {
	        		vo.setAttributeValue(key, obj.get(key));
	        	}
	        }
	        trainVOs[i] = vo;
	    }
	    
	    int importBefLen = trainVOs.length;
//	    Arrays.sort(trainVOs);
	    Collections.sort(Arrays.asList(trainVOs), new Comparator<TrainVO>() {
			@Override
			public int compare(TrainVO vo1, TrainVO vo2) {
				if(vo1.getBegindate().compareTo(vo2.getBegindate()) > 0) {
					return -1;
				}else {
					return 1;
				}
			}
	    	
	    });
	    
	    IPsndocTrainService service = (IPsndocTrainService)ServiceLocator.find(IPsndocTrainService.class);
	    TrainVO[] failtureReports = service.importData2DB(trainVOs, loginContext);
	    
	    int importAftLen = failtureReports.length;
	    StringBuffer sbMessage = new StringBuffer();
	    sbMessage.append("成功导入条数：{"+(importBefLen - importAftLen)+"}，导入失败条数：{"+importAftLen+"}。");
	    sbMessage.append("\n");
	    Arrays.sort(failtureReports);
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("message", sbMessage.toString());
	    if (importAftLen > 0) {
	      sbMessage.append("失败原因请参考最后的【失败原因】一列。\\n 错误数据已经导出，请修改后重试！");
	      map.put("errorNum", Integer.valueOf(importAftLen));
	      map.put("errorDatas", failtureReports);
	    } 
	    return map;
	    
	}

}
