package com.xintong.visualinspection.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.xintong.visualinspection.bean.*;
import com.xintong.visualinspection.pojo.TaskListByDeptAppeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xintong.system.err.BusinessException;
import com.xintong.visualinspection.service.CheckAppealService;
import com.xintong.visualinspection.service.ScoreService;
import com.xintong.visualinspection.service.TaskService;
import com.xintong.visualinspection.util.AuthorUtil;
import com.xintong.visualinspection.util.CacheUtil;
import com.xintong.visualinspection.util.Constants;

/**
 * 文件名：TestController
 * 版本信息：日期：2017/3/30 Copyright 江苏省交通规划设计院 Corporation 2017 版权所有.
 */
@RestController
@RequestMapping("/task")
public class TaskController extends BaseController {

    @Autowired
    private TaskService taskService;
    @Autowired
    private CheckAppealService checkAppealService;
    @Autowired
    private ScoreService scoreService;
    
    /**
     * 添加考核任务
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/add")
    public String add(@Valid @RequestBody Task task){
    	taskService.insert(task);
    	return super.returnSuccessResult("添加成功");
    }
    
    /**
     * 修改考核任务
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/update")
    public String update(HttpServletRequest request,@Valid @RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	User user = getCurrentUser(request);
    	task.setUpdate_user(new Long(user.getId()));
    	taskService.update(task);
    	Task t = taskService.getById(task.getId());
    	return super.returnSuccessResult("修改成功",t);
    }
    
    @RequestMapping(value = "/taskEnd")
    public String taskEnd(HttpServletRequest request, @Valid @RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	if(task.getCheck_status()==null || "".equals(task.getCheck_status())){
    		task.setCheck_status(Constants.STATUS_CHECK_END);
    	}
    	User user = getCurrentUser(request);
    	task.setUpdate_user(new Long(user.getId()));
    	taskService.update(task);
    	if(task.getAppeal_result()!=null && task.getAppeal_id()!=null){
    		CheckAppeal checkAppeal = new CheckAppeal();
    		checkAppeal.setId(task.getAppeal_id());
    		checkAppeal.setAppeal_result(task.getAppeal_result());
    		checkAppealService.update(checkAppeal);
    	}
    	return super.returnSuccessResult("修改成功");
    }
    
    @RequestMapping(value = "/taskStart")
    public String taskStart(HttpServletRequest request,@Valid @RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	if(task.getCheck_status()==null || "".equals(task.getCheck_status())){
    		task.setCheck_status(Constants.STATUS_CHECK_START);
    	}
    	User user = getCurrentUser(request);
    	task.setUpdate_user(new Long(user.getId()));
    	taskService.update(task);
    	return super.returnSuccessResult("修改成功");
    }
    
    /**
     * 删除考核任务
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/delete")
    public String delete(@RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	taskService.delete(task.getId());
    	return super.returnSuccessResult("删除成功");
    }
    
    @RequestMapping(value = "/dispatch")
    public String dispatch(HttpServletRequest request, @RequestBody Task task){
    	if(task.getCheck_status()==null || "".equals(task.getCheck_status())){
    		task.setCheck_status(Constants.STATUS_CHECK_END);
    	}
    	
    	if(task.getUpdate_check_status()==null || "".equals(task.getUpdate_check_status())){
    		task.setUpdate_check_status(Constants.STATUS_CHECK_DISPATCH);
    	}
    	if(task.getDispatch_ids()!=null && task.getDispatch_ids().length>0){
    		List<Task> taskList = taskService.getTaskList(task);
    		List<TaskStatus> taskStatusList = new ArrayList<TaskStatus>();
    		User u = getCurrentUser(request);
    		for(Task t:taskList) {
    			//插入状态到表
    			TaskStatus status = new TaskStatus();
    			status.setTask_id(t.getId());
    			status.setUpdate_time(new Date());
    			status.setUpdate_user(new Long(u.getId()));
    			status.setUpdate_username(u.getTruename());
    			status.setCheck_status(task.getUpdate_check_status());
    			String name = (CacheUtil.codeMap.get("task_status_"+task.getUpdate_check_status())).getCode_name();
    			status.setCheck_status_name(name);
    			taskStatusList.add(status);
    		}
    		taskService.dispatch(task);
    		taskService.insertStatusBatch(taskStatusList);
    		return super.returnSuccessResult("下发成功");
    	}
    	return super.returnSuccessResult("下发失败，请选择需下发任务！");
    }
    
    @RequestMapping(value = "/dispatchById")
    public String dispatchById(HttpServletRequest request, @RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	if(task.getCheck_status()==null || "".equals(task.getCheck_status())){
    		task.setCheck_status(Constants.STATUS_CHECK_DISPATCH);
    	}
    	taskService.dispatchById(task);
    	
		//插入状态到表
		TaskStatus status = new TaskStatus();
		User u = getCurrentUser(request);
		status.setTask_id(task.getId());
		status.setUpdate_time(new Date());
		status.setUpdate_user(new Long(u.getId()));
		status.setUpdate_username(u.getTruename());
		status.setCheck_status(task.getCheck_status());
		String name = (CacheUtil.codeMap.get("task_status_"+task.getCheck_status())).getCode_name();
		status.setCheck_status_name(name);
    	taskService.insertStatus(status);
    	
    	return super.returnSuccessResult("下发成功");
    }
    
    @RequestMapping(value = "/dispatchAllNoScoreTask")
    public String dispatchAllNoScoreTask(HttpServletRequest request, @RequestBody Task task){
    	if(task.getCheck_status()==null || "".equals(task.getCheck_status())){
    		task.setCheck_status(Constants.STATUS_CHECK_END);
    	}
    	
    	if(task.getUpdate_check_status()==null || "".equals(task.getUpdate_check_status())){
    		task.setUpdate_check_status(Constants.STATUS_CHECK_DISPATCH);
    	}
    	if(task.getCheck_status()==Constants.STATUS_CHECK_END){
    		task.setHasScore(2);//无扣分
    		List<Task> taskList = taskService.getTaskList(task);
    		List<TaskStatus> taskStatusList = new ArrayList<TaskStatus>();
    		User u = getCurrentUser(request);
    		for(Task t:taskList) {
    			//插入状态到表
    			TaskStatus status = new TaskStatus();
    			status.setTask_id(t.getId());
    			status.setUpdate_time(new Date());
    			status.setUpdate_user(new Long(u.getId()));
    			status.setUpdate_username(u.getTruename());
    			status.setCheck_status(task.getUpdate_check_status());
    			String name = (CacheUtil.codeMap.get("task_status_"+task.getUpdate_check_status())).getCode_name();
    			status.setCheck_status_name(name);
    			taskStatusList.add(status);
    		}
    		taskService.dispatch(task);
    		taskService.insertStatusBatch(taskStatusList);
    		return super.returnSuccessResult("下发成功");
    	}
    	return super.returnSuccessResult("下发失败，请选择需下发任务！");
    }
    @RequestMapping(value = "/confirm")
    public String confirm(HttpServletRequest request, @RequestBody Task task){
    	if(task.getCheck_status()==null || "".equals(task.getCheck_status())){
    		task.setCheck_status(Constants.STATUS_CHECK_DISPATCH);
    	}
    	
    	if(task.getUpdate_check_status()==null || "".equals(task.getUpdate_check_status())){
    		task.setUpdate_check_status(Constants.STATUS_CHECK_CONFIRM);
    	}
    	if(task.getDispatch_ids()!=null && task.getDispatch_ids().length>0){
    		List<Task> taskList = taskService.getTaskList(task);
    		List<TaskStatus> taskStatusList = new ArrayList<TaskStatus>();
    		User u = getCurrentUser(request);
    		for(Task t:taskList) {
    			//插入状态到表
    			TaskStatus status = new TaskStatus();
    			status.setTask_id(t.getId());
    			status.setUpdate_time(new Date());
    			status.setUpdate_user(new Long(u.getId()));
    			status.setUpdate_username(u.getTruename());
    			status.setCheck_status(task.getUpdate_check_status());
    			String name = (CacheUtil.codeMap.get("task_status_"+task.getUpdate_check_status())).getCode_name();
    			status.setCheck_status_name(name);
    			taskStatusList.add(status);
    		}
    		taskService.dispatch(task);
    		taskService.insertStatusBatch(taskStatusList);
    		return super.returnSuccessResult("确认成功");
    	}
    	return super.returnSuccessResult("确认失败，请选择需确认任务！");
    }
    
    /**
     * 通过id获取考核任务
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/getById")
    public String getById(@RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	Task t = taskService.getById(task.getId());
    	return super.returnSuccessResult(t);
    }
    
    /**
     * 通过多条件获取考核任务
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/getTaskList/{page}/{size}")
    public String getTaskList(HttpServletRequest request, @PathVariable Integer page,@PathVariable Integer size, @RequestBody Task task){
    	PageHelper.startPage(page, size); 
    	User user = getCurrentUser(request);
    	if(AuthorUtil.hasRole(user, Constants.ROLE_STATION_ADMIN)
    			||AuthorUtil.hasRole(user, Constants.ROLE_STATION)
    			||AuthorUtil.hasRole(user, Constants.ROLE_STATION_AGENT)
    			||AuthorUtil.containsRole(user, "ROLE_STATION")){
    		task.setChecked_dept((long)user.getOrganid());
    	}else if(AuthorUtil.hasRole(user, Constants.ROLE_JICHA)){
    		task.setCheckman(new Long(user.getId()));
    	}
    	List<Task> taskList = taskService.getTaskList(task);
    	if(taskList==null) return super.returnSuccessResult(new PageInfo(new ArrayList()));
    	return super.returnSuccessResult(new PageInfo(taskList));
    }
    
    /**
     * 通过id获取状态
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/getStatusById")
    public String getStatusById(@RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	List<TaskStatus> tList = taskService.getTaskStatusList(task.getId());
    	return super.returnSuccessResult(tList);
    }
    /**
     * 删除用户被考核次数
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/deleteUserCount")
    public String deleteUserCount(@RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	taskService.deleteInvalidTaskCount(task.getId());
    	return super.returnSuccessResult("删除成功！");
    }
    
    /**
     * 更新用户被考核次数
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/updateUserCount")
    public String updateUserCount(@RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	taskService.updateInvalidTaskCount(task);;
    	return super.returnSuccessResult("修改成功！");
    }

    @RequestMapping(value = "/gettasklistbydept/{page}/{size}")
    public String getTaskListByDept(HttpServletRequest request, @PathVariable Integer page,@PathVariable Integer size,@RequestBody TaskListByDeptAppeal task){
        PageHelper.startPage(page, size);
        User user = getCurrentUser(request);
        List<Task> taskList = taskService.getTaskListByDept(task,user);

        if(taskList==null) return super.returnSuccessResult(new PageInfo(new ArrayList()));
        return super.returnSuccessResult(new PageInfo(taskList));
    }
    
    /**
     * 查询一个周期用户被考核次数
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/getUserCount")
    public String getUserCount(@RequestBody Task task){
    	if(task.getId()==null){
    		throw new BusinessException(20002);
    	}
    	List<UserClassCount> countList = taskService.getUserCount(task);
    	return super.returnSuccessResult(countList);
    }
    
    /**
     * 查询一个周期用户被考核任务详情
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/getUserCheckedTaskByPage/{page}/{size}")
    public String getUserCheckedTaskByPage(@PathVariable Integer page,@PathVariable Integer size,@RequestBody Task task){
    	List<Task> taskList = taskService.getTaskList(task);
    	List<Task> newTaskList = new ArrayList<Task>();
    	for(Task t:taskList) {
    		if(t.getCheck_status()!=Constants.STATUS_APPLY_SUCCEED){
    			newTaskList.add(t);
    			List<Score> scoreList = scoreService.getScoreListByTaskId(t.getId());
    			String score_details="";
    			if(scoreList!=null && scoreList.size()>0) {
    				for(Score s :scoreList){
    					score_details+=s.getContent()+";";
    				}
    			}else{
    				score_details="--";
    			}
    			t.setScore_details(score_details);
    		}
    	}
    	return super.returnSuccessResult(new PageInfo(newTaskList));
    }
}
