package com.xintong.visualinspection.controller.gettway;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xintong.system.err.BusinessException;
import com.xintong.visualinspection.bean.*;
import com.xintong.visualinspection.controller.BaseController;
import com.xintong.visualinspection.pojo.fwq.TaskData_F;
import com.xintong.visualinspection.service.CheckAppealService;
import com.xintong.visualinspection.service.CheckAppealService_F;
import com.xintong.visualinspection.service.TaskService_F;
import com.xintong.visualinspection.util.AuthorUtil;
import com.xintong.visualinspection.util.CacheUtil;
import com.xintong.visualinspection.util.Constants;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/f/task")
public class TaskController_F extends BaseController {

    @Reference(version = "1.0.0",
            application = "${dubbo.application.id}",
            registry = "${dubbo.registry.address}")
    private TaskService_F taskService_f;

    @Reference(version = "1.0.0",
            application = "${dubbo.application.id}",
            registry = "${dubbo.registry.address}")
    private CheckAppealService_F checkAppealService_f;

    @RequestMapping(value = "/getall/{page}/{size}")
    public String getall(HttpServletRequest request, @PathVariable Integer page, @PathVariable Integer size, @RequestBody FwqCheckTask fwqCheckTask) {
        User user = getCurrentUser(request);
        if (AuthorUtil.hasRole(user, Constants.ROLE_FWQ_ADMIN)
                || AuthorUtil.hasRole(user, Constants.ROLE_FWQ)
                || AuthorUtil.containsRole(user, "ROLE_FWQ")) {
            fwqCheckTask.setChecked_dept((long) user.getOrganid());
        } else if (AuthorUtil.hasRole(user, Constants.ROLE_JICHA)) {
            fwqCheckTask.setCheckman(new Long(user.getId()));
        }
        Object ss = taskService_f.getAllTask(page, size, fwqCheckTask);
        return super.returnSuccessResult(ss);
    }


    @RequestMapping(value = "/update")
    public String update(HttpServletRequest request, @Valid @RequestBody FwqCheckTask fwqCheckTask) {
        if (fwqCheckTask.getId() == null) {
            throw new BusinessException(20002);
        }
        User user = getCurrentUser(request);
        fwqCheckTask.setUpdate_user(new Long(user.getId()));
        taskService_f.updateStatus(fwqCheckTask);
        if(fwqCheckTask.getAppeal_result()!=null && fwqCheckTask.getAppeal_id()!=null){
            CheckAppeal_F checkAppeal = new CheckAppeal_F();
            checkAppeal.setId(fwqCheckTask.getAppeal_id());
            checkAppeal.setAppeal_result(fwqCheckTask.getAppeal_result());
            checkAppealService_f.update(checkAppeal);
        }
        FwqCheckTask t = taskService_f.getTask(fwqCheckTask);
        return super.returnSuccessResult("修改成功", t);
    }

    @RequestMapping(value = "/add")
    public String addtask(HttpServletRequest request, @Valid @RequestBody TaskData_F taskData_f) {
        if (taskData_f == null || taskData_f.getCheckAreaData() == null || taskData_f.getUserids() == null || taskData_f.getUserids().size() < 1 || taskData_f.getCheckAreaData().size() < 1) {
            throw new BusinessException(21502);
        }
        List<User> us = new ArrayList<>();
        for (String u : taskData_f.getUserids()
                ) {
            User user = CacheUtil.userMap.get(Long.valueOf(u));
            us.add(user);
        }
        taskData_f.setUsers(us);

        User user = getCurrentUser(request);
        taskData_f.setUser_id(user.getId());
        try {
            taskService_f.addTask(taskData_f);
        } catch (Exception e) {
            throw new BusinessException(21501);
        }

        return super.returnSuccessResult("添加成功", null);
    }

    @RequestMapping(value = "/getStatusById")
    public String getStatusById(@RequestBody Task task) {
        if (task.getId() == null) {
            throw new BusinessException(20002);
        }
        List<TaskStatus> tList = taskService_f.getTaskStatusList(task.getId());
        return super.returnSuccessResult(tList);
    }


