package com.unis.flowable.server.controller;

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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.unis.common.utils.CurrentUtil;
import com.unis.common.utils.MapUtil;
import com.unis.common.utils.ResponseWrapper;
import com.unis.flowable.common.vo.HistoryApprovalVO;
import com.unis.flowable.common.vo.ItemFilterVO;
import com.unis.flowable.server.service.FlowTaskService;
import com.unis.flowable.server.service.HomePageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/homealready")
@Slf4j
@Api(value = "系统首页已办查询", tags = "系统首页已办查询")
@SuppressWarnings("all")
public class HomePageAlreadyController {

	@Autowired
	private HomePageService homeService;
	
	@Autowired
	private FlowTaskService flowTaskService;
	
	
	
	
	  /* @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
	 */
	@ApiOperation(value = "【粮食首页】查询已办事项", notes = "参数：起始页，每页展示行数")
	@PostMapping(value = "/queryCompleteItems/{page}/{size}")
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", value = "起始页", required = true),
			@ApiImplicitParam(name = "size", value = "每页展示行数", required = true) })
	public ResponseWrapper queryCompleteItems(
			@PathVariable("page") Integer page,
			@PathVariable("size") Integer size,
			@RequestBody ItemFilterVO itemFilterVO
	) {
		try {
			Map<String, Object> list = homeService.queryCompleteItems(page, size, itemFilterVO);
			return ResponseWrapper.success(200, "查询成功", list);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.error("【粮食首页】待办事项查询失败");
		}
	}
	
	  /**
     * 查询已办事项
     * @return ResponseWrapper
     * @author liyb
     * @date 2018-12-12 14:30:55
     * @version v1.0
     */
    @ApiOperation(value = "查询已办事项", notes = "主要参数：用户登录账号")
    @PostMapping(value = "/findAllCompleteItems/{page}/{size}")
    @ApiImplicitParams({ @ApiImplicitParam(name = "page", value = "起始页", required = true),
            @ApiImplicitParam(name = "size", value = "每页展示行数", required = true) })
    public ResponseWrapper findAllCompleteItems(@RequestBody ItemFilterVO itemFilterVO,@PathVariable Integer page,@PathVariable Integer size) {
        try {
            Map<String,Object> result = new HashMap<>();
            List<Map> mapList = new ArrayList();
            if(StringUtils.isEmpty(itemFilterVO.getUserId())){
                itemFilterVO.setUserId(CurrentUtil.getUserAccount());
            }

         /**
          * 省级储备粮承储资格申请表(粮食类)
          */
         String creditCode=CurrentUtil.getCreditCode();
         List<HistoryApprovalVO> findByAlreadyDoneoPage = flowTaskService.findByAlreadyDoneoPage(creditCode);
         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("starter", "");
                 map.put("desc", "");
                 map.put("creditCode", creditCode);
                 map.put("code","");
                 map.put("startTime",flow.get("startTime"));
                 map.put("endTime",flow.get("endTime"));
                 map.put("assignTime", flow.get("endTime"));
                 map.put("type", "6");
                 map.put("userCreditCode",flow.get("userCreditCode"));
                 mapList.add(map);
             }
         }
            // 模糊查询
            if (StringUtils.isNotEmpty(itemFilterVO.getProcName())) {
                mapList = searchLikeByCondition(itemFilterVO.getProcName(),"procName", mapList);
            }
            if (StringUtils.isNotEmpty(itemFilterVO.getBbq())) {
                mapList = searchLikeByCondition(itemFilterVO.getBbq(),"bbq", mapList);
            }
            Collections.sort(mapList, 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 ResponseWrapper.success(200, "查询已办事项成功", MapUtil.getMapForPage(mapList,page,size));
        } catch (Exception e) {
            e.printStackTrace();
           
            return ResponseWrapper.error( "查询已办事项失败");
        }
    }
    
    
    
	


	
}
