package com.unis.flowable.server.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.unis.common.utils.CurrentUtil;
import com.unis.common.utils.DateUtil;
import com.unis.common.utils.MapUtil;
import com.unis.common.utils.ResponseWrapper;
import com.unis.flowable.common.vo.DeploymentVO;
import com.unis.flowable.common.vo.HistoryApprovalVO;
import com.unis.flowable.common.vo.ItemFilterVO;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@SuppressWarnings("all")
public class HomePageService {

	@Autowired
	FlowTaskService flowTaskService;
	
	/**
	 * 【粮食首页】查询待办事项
	 * @param page
	 * @param size
	 * @param itemFilterVO
	 * @return Map<String, Object>
	 * @author liyb
	 * @date 2019-05-10 11:01:30
	 * @version v1.0
	 */

	public Map<String, Object> findWaitItemForGrain(Integer page, Integer size, ItemFilterVO itemFilterVO) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map> itemArr = new ArrayList<>();
		ItemFilterVO filterVO = new ItemFilterVO();
		if(StringUtils.isEmpty(itemFilterVO.getUserId())){
			filterVO.setUserId(CurrentUtil.getUserAccount());
		}else{
			filterVO.setUserId(itemFilterVO.getUserId());
		}
		
		/**
		 * 省级储备粮承储资格申请表(粮食类)
		 */
		System.out.println("====================省级储备粮承储资格申请表======================");
		List<DeploymentVO> deploymentListList=new ArrayList();
		
		
		//组任务
		List<DeploymentVO> groupList= flowTaskService.getUserTaskGroupNoPage(CurrentUtil.getUserId(),CurrentUtil.getAreaCode());
		deploymentListList.addAll(groupList);
		
		//个人任务
		List<DeploymentVO> userList= flowTaskService.getUserTaskNoPage(CurrentUtil.getUserId());
		deploymentListList.addAll(userList);
		ResponseWrapper responseWrapperFlowAble = ResponseWrapper.success(deploymentListList);
		if(responseWrapperFlowAble.getInfoCode().intValue()==200) {
			  Object obj= responseWrapperFlowAble.getData();
              List parseObject = JSONObject.parseObject(JSONObject.toJSONString(obj), List.class);
              List<Map> resultDate = JSONObject.parseArray(JSONObject.toJSONString(parseObject), Map.class);
			for(Map flow:resultDate){
				Map map = new HashMap();
				map.put("actId","");
				map.put("taskId",flow.get("taskId"));
				map.put("procInstId", flow.get("procInsId"));
				map.put("procdefKey", flow.get("procdefKey"));
				map.put("actName", flow.get("taskName"));
				map.put("procName",flow.get("procdefName"));
				map.put("desc", "");
				map.put("code","");
				map.put("assignTime",flow.get("startTime"));
				map.put("creditCode", CurrentUtil.getAreaCode());
				map.put("businessType", "70");
				map.put("assigner", CurrentUtil.getOrgName());
				map.put("bbq", flow.get("bbq"));
				map.put("userCreditCode", flow.get("userCreditCode"));
				map.put("startTime", flow.get("startTime"));
				map.put("starter", flow.get("starter"));
				
				// 10  个人任务  20 组任务
				map.put("userTaskType", flow.get("userTaskType"));
				itemArr.add(map);
			}
		}
		// 模糊查询
		if (StringUtils.isNotEmpty(itemFilterVO.getProcName())) {
			itemArr = searchLikeByCondition(itemFilterVO.getProcName(),"procName", itemArr);
		}
		if (StringUtils.isNotEmpty(itemFilterVO.getStarter())) {
			itemArr = searchLikeByCondition(itemFilterVO.getStarter(),"starter", itemArr);
		}
		Collections.sort(itemArr, new Comparator() {
			@Override
			public int compare(Object o1, Object o2) {
				if (o1 instanceof Map && o2 instanceof Map) {
					Map e1 = (Map) o1;
					Map e2 = (Map) o2;
					if (!"".equals(e1.get("assignTime")) && null != e1.get("assignTime")
							&& !"".equals(e2.get("assignTime")) && null != e2.get("assignTime")) {
						if (e1.get("assignTime").toString().compareTo(e2.get("assignTime").toString()) > 0) {
							return -1;
						}
						if (e1.get("assignTime").toString().compareTo(e2.get("assignTime").toString()) == 0) {
							return 0;
						}
						if (e1.get("assignTime").toString().compareTo(e2.get("assignTime").toString()) < 0) {
							return 1;
						}
					} else {
						return -1;
					}
				}
				throw new ClassCastException("不能转换为JSONObject类型");
			}
		});
		return MapUtil.getMapForPage(itemArr,page,size);
	}
	
	

	/**
	 * @Description: 模糊查询
	 * @date 2019-05-10 14:04:54
	 * @author liyb
	 * @version v1.0
	 * @param name 条件名称
	 * @param list 要筛选的集合
	 * @return List
	 */
	private List<Map> searchLikeByCondition(String key,String value, List<Map> list) {
		List results = new ArrayList();
		Pattern pattern = Pattern.compile(key);
		for (int i = 0; i < list.size(); i++) {
			if(ObjectUtils.notEqual(list.get(i).get(value),null)){
				Matcher matcher = pattern.matcher(String.valueOf(list.get(i).get(value)));
				if (matcher.find()) {
					results.add(list.get(i));
				}
			}
		}
		return results;
	}
	
	
	/**
	 * 【粮食首页】查询已办事项
	 * @param page
	 * @param size
	 * @return ResponseWrapper
	 * @author liyb
	 * @date 2019-05-10 11:01:30
	 * @version v1.0
	 */
	
	public Map<String, Object> queryCompleteItems(
			Integer page, Integer size,
			ItemFilterVO itemFilterVO
	) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map> itemArr = new ArrayList<>();
		ItemFilterVO filterVO = new ItemFilterVO();
		if(StringUtils.isEmpty(itemFilterVO.getUserId())){
			filterVO.setUserId(CurrentUtil.getUserAccount());
		}else{
			filterVO.setUserId(itemFilterVO.getUserId());
		}
	