    @RequestMapping(value = "/dispatch")
    public String dispatch(HttpServletRequest request, @RequestBody FwqCheckTask task) {
        if (task.getCheck_status() == null || "".equals(task.getCheck_status())) {
            task.setCheck_status(Constants.STATUS_CHECK_END);
        }

        if (task.getDispatch_ids() != null && task.getDispatch_ids().length > 0) {
            try {
                List<FwqCheckTask> taskList = (List<FwqCheckTask>) taskService_f.getAllTask(0, 0, task);
                List<TaskStatus> taskStatusList = new ArrayList<TaskStatus>();
                User u = getCurrentUser(request);
                for (FwqCheckTask t : taskList) {
                    t.setUpdate_user(u.getId().longValue());
                    t.setCheck_status(Constants.STATUS_CHECK_DISPATCH);
                    taskService_f.updateStatus(t);
                }
            } catch (Exception e) {
                return super.returnSuccessResult("下发失败，发生错误！");
            }
            return super.returnSuccessResult("下发成功");
        }
        return super.returnSuccessResult("下发失败，请选择需下发任务！");
    }

    @RequestMapping(value = "/dispatchById")
    public String dispatchById(HttpServletRequest request, @RequestBody FwqCheckTask 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);
        }
        User u = getCurrentUser(request);
        task.setUpdate_user(u.getId().longValue());
        taskService_f.updateStatus(task);
        return super.returnSuccessResult("下发成功");
    }

    @RequestMapping(value = "/dispatchAllNoScoreTask")
    public String dispatchAllNoScoreTask(HttpServletRequest request, @RequestBody FwqCheckTask task) {
        if (task.getCheck_status() == null || "".equals(task.getCheck_status())) {
            task.setCheck_status(Constants.STATUS_CHECK_END);
        }

        if (task.getCheck_status() == Constants.STATUS_CHECK_END) {
            task.setHasScore(2);//无扣分
            try {
                List<FwqCheckTask> taskList = (List<FwqCheckTask>) taskService_f.getAllTask(0, 0, task);
                List<TaskStatus> taskStatusList = new ArrayList<TaskStatus>();
                User u = getCurrentUser(request);
                for (FwqCheckTask c : taskList
                        ) {
                    c.setUpdate_user(u.getId().longValue());
                    c.setCheck_status(Constants.STATUS_CHECK_DISPATCH);
                    taskService_f.updateStatus(c);
                }
            } catch (Exception e) {
                return super.returnSuccessResult("下发失败，发生错误！");
            }

            return super.returnSuccessResult("下发成功");
        }
        return super.returnSuccessResult("下发失败，请选择需下发任务！");
    }

    @RequestMapping(value = "/confirm")
    public String confirm(HttpServletRequest request, @RequestBody FwqCheckTask task) {
        if (task.getCheck_status() == null || "".equals(task.getCheck_status())) {
            task.setCheck_status(Constants.STATUS_CHECK_DISPATCH);
        }


        if (task.getDispatch_ids() != null && task.getDispatch_ids().length > 0) {
            try {
                List<FwqCheckTask> taskList = (List<FwqCheckTask>) taskService_f.getAllTask(0, 0, task);
                List<TaskStatus> taskStatusList = new ArrayList<TaskStatus>();
                User u = getCurrentUser(request);
                for (FwqCheckTask t : taskList) {
                    t.setUpdate_user(u.getId().longValue());
                    t.setCheck_status(Constants.STATUS_CHECK_CONFIRM);
                    taskService_f.updateStatus(t);
                }

            } catch (Exception e) {
                return super.returnSuccessResult("确认失败，发生错误！");
            }
            return super.returnSuccessResult("确认成功");
        }
        return super.returnSuccessResult("确认失败，请选择需确认任务！");
    }

    @RequestMapping(value = "/taskEnd")
    public String taskEnd(HttpServletRequest request, @Valid @RequestBody FwqCheckTask 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_f.updateStatus(task);

        if(task.getAppeal_result()!=null && task.getAppeal_id()!=null){
            CheckAppeal_F checkAppeal = new CheckAppeal_F();
            checkAppeal.setId(task.getAppeal_id());
            checkAppeal.setAppeal_result(task.getAppeal_result());
            checkAppealService_f.update(checkAppeal);
        }
        return super.returnSuccessResult("修改成功");
    }
}
