package nc.impl.hr.train;

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 java.text.ParseException;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.pa.PreAlertReturnType;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.bs.uap.lock.PKLock;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.vo.hi.cloud.train.CloudFinshDetailVO;
import nc.vo.hi.cloud.train.CloudKnowledgesVO;
import nc.vo.hi.cloud.train.CloudOnlineuserknowledge;
import nc.vo.pub.BusinessException;
/**
 * 员工所有线上学习记录到NCC后台表
 * @author chenzf
 * @date 2022-4-20 20:30:06
 * 
 */
public class CloudOnlineuserknowledgePlugin implements IBackgroundWorkPlugin {

	/**
	  * 获取两个日期相差多少个月
	  */
	public int getMonthSpace(String date1, String date2)
            throws ParseException {

        int result = 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();

        c1.setTime(sdf.parse(date1));
        c2.setTime(sdf.parse(date2));

        int i = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR);
        int month = 0;
        if (i<0)
        {
            month = -i*12;
        }else if(i>0)
        {
            month =  i*12;
        }
        result = (c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH)) + month;
        
        return result == 0 ? 1 : Math.abs(result);

    }
	
	@Override
	public PreAlertObject executeTask(BgWorkingContext arg0) throws BusinessException {
		PreAlertObject alertObj = new PreAlertObject();
		if(!PKLock.getInstance().addDynamicLock("CloudFinshDetailPlugin")) {
			alertObj.setReturnObj("任务执行中，请勿重复执行！");
			return alertObj;
	    }
		TrainCloudSchoolImpl impl = new TrainCloudSchoolImpl();
		Map<String,Object> bodyMap = impl.getBodyMap();
		Map map = arg0.getKeyMap();
		String updateDate = "";//"yyyy-MM-dd"
		String updateEndDate = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date today = new Date();//获取今天的日期
		Calendar c = Calendar.getInstance();
		c.setTime(today);
		int months = 0;//当前年到2020-01具体多少个月
		if(map.get("nums") != null && !"".equals(map.get("nums"))) {
			int nums = Integer.valueOf(arg0.getKeyMap().get("nums").toString());
			if(nums == 0) {
				try {
					months = getMonthSpace(sdf.format(c.getTime()),"2019-01-01");
				} catch (ParseException e) {
					e.printStackTrace();
				}
				updateEndDate = sdf.format(c.getTime());
				c.add(Calendar.DAY_OF_MONTH, -30);
				updateDate = sdf.format(c.getTime());
			} else {
				c.add(Calendar.DAY_OF_MONTH, -nums);
				updateDate = sdf.format(c.getTime());
				c.add(Calendar.DAY_OF_MONTH, 30-nums);
				updateEndDate = sdf.format(c.getTime());
				months = Integer.valueOf(arg0.getKeyMap().get("nums").toString());
			}
		} else {
			c.add(Calendar.DAY_OF_MONTH, -1);
			updateDate = sdf.format(c.getTime());
			c.add(Calendar.DAY_OF_MONTH, 30);
			updateEndDate = sdf.format(c.getTime());
		}
		BaseDAO dao = new BaseDAO();
		List<CloudOnlineuserknowledge> insertList = new ArrayList();
		List<CloudOnlineuserknowledge> updList = new ArrayList();
		if(months == 0) {
			bodyMap.put("updateDate", updateDate);
			bodyMap.put("updateEndDate", updateEndDate);
			Map<String,List<CloudOnlineuserknowledge>> resultMap = this.onlineuserknowledge(bodyMap, dao, impl);
			if(resultMap.size() > 0) {
				insertList.addAll(resultMap.get("insert"));
				insertList.addAll(resultMap.get("update"));
			}
		}else if(months > 0) {
			c.setTime(today);
			for(int i = 0; i < months; i++) {
				updateEndDate = sdf.format(c.getTime());
				c.add(Calendar.MONTH, -(i+1));
				updateDate = sdf.format(c.getTime());
				bodyMap.put("updateDate", updateDate);
				bodyMap.put("updateEndDate", updateEndDate);
				Map<String,List<CloudOnlineuserknowledge>> resultMap = this.onlineuserknowledge(bodyMap, dao, impl);
				if(resultMap.size() > 0) {
					insertList.addAll(resultMap.get("insert"));
					insertList.addAll(resultMap.get("update"));
				}
			}
		}
		
		alertObj.setMsgTitle("");
		if(insertList.size() > 0) {
			String[] pks = dao.insertVOList(insertList);
			alertObj.setReturnObj(pks);
			alertObj.setMsgTitle("新增员工所有线上学习记录"+pks.length+"条数据");
		}
		if(updList.size() > 0) {
			dao.updateVOList(updList);
			alertObj.setMsgTitle(alertObj.getMsgTitle()+"修改员工所有线上学习记录"+updList.size()+"条数据!");
		}
		
//		bodyMap.put("updateDate", updateDate);
//		bodyMap.put("updateEndDate", updateEndDate);
//		BaseDAO dao = new BaseDAO();
//		int totalPages = 0;
//		String result = impl.getOnlineuserknowledge(bodyMap, 1, 300);
//		if(StringUtils.isNotBlank(result)) {
//			JSONObject jsonObject = JSONObject.parseObject(result);
//			String code = jsonObject.getString("code");
//			List<CloudOnlineuserknowledge> insertList = new ArrayList();
//			List<CloudOnlineuserknowledge> updList = new ArrayList();
//			if("0".equals(code)) {
//				JSONObject data = jsonObject.getJSONObject("data");
//				JSONObject paging = data.getJSONObject("paging");
//				if(paging != null) {
//					totalPages = paging.getInteger("totalPages");//总页数
//					int totalCount = paging.getInteger("totalCount");//总条数
//				}
//				JSONArray jsonArray = data.getJSONArray("datas");//数据data
//				String sql = "select id,pk_onlineuserknowledge from cloud_onlineuserknowledge where nvl(dr,0) = 0";
//				List<Map<String,String>> listMap = (List<Map<String,String>>) dao.executeQuery(sql, new ColumnListProcessor());
//				List<String> list = new ArrayList();//存id的list
//				Map<String,String> idMap = new HashMap();//id为key，pk_kngcatalogs为value
//				if(list != null && list.size() >0) {
//					for(Map<String,String> m : listMap) {
//						list.add(m.get("id"));
//						idMap.put(m.get("id"), m.get("pk_onlineuserknowledge"));
//					}
//				}
//				if(jsonArray != null) {
//					List<CloudOnlineuserknowledge> vosList = JSONArray.parseArray(jsonArray.toJSONString().replaceAll("status", "cloudStatus"), CloudOnlineuserknowledge.class);
//					if(vosList != null) {
//						for(CloudOnlineuserknowledge vo : vosList) {
//							if(!list.contains(vo.getId())) {
//								insertList.add(vo);
//							}else {
//								vo.setPk_onlineuserknowledge(idMap.get(vo.getId()));
//								updList.add(vo);
//							}
//						}
//					}
//				}
//				if(totalPages > 1) {
//					for(int i = 2; i < totalPages+1;i++) {
//						result = impl.getOnlineuserknowledge(bodyMap, i, 300);
//						JSONObject ijsonObject = JSONObject.parseObject(result);
//						JSONObject datai = ijsonObject.getJSONObject("data");
//						String icode = ijsonObject.getString("code");
//						if("0".equals(icode)) {
//							JSONArray jsonArrayi = datai.getJSONArray("datas");//数据data
//							if(jsonArrayi != null) {
//								List<CloudOnlineuserknowledge> vosList = JSONArray.parseArray(jsonArrayi.toJSONString(), CloudOnlineuserknowledge.class);
//								//判断是否已存在中间表
//								if(vosList != null) {
//									for(CloudOnlineuserknowledge vo : vosList) {
//										if(!list.contains(vo.getId())) {
//											insertList.add(vo);
//										}else {
//											vo.setPk_onlineuserknowledge(idMap.get(vo.getId()));
//											updList.add(vo);
//										}
//									}
//								}
//							}
//						}
//					}
//				}
//			}
//			alertObj.setMsgTitle("");
//			if(insertList.size() > 0) {
//				String[] pks = dao.insertVOList(insertList);
//				alertObj.setReturnObj(pks);
//				alertObj.setMsgTitle("新增员工所有线上学习记录"+pks.length+"条数据");
//			}
//			if(updList.size() > 0) {
//				dao.updateVOList(updList);
//				alertObj.setMsgTitle(alertObj.getMsgTitle()+"修改员工所有线上学习记录"+updList.size()+"条数据!");
//			}
//		}
		alertObj.setReturnType(PreAlertReturnType.RETURNMESSAGE);
		return alertObj;
	}
	
	public Map<String,List<CloudOnlineuserknowledge>> onlineuserknowledge(Map<String,Object> bodyMap,BaseDAO dao,TrainCloudSchoolImpl impl) throws BusinessException{
		Map<String,List<CloudOnlineuserknowledge>> resultMap = new HashMap();
		int totalPages = 0;
		String result = impl.getOnlineuserknowledge(bodyMap, 1, 300);
		if(StringUtils.isNotBlank(result)) {
			JSONObject jsonObject = JSONObject.parseObject(result);
			String code = jsonObject.getString("code");
			List<CloudOnlineuserknowledge> insertList = new ArrayList();
			List<CloudOnlineuserknowledge> updList = new ArrayList();
			if("0".equals(code)) {
				JSONObject data = jsonObject.getJSONObject("data");
				JSONObject paging = data.getJSONObject("paging");
				if(paging != null) {
					totalPages = paging.getInteger("totalPages");//总页数
					int totalCount = paging.getInteger("totalCount");//总条数
				}
				JSONArray jsonArray = data.getJSONArray("datas");//数据data
				String sql = "select id,pk_onlineuserknowledge from cloud_onlineuserknowledge where nvl(dr,0) = 0";
				List<Map<String,String>> listMap = (List<Map<String,String>>) dao.executeQuery(sql, new ColumnListProcessor());
				List<String> list = new ArrayList();//存id的list
				Map<String,String> idMap = new HashMap();//id为key，pk_kngcatalogs为value
				if(list != null && list.size() >0) {
					for(Map<String,String> m : listMap) {
						list.add(m.get("id"));
						idMap.put(m.get("id"), m.get("pk_onlineuserknowledge"));
					}
				}
				if(jsonArray != null) {
					List<CloudOnlineuserknowledge> vosList = JSONArray.parseArray(jsonArray.toJSONString().replaceAll("status", "cloudStatus"), CloudOnlineuserknowledge.class);
					if(vosList != null) {
						for(CloudOnlineuserknowledge vo : vosList) {
							if(!list.contains(vo.getId())) {
								insertList.add(vo);
							}else {
								vo.setPk_onlineuserknowledge(idMap.get(vo.getId()));
								updList.add(vo);
							}
						}
					}
				}
				if(totalPages > 1) {
					for(int i = 2; i < totalPages+1;i++) {
						result = impl.getOnlineuserknowledge(bodyMap, i, 300);
						JSONObject ijsonObject = JSONObject.parseObject(result);
						JSONObject datai = ijsonObject.getJSONObject("data");
						String icode = ijsonObject.getString("code");
						if("0".equals(icode)) {
							JSONArray jsonArrayi = datai.getJSONArray("datas");//数据data
							if(jsonArrayi != null) {
								List<CloudOnlineuserknowledge> vosList = JSONArray.parseArray(jsonArrayi.toJSONString().replaceAll("status", "cloudStatus"), CloudOnlineuserknowledge.class);
								//判断是否已存在中间表
								if(vosList != null) {
									for(CloudOnlineuserknowledge vo : vosList) {
										if(!list.contains(vo.getId())) {
											insertList.add(vo);
										}else {
											vo.setPk_onlineuserknowledge(idMap.get(vo.getId()));
											updList.add(vo);
										}
									}
								}
							}
						}
					}
				}
				resultMap.put("insert", insertList);
				resultMap.put("update", updList);
			}else {
				throw new BusinessException(jsonObject.getString("message"));
			}
		}
		return resultMap;
	}

}