/**
 * 省级储备粮承储资格申请表(粮食类)
 */
     String userId=CurrentUtil.getUserId();
     List<HistoryApprovalVO> findByAlreadyDoneoPage = flowTaskService.findByAlreadyDoneoPage(userId);
     ResponseWrapper responseWrapperFlowAble = ResponseWrapper.success(200, "", findByAlreadyDoneoPage);
     if(responseWrapperFlowAble.getInfoCode().intValue()==200) {
	Object obj= responseWrapperFlowAble.getData();
    List parseObject = JSONObject.parseObject(JSONObject.toJSONString(obj), List.class);
    List<Map> resultDate = JSONObject.parseArray(JSONObject.toJSONString(parseObject), Map.class);
	for(Map flow:resultDate){
		Map map = new HashMap();
		map.put("actId","");
		map.put("taskId",flow.get("taskId"));
		map.put("procInstId", flow.get("procInsId"));
		map.put("procdefKey", flow.get("procdefKey"));
		map.put("actName", flow.get("taskName"));
		map.put("procName",flow.get("procdefName"));
		map.put("desc", "");
		map.put("creditCode", CurrentUtil.getAreaCode());
		map.put("code","");
		map.put("startTime",flow.get("startTime"));
		map.put("endTime",flow.get("endTime"));
		map.put("assignTime", flow.get("endTime"));
		map.put("businessType", "70");
		map.put("dealTime", 1);
		map.put("bbq", flow.get("bbq"));
		map.put("userCreditCode", flow.get("userCreditCode"));
		map.put("startTime", flow.get("startTime"));
		map.put("starter", flow.get("starter"));
		String start=flow.get("startTime").toString();
		String end=flow.get("endTime").toString();
		//两个字符串时间相减
		long st=DateUtil.turnStrDateToJavaUtilDate(start,DateUtil.df).getTime();
		long en=DateUtil.turnStrDateToJavaUtilDate(end,DateUtil.df).getTime();
		long tot=en-st;
		//耗时
		map.put("duration", DateUtil.secondToTime(tot));
		itemArr.add(map);
	}
}
		// 模糊查询
		if (StringUtils.isNotEmpty(itemFilterVO.getProcName())) {
			itemArr = searchLikeByCondition(itemFilterVO.getProcName(),"procName", itemArr);
		}
		if (StringUtils.isNotEmpty(itemFilterVO.getStarter())) {
			itemArr = searchLikeByCondition(itemFilterVO.getStarter(),"starter", itemArr);
		}
		Collections.sort(itemArr, new Comparator() {
			@Override
			public int compare(Object o1, Object o2) {
				if (o1 instanceof Map && o2 instanceof Map) {
					Map e1 = (Map) o1;
					Map e2 = (Map) o2;
					if (!"".equals(e1.get("assignTime")) && null != e1.get("assignTime")
							&& !"".equals(e2.get("assignTime")) && null != e2.get("assignTime")) {
						if (e1.get("assignTime").toString().compareTo(e2.get("assignTime").toString()) > 0) {
							return -1;
						}
						if (e1.get("assignTime").toString().compareTo(e2.get("assignTime").toString()) == 0) {
							return 0;
						}
						if (e1.get("assignTime").toString().compareTo(e2.get("assignTime").toString()) < 0) {
							return 1;
						}
					} else {
						return -1;
					}
				}
				throw new ClassCastException("不能转换为JSONObject类型");
			}
		});
		
		return MapUtil.getMapForPage(itemArr,page,size);
	}
	
}
