package com.chinaitop.depot.intelligent.ventilation.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.chinaitop.depot.intelligent.ventilation.model.BusinessApproval;
import com.chinaitop.depot.intelligent.ventilation.model.BusinessApprovalExample;
import com.chinaitop.depot.intelligent.ventilation.model.BusinessApprovalExample.Criteria;
import com.chinaitop.depot.intelligent.ventilation.service.BusinessApprovalService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value="/intelligents/approval")
@Api(value= "ApprovalController", description = "审批管理")

public class ApprovalController {
	@Resource
	private BusinessApprovalService businessApprovalService;

	@RequestMapping(value="/getList",produces = MediaType.APPLICATION_JSON_VALUE,  method=RequestMethod.GET)
	@ApiOperation(value="获取审批列表", notes = "查询数据列表，支持分页")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
		@ApiImplicitParam(name = "userId", value = "当前登录人id", paramType = "query"),
		@ApiImplicitParam(name = "projectId", value = "业务单据id", paramType = "query"),
		@ApiImplicitParam(name = "orderByClause", value = "排序方式", paramType = "query")
	})
    public PageInfo<BusinessApproval> getList(Integer pageNum,Integer pageSize,String type, BusinessApproval businessApproval,Integer userId ,Integer projectId, String taskType, String orderByClause) {
    	BusinessApprovalExample businessApprovalExample=new BusinessApprovalExample();
    	if (null != orderByClause && !"".equals(orderByClause)) {
    		businessApprovalExample.setOrderByClause(" apply_time " + orderByClause); //创建时间
    	}
    	Criteria createCriteria = businessApprovalExample.createCriteria();
    	/*if (null != userId && !"".equals(userId)) {
    		createCriteria.andOperatorEqualTo(userId.toString());
    	}*/

    	if ("todo".equals(type)) {
    		//createCriteria.andResultEqualTo("待审批");
    		createCriteria.andResultNotEqualTo("同意");
    		createCriteria.andResultNotEqualTo("拒绝");
    		createCriteria.andResultNotEqualTo("已审批");
    		createCriteria.andResultNotEqualTo("审批结束");
    	} else if("complete".equals(type)) {
    		//createCriteria.andResultNotEqualTo("待审批");
    		createCriteria.andResultNotEqualTo("驳回");
    		createCriteria.andResultNotEqualTo("待审批");
		}
    	if (null != taskType && !"".equals(taskType)) {
    		createCriteria.andTaskTypeEqualTo(taskType);
    	}
    	
    	if (businessApproval.getProjectName()!=null && !"".equals(businessApproval.getProjectName())) {
    		createCriteria.andProjectNameLike("%"+businessApproval.getProjectName()+"%");
    	}
    	if (businessApproval.getApplyName()!=null && !"".equals(businessApproval.getApplyName())){
    		createCriteria.andApplyNameLike("%"+businessApproval.getApplyName()+"%");
    	}
    	if(businessApproval.getTaskId()!=null && !"".equals(businessApproval.getTaskId())){
    		createCriteria.andTaskIdEqualTo(businessApproval.getTaskId());
    	}
    	if (projectId != null){
    		createCriteria.andProjectIdEqualTo(projectId);
    	}
    	
    	if (null != pageNum && null != pageSize) {
    		PageHelper.startPage(pageNum, pageSize);
    	}
        List<BusinessApproval> queryByExample = businessApprovalService.queryByExample(businessApprovalExample);
        PageInfo<BusinessApproval> pageInfo = new PageInfo<BusinessApproval>(queryByExample);
        return pageInfo;
    }

	@RequestMapping(value="/getListSize", produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.GET)
	@ApiOperation(value="获取审批列表总数，为首页提供", notes = "获取审批列表总数")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "当前登录人id", paramType = "query")
	})
    public int getListSize(String type, BusinessApproval businessApproval,Integer userId ,HttpServletRequest request) {
    	/*UserInfo userInfo= (UserInfo) request.getSession().getAttribute("userInfo");
    	Integer userId = userInfo.getUserId();*/
    	BusinessApprovalExample businessApprovalExample=new BusinessApprovalExample();
    	Criteria createCriteria = businessApprovalExample.createCriteria();
    	createCriteria.andOperatorEqualTo(userId.toString());
    	//createCriteria.andResultEqualTo("待审批");
    	createCriteria.andResultNotEqualTo("同意");
		createCriteria.andResultNotEqualTo("拒绝");
		createCriteria.andResultNotEqualTo("已审批");
		createCriteria.andResultNotEqualTo("审批结束");
        List<BusinessApproval> queryByExample = businessApprovalService.queryByExample(businessApprovalExample);
        //待办理共有多少条数据
        int size = queryByExample.size();
        return size;
    }

	@RequestMapping(value="/update", produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
    @ApiOperation(value="更新流程轨迹表数据", notes = "更新流程轨迹表数据")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "businessApproval", value = "数据字符串", paramType = "form"),
		@ApiImplicitParam(name = "approvalStatus", value = "审批状态", paramType = "form")
	})
    public Map<String, Object> update(String businessApproval, Integer approvalStatus) {
    	Map<String, Object> map = new HashMap<String, Object>();

    	ObjectMapper mapper = new ObjectMapper();
    	BusinessApproval Approval = null;
    	try {
			Approval = mapper.readValue(businessApproval, BusinessApproval.class);

			//先将前面的审批数据的result刷成已审批
    		BusinessApprovalExample businessApprovalExample=new BusinessApprovalExample();
        	Criteria criteria = businessApprovalExample.createCriteria();
        	
        	if(Approval.getProjectId()!=null){
        		criteria.andProjectIdEqualTo(Approval.getProjectId());
        	}
        	if(Approval.getTaskType()!=null){
        		criteria.andTaskTypeEqualTo(Approval.getTaskType());
        	}
        	if(Approval.getTaskId()!=null){
        		criteria.andTaskIdEqualTo(Approval.getTaskId());
        	}
        	if(Approval.getTaskType()!=null){
        		criteria.andTaskTypeEqualTo(Approval.getTaskType());
        	}
        	businessApprovalExample.setOrderByClause(" id  asc ");

        	List<BusinessApproval> list = businessApprovalService.queryByExample(businessApprovalExample);
        	if (null != list && list.size() > 0) {
        		for (BusinessApproval obj_list : list) {
        			BusinessApproval approval_obj = obj_list;
        			approval_obj.setResult("已审批");
            		businessApprovalService.updateByPrimaryKeySelective(approval_obj);
        		}
        	}

        	/* 把新的轨迹数据插入 */
			businessApprovalService.add(Approval);

			if (4 == approvalStatus || approvalStatus == 0 || approvalStatus == 6) {
				//将当前单号的所有轨迹数据刷为审批结束
				list = businessApprovalService.queryByExample(businessApprovalExample);
				if (null != list && list.size() > 0) {
	        		for (BusinessApproval obj_list : list) {
	        			BusinessApproval approval_obj = obj_list;
	        			if (4 == approvalStatus || approvalStatus == 6) {
	        				approval_obj.setResult("审批结束");
	        			} else if (approvalStatus == 0) {
	        				approval_obj.setResult("已审批");
	        			}
	            		businessApprovalService.updateByPrimaryKeySelective(approval_obj);
	        		}
	        	}
			}
	    	map.put("status", "success");
		} catch (IOException e) {
			System.err.println("》》》提交流程异常》》》提交流程异常》》》》提交流程异常》》》提交流程异常》》》》》提交流程异常》》》》》提交流程异常》》》》提交流程异常》》》》提交流程异常");
			e.printStackTrace();
		}

        return map;
    }

	@RequestMapping(value="/removeList", produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
    @ApiOperation(value="删除流程轨迹表数据", notes = "更新流程轨迹表数据")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "projectId", value = "业务数据ID", paramType = "form"),
		@ApiImplicitParam(name = "taskType", value = "任务类型", paramType = "form")
	})
    public Map<String, Object> removeList(Integer projectId, String taskType) {
    	Map<String, Object> map = new HashMap<String, Object>();

    	try {
    		BusinessApprovalExample businessApprovalExample=new BusinessApprovalExample();
        	Criteria criteria = businessApprovalExample.createCriteria();
        	criteria.andProjectIdEqualTo(projectId);
        	if ("1".equals(taskType)) {
        		criteria.andTaskTypeEqualTo("fumigationProgram");
        	} else if ("2".equals(taskType)) {
        		criteria.andTaskTypeEqualTo("storageAeration");
        	}

        	businessApprovalService.removeList(businessApprovalExample);
	    	map.put("status", "success");
		} catch (Exception e) {
			e.printStackTrace();
		}

        return map;
    }

}
